Selling per-node access without creating two entities I want to create a Pay-per-view site under Drupal.

I followed the instructions of Commerce guys, which combines the use of Drupal Commerce and Content access.

But this solution means creating two entities: a product display + the paying article. It raises several problems: two nodes with the same name, two nodes as we can comment...

I would thus want only one node, with a visible teaser before purchase, then all the text after purchase.

My question : how to selling per-node access without creating two entities ?

It really depends on how you want to display the content to your customers. For example, you could show a teaser of the content page via Views. Access to the full content page could be contingent on node access implemented via the Content Access module. You then just have to figure out how to display to the customer which articles they have full access to - for example, a "Purchased articles" View that shows all fully accessible articles using a node access filter.


how to publish a node content to the walll of a Facebook account? Just wondering if is there any module to let publish a node content (title, body and images) to the wall of a Facebook account?

check Fridge for a fast solution. wont post the whole content, though. (and i wonder how that would be done)


How to merge two views block result to a single block I installed the flag module. Created two flag entities node(for node pages) and term(for taxonomy term pages). Created 2 different views with block display. The requirement is to display latest 10 favorites. As of now i am showing the term view in header of node view and limited both to show latest 5 favorites(5 from each). But this will not fulfill my requirement. I need to merge these two views results to  a single one and to show the latest 10 favorites from both. Is there any way to do it.

May be this can help you.

You can use  https://www.drupal.org/project/views_field_view module to embed view in another view as a field.

Or You can create a custom block and merge both views. To get the views in your custom code you can use views_embed_view() or module_invoke();

check for more information
https://www.drupal.org/node/1034524
https://api.drupal.org/api/views/views.module/function/views_embed_view/7


Contact form doesn't send mail I am using the contrib contact module to add a contact form.

I created a category in /admin/structure/contact to add the recipient. I added my person address mail (It's valid).

When I test the form, Drupal returns a confirm notification to say that the mail is send successfully.. But the mail is not received.

In /admin/reports/dblog, any error is reported.

PS: I use in my site other functions to send mail and it's received.

Any idea please?

Thank you..

I used the webform to create a contact form and mails are send


Getting custom body class from node field I would need to get a custom body class, so that admin can set the class. At the moment I have field on page node type where I try to get it. The code what I have is below but it doesn't seem to work that smoothly. Something it prints two body classes (like this <body class="classes comes here" class="another set of classes">) It's in template.php and preprocess_html function.

$node = menu_get_object();
if ($node && isset($node->nid)) {

    $field_bClass = field_get_items('node', $node, 'field_bClass');

    if (!empty($field_bClass)) {
        $field_field_bClass_output = field_view_value('node', $node, 'field_bClass', $field_bClass[0], array(
            'type' => 'value'
        ));

        $vars['classes_array'][] = $field_field_bClass_output['#markup'];

    }
}

Is that corrrect and what should be done difrently?

function TEMPLATE_preprocess_html(&$vars) {
    $node = menu_get_object();
    if ($node && isset($node->nid)) {
        $field_body_class = field_get_items('node', $node, 'field_body_class');

        if (isset($field_body_class[0]['value'])) {
            $vars['classes_array'][] = $field_body_class[0]['value'];
        }
    }
}

This is how it would look today in Drupal 7, assuming your field name is what it is in the example. (The difference with the other answer being instead of $vars['attributes_array']['class'][] using $vars['classes_array'][])


Set parent for programmatically created menu links I'm currently programmatically generating a menu and menu links inside it. This is working but I'm having trouble setting the parents for the links. Here is my current code

    $langcode = 'es';
    if (empty($menu_id)) {return ['#markup' => 'menu not specified'];}
    $menu = \Drupal::entityTypeManager()->getStorage('menu')
        ->create([
            'langcode' => $langcode,
            'status' => TRUE,
            'label' => $menu_id,
            'id' => $menu_id,
            'description' => 'this menu was created programmatically',
        ])->save();

    $items = [
        '1' => 'item 1',
        '2' => 'item 2',
        '3' => 'item 3',
    ];
    $parent = NULL;
    foreach ($items as $id => $title) {
        if ($id == '2') {$parent = '1';} else { $parent == NULL;}
        $menu_link = MenuLinkContent::create([
            'title' => $title,
            'link' => ['uri' => 'internal:/node/' . $nid],
            'menu_name' => $menu_id,
            'expanded' => true,
            'langcode' => $langcode,
            'status' => TRUE,
            'parent' => $parent,
        ]);

        $menu_link->save();
        var_dump($menu_link->getParentId());
    }

This line

var_dump($menu_link->getParentId());

is actually displaying the correct parent. But when visiting the menu in the admin page the parent is not set and is at the top level of the menu. Is there a specific issue with my code? How would you set the parent of a programmatically generated menu link?

Turns out when setting the parent you don't use the id of the menu_link_content you use the 'menu_link_content:' followed by the uuid of the link. Here's an example of a properly formatted parent field.

  'menu_link_content:0025c274-4db3-4745-b51e-714c998b5a50'

I fixed the code like so

    foreach ($items as $id => $title) {
        if ($id == '2') {
            $parent = 'menu_link_content:' . $previous_menu_link->uuid();
        } else {
            $parent == NULL;
        }

        $menu_link = MenuLinkContent::create([
            'title' => $title,
            'link' => ['uri' => 'internal:/node/' . $nid],
            'menu_name' => $menu_id,
            'expanded' => true,
            'langcode' => $langcode,
            'status' => TRUE,
            'parent' => $parent,
        ]);

        $menu_link->save();
        $previous_menu_link = $menu_link;
    }


Update Webform Submission from subsequent form on confirmation page I am trying to update a webform submission from a form on the confirmation page. My callback function is as follows, but it's not updating the submission. What is the correct syntax to accomplish this? I'm getting the webform node and the submission are loaded correctly but the webform_submission_update is not updating the record. What am I doing wrong?

$nid = 3389;
$webform = node_load(3389);
$sid = $form['sid']['#default_value'];
module_load_include('inc', 'webform', 'includes/webform.submissions');
$submission = webform_get_submissions($nid, $sid);
$email = check_plain($form['your-email']['#value']);
$submission->data[14]['value'][0] = $email;
webform_submission_update($webform, $submission);

Looks like you are you using the wrong function, rather then retrieving a single webform submission you are retrieving multiple entries.

$nid = 3389;
$webform = node_load(3389);
$sid = $form['sid']['#default_value'];
module_load_include('inc', 'webform', 'includes/webform.submissions');
$submission = webform_get_submission($nid, $sid); // note function name
$email = check_plain($form['your-email']['#value']);
$submission->data[14]['value'][0] = $email;
webform_submission_update($webform, $submission);


How to read data from nodes and display in this complex table? I have some nodes in my site

Day         Color   Type    Value
01-01-2018  blue    A       4
02-01-2018  yellow  B       3
02-01-2018  orange  C       2
03-01-2018  red     B       8

I need to show this data in the following way (NOT USING VIEWS):

Does anyone knows if it's possible using the table theme in Drupal?
I don't think it's possible to have the double header either.

Is there any other way to achieve this?

You'll have to flatten the data yourself, as you're grouping by date (you'd have to regardless of the double header and colspans), but yes, theme_table can accommodate that.

I haven't tested this but it should be at least near to working. The key points to note are colspan, which does what you'd think, and header, which will mark a cell to be rendered as <th> rather than <td>. Meaning you can stuff the second row of headers into the body. Not ideal, as they'll be inside a <tbody>, but I suspect good enough.

$header = [
  [
    'data' => '',
    'colspan' => 2,
  ],
  [
    'data' => 'Type',
    'colspan' => 3,
  ],
];

$rows = [
  [
    [
      'data' => 'Day',
      'header' => TRUE,
    ],
    // Other header rows here, with 'header' => TRUE
  ]
];

// Loop through your grouped data
foreach ($data as $item) {
  $rows[] = [
    $item->date,
    $item->colours,
    $item->type_a,
    $item->type_b,
    $item->type_c,
  ];
}

$build = [
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
];


How can I change comment text to "DELETED" instead of actually deleting the comment? I'm using threaded comments on my Drupal 7 site, and I'd like to be able to publicly preserve the fact that so-and-so commented here, and these were the replies. However, when a comment is deleted, all the replies are removed too. When a comment is deleted, I want the comment text to be changed to "DELETED" instead of actually deleting the comments.

I know about the un-publishing and hidden-comment kind of solutions, but I'd like the specific functionality I described instead of a workaround like those.

I use module Comment Delete, rewritten for Drupal 7.
Here is the code that is responsible for what you need:

$num_replies = db_query('SELECT COUNT(cid) FROM {comment} WHERE pid = :cid AND status = :status', array(':cid' => $comment->cid, ':status' => COMMENT_PUBLISHED))->fetchField();
if ($num_replies) {
  $comment->comment_body[LANGUAGE_NONE][0]['value'] = t('[The comment subject/body has been deleted, all replies will remain]');
  comment_save($comment);
  drupal_set_message(t('The comment subject/body has been deleted, all replies will remain.'));
}
else {
  comment_delete($comment->cid);
  drupal_set_message(t('The comment has been deleted.'));
}


Why wrap lines in plain emails? Drupal adds line breaks after a width of 77 in the function wrapMailLine() of the class core/lib/Drupal/Core/Mail/MailFormatHelper.php.

What is the reason for that?

If you open the mail in a small viewport like on a phone, e.g. the line breaks after 50 chars and then again after 27 chars. This behavior is undesired.

Because of RFC2822 (Internet Message Format), section 2.1.1 (Line Length Limits):

  There are two limits that this standard places on the number of
     characters in a line. Each line of characters MUST be no more than
     998 characters, and SHOULD be no more than 78 characters, excluding
     the CRLF.

Why they chose 77 and not 78 for Drupal, I don't know, but I'd bet my house the decision was originally based on that standard.


Override a function in a contrib module My company received a maintenance contract for a website developed in Drupal 7. The Drupal 7 website uses the Quiz contrib module, ver. 7.x-4.0-rc10. The module is used to implement a feature where authenticated users answer questions to tests.

When an authenticated user completes the test and views his result, the following notice errors are displayed on the results page,

Notice: Undefined index: nid in quiz_take_quiz() (line 2078 of C:\wamp64\www\........\modules\contrib\quiz\quiz.module).
Notice: Undefined index: vid in quiz_take_quiz() (line 2078 of C:\wamp64\www\........\modules\contrib\quiz\quiz.module).
Notice: Trying to get property 'type' of non-object in quiz_take_quiz() (line 2082 of C:\wamp64\www\........\modules\contrib\quiz\quiz.module).
Notice: Undefined index: in quiz_take_quiz() (line 2082 of C:\wamp64\www\........\modules\contrib\quiz\quiz.module).
Notice: Trying to get property 'is_valid' of non-object in quiz_take_quiz() (line 2084 of C:\wamp64\www\........\modules\contrib\quiz\quiz.module).

The Quiz module has a function, quiz_take_quiz($quiz).

As part of contract signed by my company, I have to resolve all notices. Therefore, what I intend to do is override this function and modify the exact line which is responsible for throwing the above notices (line no. 2078) and add a variable validation there.

However being a newbie to Drupal development I don't know where to start and what to do. I do know that modifying the code in a contrib module is not the best practice. I have hidden the path to the .module file with ........ to maintain privacy.

Can anyone please provide me the solution to this?

After going through all of your replies and a few internal discussions in my company, I have decided to modify the Quiz module's code by creating and applying a patch, quiz_notice_messages_in_result_screen.patch.

As per the information provided by Alfred Armstrong's the said patch will be solely used for our company's internal purposes, so as to find a way around the Drupal's general practice of reporting a contrib module's issues and suggesting patches for the same.

Below are the contents of the quiz_notice_messages_in_result_screen.patch file.

diff --git a/modules/contrib/quiz/quiz.module b/modules/contrib/quiz/quiz.module
index dd2b88c..e551aac 100644
--- a/modules/contrib/quiz/quiz.module
+++ b/modules/contrib/quiz/quiz.module
@@ -2075,13 +2075,19 @@ function quiz_take_quiz($quiz) {
     $_SESSION['quiz_' . $quiz->nid]['quiz_questions'][0]['rid'] = $_SESSION['quiz_' . $quiz->nid]['result_id'];
     $_SESSION['quiz_' . $quiz->nid]['previous_quiz_questions'][] = $_SESSION['quiz_' . $quiz->nid]['quiz_questions'][0];
     $former_question_array = array_shift($_SESSION['quiz_' . $quiz->nid]['quiz_questions']);
+    if (empty($former_question_array['nid']) || empty($former_question_array['vid'])) {
+      $former_question_array['nid'] = $quiz->nid;
+      $former_question_array['vid'] = $quiz->vid;
+    }
     $former_question = node_load($former_question_array['nid'], $former_question_array['vid']);

     // Call hook_evaluate_question().
     $types = _quiz_get_question_types();
-    $module = $types[$former_question->type]['module'];
+    $module = empty($types[$former_question->type]['module']) ? '' : $types[$former_question->type]['module'];
     $result = module_invoke($module, 'evaluate_question', $former_question, $_SESSION['quiz_' . $quiz->nid]['result_id']);
-    $q_passed_validation = $result->is_valid;
+    if(isset($result->is_valid)) {
+      $q_passed_validation = $result->is_valid;
+    }
     $check_jump = TRUE;
     if ($q_passed_validation === TRUE) {
       quiz_store_question_result($quiz, $result, array('set_msg' => TRUE, 'question_data' => $former_question_array));

Thank you No Sssweat, Alfred Armstrong and Alan Dixon for your inputs.


Upgrading Drupal 7.43 to 8 error: Source database is Drupal version 8 but version 7 was selected I am new to Drupal, but I am trying to upgrade a site with the version 7.43 to 8, flowing these steps: https://www.drupal.org/docs/8/upgrade/upgrade-using-web-browser

After installing the Migrate modules and defining the source site, I have the following error message:

  Source database is Drupal version 8 but version 7 was selected.

In my old site's database, the drupal_version table is empty.

Any help?

I managed to solve it.
It was caused be an update on PHP, that caused blank pages or “white screen of death” (WSOD) in the admin, too.
After updateing to 7.59, everithing was OK.
This article helped me: https://www.drupal.org/node/158043


Customizing search results page to use template.php and search-results.tpl.php I'm using Drupal 7, the basic Drupal search tool. I like what it returns as far as the actual node pages. However, I want to customize the main search results page that shows a list of results after a user enters a term to search by.

Right now it shows a list with a linked title to the node (fine), and then a 'summary' (if you can call it that) that's sort of a jumbled mess of the URL, part of the description field, and some other fields. I just want the description to show up there. I'd also like to add the date field and the associated image for the node in the search results. So I've discovered that I need to customize template.php mytheme_preprocess_search_results function and also search-results.tpl.php (results NOT result).

But I can't figure out how to parse out individual items from what the database is returning so I can make sure to only print those out in the tpl file. I did a var_dump on $search_results and see it returns a big 'ol chunk of HTML and database data...but how do I return just individual fields from the database and print those out?

Right now it just does a print $search_results.

I tried print $title and print $url but drupal complains it doesn't recognize those vars. So what are the vars and how can I use them to display what I want?

I'm also noticing it's showing the author and date for each node in the search results (although I hid this information in the content type)...so I'd also like to hide that information in the search results.

I've found a bunch of stuff online that led me to those two files I referenced, for changing the search results...but nothing that specifically addressed how to grab and use individual fields from the database. I also don't want to use a module, I want to do this with template.php and the tpl.php files if possible.

Thanks for your help in advance!

To change the snippet (that jumbled mess you mention), use theme_preprocess_search_result() (you want to override each search result, not the page of search results). Explicitly set $variables['snippet'] to the value you want to display.

A common tactic is to use the node's teaser view.

function mytheme_preprocess_search_result($variables) {
  $teaser = node_view($variables['result']['node'],'teaser');
  $variables['snippet'] = drupal_render($teaser);
}

You can manage the node's teaser in Admin -> Structure -> Content Types -> Your content type -> Manage Display -> Teaser as always.

There's a no-code approach also. While you're managing displays, check out the expandable fieldset for 'Custom display settings' and check the one for 'Search results highlighting input'. Here you can control the fields you want to display, but Drupal will still show only a snippet, and it will highlight where in the node your search terms show up. Ditch the preprocess function in this case.

Here is one more example with the theme_preprocess_search_result() function that shows the first 160 characters of the body field: https://alastaira.wordpress.com/2011/01/07/customising-the-search-results-snippet-in-drupal-7/ (note that this one does not check for language).


sort comments descending programmatically I want to sort all comment descending  programmatically, I found this Comments sorted by oldest first but I dont want use those modules or views solution.
anybody know how can I sort comment descending programmatically?
I means comments in below node(contents) , first ideal is get comments related to node by query and set orderby DESC  but everything show reversed in thread mode, replies come above comment !!!.

<?php
$query = db_select('comment') ->fields('comment', array('cid')) ->condition('nid', arg(1), '=');
$query->orderBy('created', 'DESC');
$result = $query->execute();
$cids = $result->fetchCol();
$comments=comment_load_multiple($cids);
foreach($comments as $comment)  {
  //do some stuff with the comment
}
?>


What is the best practice to index remaining content with solr? First please forgive me if this a recurrent question (I cannot find a solution otherwise).
I want to avoid waiting my cron to index remaining content with solr.
What is the best solution to have all the content automatically indexed??

I have done an alternative solution: I have created a cron job on my server where I run every two minutes the drush solr-index command.

What do you think about this solution? (Is it heavy to call every 2 minutes even if no content found?)

Thanks for your advices

The Apache Solr configuration page (/admin/config/search/apachesolr) provides a button under actions to index all queued content, which should send everything left in the queue. That can put a great deal of load on your server, so you should only use that option with some thought about how/if it will effect your users.

When I did a large import recently I went ahead and pushed it all the Solr as quickly as possible, but I was able to do that before the site went live. That meant that when users arrived the search index was complete.  If I'd had to do it while it was in production I would have spread it out to make sure the server was very responsive when they first started to use it.

The load that comes from extra cron runs is site specific. Some sites you can't really see the effects other sites it can have a noticeable slowdown from cron runs. I have worked with sites with light cron loads (or powerful servers) that run cron once a minute to allow functions like the Solr index or external data syncs stay very close to current. The 'right' answer here depends on your site, your server, and your users.

Also remember that you do not benefit from having cron run faster than it takes for an individual cron run to complete. If you have your Solr sync setup to send lots of large files for indexing in each pass it is possible your cron runs take more than two minutes.


Change all article text format to basic html I installed Drupal 8 on my site and used migrate to migrate my old site Drupal 6 to Drupal 8.

The error message pop out.

But when total articles have been all imported to new site Drupal 8.

The content of the article is not displaying. Only title of article shown.

I checked the article, there is content there.

It needs to be change from text format FULL HTML to BASIC HTML to make it appear on the site.

I have more than 20,000 articles.
How do I do change it for all?

Is it adding the script here and press "Format"?

While you might just need to add/configure the full_html text format, you can update the text format for all body fields to basic_html via a DB query ( and clear cache )

db_update('node__body')
  ->fields(array('body_format' => 'basic_html'))
  ->condition('bundle', 'article')
  ->execute();

db_update('node_revision__body')
  ->fields(array('body_format' => 'basic_html'))
  ->condition('bundle', 'article')
  ->execute();

The raw SQL equivalent (e.g for PHPMyAdmin) is:

UPDATE node__body set body_format = 'basic_html' where bundle = 'article';
UPDATE node_revision__body set body_format = 'basic_html' where bundle = 'article';

Backup your database first


Allowing anonymous users to contact node authors I want anonymous users to send messages to node authors. Also I want the sent messages to be visible to node authors in their user account. Here is what I have tried so far:

Private message - Solves what I am looking for but does not work for anonymous users
Webforms - New to it but I don't see a way for node authors to access the sent messages within their account

I'm pretty sure this can be done by combining the core Contact module with the Contact Storage module.
Steps to implement

Enable the Contact module and give anonymous the permission Use users' personal contact forms.
Enable the Contact Storage module and create a view showing Contact message. Configure a contextual filter with the user ID so that only messages to the logged-in user are displayed.


Untag/Remove a taxonomy term from a node I am inserting and updating node programmatically in drupal 7.When am updating I want to delete the taxonomy terms tagged in that particular node and have to insert new terms.

Please help me to untag the taxonomy terms of that node.the unset($node->taxonomy_field) is not working.Can anyone help me?

With Views Bulk Operations for Drupal 7, you can execute arbitrary PHP scripts.

In order to bulk-delete a specific taxonomy term, you can make a View that shows all content with the particular term you want to remove: Be sure to add a Relationship in the View like "Content: Taxonomy terms on node" so you can filter out content with the terms you want to keep.

Then in the same View, you'd add a VBO field to execute an arbitrary PHP script. VBO no longer uses $node but rather $entity, so you can pass through the following script modified from Dave Parrish's answer above (where field_name_of_taxonomy_term would be the name of the Term Reference or Entity Reference field where you save the taxonomy terms on the node):

for ($i = 0; count($entity->field_name_of_taxonomy_term[$entity->language]) > $i; $i++) {
    if ($entity->field_name_of_taxonomy_term[$entity->language][$i]['tid'] == 'TID to Remove') {
        unset($entity->field_name_of_taxonomy_term[$entity->language][$i]);
    break;
    }
}
node_save($entity);


How to implement jQuery Accordion for a Menu? I'm looking to implement something like the Accordion Menu module, but unfortunately that module has issues with Menu Block and other modules... so what's the best way to implement the jQuery Accordion menu with primary and secondary links, from a theming perspective? Should be a simple question for a themer, but I haven't found any specific tutorials that can take me step by step.

Using Drupal 7, Adaptive Theme.

update: thanks for all the responses. I'll look at all of the suggestions and provide another update :-)

Madam Adam's solution: not working correctly yet

  Only got it to work with this modification; added to js file

(function ($) {
//add drupal 7 code
Drupal.behaviors.myfunction = {
    attach: function(context, settings) {
//end drupal calls

//some jquery goodness here...
$( "#accordion" ).accordion( {
  header: "li",
  collapsible: true
} );

}}})
(jQuery);

You have to include the accordion library by adding this line to your theme's template.php:

drupal_add_library('system', 'ui.accordion');

Then you trigger the accordion by adding this to yout template.php or an external js-file:

$( "#menu-container" ).accordion( {
  header: "li",
  collapsible: true
} );


Drupal pager in views I have a view created for product categories, now I want pager, I configure the settings by displaying specified num of items instead of all items, now I am getting the specified num of items on a page but not getting the pager when I added more than specified number of items?

In view, select full/mini pager & do necessary settings. Please check screeshots below

Change pager type

Change settings


Displaying a block on a content profile page passing the content profile nid into the block I have a view block. It takes an argument to filter the content. The argument is the nid of a content profile. I then use a relationship to get the uid of the content profile. This uid means I only returns nodes related to the user of the content profile.

I wish to display this block on the users content profile page. So there would be a block listing nodes from the same user on there content profile. I am displaying the block using context.

What is the best way to get the filtering to occur. I currently am passing an argument which gets the nid of the content profile from the url. I have been told that I can do this by using spaces and contexts and not my custom php. How would you do this>

Add an argument of type Node[nid] to your views

Configure Action to take if argument is not present for Provide default argument as PHP Code

Add following code in the text area

  $node = node_load((int)arg(1));
  return $node->uid;


Make website visible only to registered users - create invitation system to allow registration So, my problem is two-fold:

I want to have a beta version of my website that I'll make available only to some friends, but I also want to give those friends the option of inviting other friends through some kind of invitation system (e.g. like Gmail did it back in 2004 when it first started).
I need to deny access to all content of my website if someone does not have an account.

So, ideally, I want to have a front page with a simple logo and a login form along with some text that allows the guest to enter an email address and be notified about the site going live (or get in some kind of queue). Of course, I also want to keep track of these requests/subscriptions.

So, is there a solution for this kind of functionality in Drupal? I guess I could write custom code and/or use extensive theming to achieve all these goals but I was wondering if there is a ready-made combination of modules that I can use and I'm obviously missing.

See, the Request Invitation module will likely do your job
For this one, first create a new user role @ admin/people/permissions/roles (something like "Premium Users" or "Special Group" or "Only Friends" or something that makes sense). Then use the Content Access module to only allow people from the above mentioned user role to see particular contents.

Then copy the contents of page.tpl.php into a new file named page--front.tpl.php and start editing. This will theme for the front page only, where you can now add a form for the requests and so on.


Get latest revision vid in views I'm using the revisioning module to handle the status of nodes. As far as the nodes go, they've been working perfect and the work flow is exactly what I want. However, I'm running into an issue when trying to construct a view.

What I'm able to do so far:

Create the view
Set the node type
Limit it to only nodes that have pending revisions

(I get the two nodes with pending revisions (an unpublished rev)

Get the nid of the node

Where I'm having issues:

I try to select the vid of the pending revision, but instead I get the vid of the currently published revision.

I'm not sure where to go. I've tried using "Type: Content" and "Type: Content revision" and get the exact same behavior. I've tried playing with Relationships and still get the same behavior, but I don't think a relationship touches what I need.

... This is incredibly irritating because I'm obviously getting the pending nodes that I want, I'm just not getting the vid for what's pending (which is what my filter uses to get those nodes in the first place) and instead getting it for what's published.

I can imagine there might be some headache because it's possible to have multiple pending revisions, in that case, I should see two lines for that one nid since nid and vid /should/ be unique.

Instead of views_php use something like this. Add it as a field - you just need a custom handler to call the revisioning function that returns the latest vid.

/*
* Implements hook_views_data_alter().
*/
function MYMODULE_views_data_alter(&$data) {
  $data['node_revision']['latest_revision'] = array(
    'title' => t('Latest revision'),
    'help' => t('Get the latest vid.'),
    'group' => t('Content revision'),
    'real field' => 'nid',
    'field' => array(
      'handler' => 'MYMODULE_field_handler_latest_revision',
      'click sortable' => TRUE,
    ),
  );
}

And the handler:

/**
 * Provide the latest revision number from the nid field.
 */
class MYMODULE_field_handler_latest_revision extends views_handler_field {

  // Return latest vid as the field value.
  public function render($values) {
    $value = $this->get_value($values);
    return revisioning_get_latest_revision_id($value);
  }
}


empty ajax block not loaded on cached page Drupal 6 user.
I came across interesting problem: I would like to use ajax block on cached pages on my webshop. The block would display some products which other customers have bought along with products inside current customers cart.
The tricky part is that this ajax block is initially empty, so after warming all pages in cache, this block is not rendered by drupal. Which means that ajax can not be working with this block.

My question is: how can I render the block even it is initially empty? The block is made in views, I tried to add attachment displaying some data, so there would be some content inside the block, but the block is not rendered anyway.

Thank you for help

My solution was to create a view where I displayed random node element (i.e. title) in a block and in the same view I attached the attachment display to the block, which contains the fields that should sit in ajax block. Finally I hid the block with css rule. This way the block get's rendered in theme.


{{ content.field_test }} doesn't work in node.html.twig I created a field whose machine name is field_test. I want to show this field in node.html.twig, but when I use {{ content.field_test }}, {{ content.field_test.value }}, or {{ content.field_test[0] }} the field is not printed.

How can I achieve this in Drupal 8.3.5?

Uninstalling Field Layout module will solve this. (tested with Drupal 8.6.10, using subtheme built on Barrio Bootstrap 4).


Remove contributor role when user deletes all of his content I have the following problem that I don't seem to be able to solve myself:

Today user BRIAN feels like creating some content, let's say 5 articles. I created a rule using the RULES MODULE that automatically assigns him the role CONTRIBUTOR after creating the first article.

Tomorrow Brian will realize that 4 of his articles weren't that great, and he decides to delete them. No problem, there is still one article out there authored by him and Brian is still a contributor! HOWEVER, as soon as Brian also deletes his very last piece of contributed content, I want him to lose his contributor role.

How do I put this into a rule?

On Brian's user profile, there is a VIEWS block listing all of Brian's content. The RULES BONUS PACK (http://drupal.org/project/rb) would let me check the number of results of this block and remove his contributor role as soon as the number of results drops down to 0. However, the module is still in development and I really don't want to use a dev-version on a productive website.

I read somewhere that the VIEWS BULK OPERATIONS module could do the job, but I really wouldn't know how. Could someone give me a hint, please?

Checkout the rules bonus pack

  Conditions

  Check number of results from a view: This condition loads a view and checks   the number of results – condition is passed if it is at least
  as many results   as you set. You can pass on arguments to the view.


Views - Change view based on number of results With Views, can you change the display of the view depending on the number of nodes being displayed?

For example:
Let say you are using views to override a taxonomy page.
If the taxonomy page has only one node present, then the one node should be displayed in full.
However, if the taxonomy page has more than one node, then a list of nodes should be displayed (so the user click on the node they want.)

Is this possible with views?

(This question applies to Drupal 7).

The only way I can think to do this will require some views, and a little code:

Build view that gets the list of nodes as Node IDs (nids) for a given taxonomy term.
Then build a view that gets your nodes and has filters as needed. It should take multiple, comma separated nids as an argument.

a: Add a display (block, pane, whatever type you need) that shows nodes in full, but limit it to one row.
b: Add another display that handles the list version.

With these building blocks you can call the appropriate Views display using some code. You can write this and either put it in in your own module, custom theme or simply add PHP snippet into a node or custom Panel pane.

The pseudocode looks like this:

call the first view and get the result with $result = views_get_view_result()
count() how many rows are returned in $results, set $single_result = TRUE accordingly.
take the $results array and turn it in to a comma-separated string of nids with implode(',', $result)
If there's a $single_result then embed the view display for a single full node in the page and pass it $results as an argument, like so: views_embed_view('your_view_name, 'your_full_view_display_name', $results)
If there's not a $single_result then embed the view display for multiple entries, with $results passed to it.

The above has most of the core functions you'll need... I'll leave it to you to turn this into proper code!


Rules: Load List of Entities by Object or Entity ID (Performance) I'm looking to load a list of Users by an Entity Reference Property within Rules. There may be times when I need to load hundreds or thousands of Users that have a matching Property to update a secondary Property. I'm having a difficult time determining the best performance option.

Here's my use case:

Users within our website may be linked to a Company (stored as a Node with Content-Type: company). When any user of this Company purchases membership, the company Node is updated with a Taxonomy Term Reference "Member." Then, every employee (read: User with entity reference to the same company node) of that organization needs to have a Taxonomy Reference field within their account updated to reflect they are a "Member (Corp)."

My Rules Based Solutions (that is executed when the order is first Paid In Full that sets the Data Value for that Property of the Company node, then...):

Solution A (Rules without VBO View):

Fetch all User Entities By Property: company, where company = Company node.
Loop through User list.
Check that Entity has Field: "Membership Status."
Set Data Value: "Membership Status" = "Member (Corp)."

Solution B (Rules with: Load a List of Entities from a VBO View):

Pass nid as parameter to view.
Loop through returned List.
Check that Entity has Field: "Membership Status."
Set Data Value: "Membership Status" = "Member (Corp)."

Solution C (Rules with: Load a List of Entity IDs from a VBO View):

Pass nid as parameter to view.
Loop through returned List.
Fetch User Entity by ID.
Check that Entity has Field: "Membership Status."
Set Data Value: "Membership Status" = "Member (Corp)."

I'm hesitant to load up every Entity that matches due to Performance implications; however, being fairly new to Drupal, I'm not sure the most efficient method to bulk update all of the affected Users.

Can you help me better understand the performance implications of these solutions? Perhaps, I'm missing a better option that I haven't considered? Thanks in advance for your help!

*This question is in reference to Drupal 7.

Using Solution A will pretty sure have performance implications, so I wouldn't recommend that approach "to load hundreds or thousands of Users". Below is a blueprint of yet another approach (another option that you could considered, up to you to decide if it is "better"), which will allow you to reduce the performance risk significantly ...

Step 1 - Refine your view

Adapt the VBO view you already have, by limiting the results of that view to the first X users only. Pick a value for X that fits your needs, to start make it small enough and increase later on as much as you feel comfortable with.

Also adapt the views filter, to no longer include the users that have been processed already (by the Rules Component described in the next steps).

Step 2 - Create a Rules Component

Create a custom Rules Component which performs the Rules Actions as in your Solution "B" or "C". If the value of X is small enough, you can do some experiments with either of these solutions (B or C), i.e. to find out what happens if you increase the value of X (and based on that decide for yourself which one works best). Note that the list to be processed is limited to "X users" only (i.e. those that are contained in your views results from the previous step).

Add an additional Rules Action in your Rules Component, to actually reschedule the execution of this Rules Component itself after a few seconds or minutes (whatever fits). And trigger the very first execution of this Rules Component via a custom rule that is triggered "When any user of a Company purchases membership" (as in your question, I bet you have some appropriate Rules Event for that).

Step 3 - Stop rescheduling the Rules Component when the time is right

Also add a Rules Condition in the Rules Component of the previous step, to "Check the number of results returned by a VBO view" (using the same VBO view). The actual number of results should be at least 1. If there are zero results, then the Rules Actions of this Rules Component will not be performed, which is what we want. Since it will also prevent the the rules component reschedules itself when all users have been processed.

Step 4 - Review the frequency of your cron jobs

Make sure your cron job runs frequent enough, because each execution of your scheduled Rules Component will actually only happen when cron runs.

Conclusion: because this approach is based on the Rules Scheduler, the elapsed time will be longer, for sure. But the advantage of it is that, as compared to any of your 3 solutions as in your question, the poor user "of the Company who purchased the membership", will not have to wait for the rule to complete execution, before being able to do anything else on the site.

PS: I'm assuming this is about D7 ...


How do I get a multi-field values? I have content type called "sample", where i have field called 'user detail' which is a multifield. I'm using multifield module to get this.
  I'm creating a view for display sample content type contents, but i'm not able to fetch multifield fields in view table.Can anybody help me in fetching multifield values?

By default this puppy does not come with Views integration, perhaps it will soon in the near future.

For now, you will need to patch it, with this patch.


Base URL for all external links I have site that has multiple external links. I need a way to edit them all at once.
For example: I have a site www.example.com that has multiple external links like SOME-IP/getaccess, SOME-IP/getaccess/todolist etc.
As the number of these external links is large, its extremely difficult to move a site to a new setup.

I am looking for a way to edit these external links at one place. like i want to change base url of external links. Something like to change SOME-IP/getaccess, SOME-IP/getaccess/todolist etc. TO SOME-OTHER-IP/getaccess, SOME-OTHER-IP/getaccess/todolist etc. so that all external links will work in a new setup.

I know this is something that many have experienced in websites with multiple external links.

I read read and read, only thing i come up with global variables in settingg.php but how to use these variables in existing modules.
Or Is there a module that allow to edit all external links at once.

Thanks for all the support.

This sounds like an unfortunate build decision coming back to hurt maintenance; that in itself is a common occurrence.  One phrase I must repeat here is "if things dont go as you planned, you have had an experience."  The issue that you have, at least in the school I went to, is called a Magic Number Unique values with unexplained meaning or multiple occurrences which could (preferably) be replaced with named constants

Now, solutions.  If you just want to plaster on more code to resolve this, then look at the External Links module.  This module adds javascript that checks every link on your site to see if they use the site's base url, and if not it adds an image to indicate the link goes elsewhere.  You could modify this code (the joys of open source) to change the IP from the old to the new.  This is what I would consider a weak solution.  It gets the desired result but it adds more code and processing to the site, and doesn't truly fix the root issue.

A better method would be to define a site variable ( code example ) to hold the ip address and then go and edit all of the references to it throughout the entire site to use that variable instead.  This works if all of the links are generated in php somewhere, and not just hard-coded in the body field of various nodes.  The advantage here is, if that ip address changes again you only have to update the variable value.  That can even be done with a drush vset.

Now, assuming these links are in node bodies and do not have the ability to use a php variable, you can get a similar result with a hook.  I would still recommend setting the new ip in a variable.  Then using a hook_node_view you can preg_replace the old ip address with the contents of the variable in the whole body field for any node.  Or in other fields too, or only on nodes of if( in_array( $node->type, $target_types_array)) etc.  This has the advantage of similar flexibility to the variable solution, but it does add extra processing like the javascript solution.  However, it is a hook that does not need loops so it will not be much of an increase.


Set URL Fragment based on which Vertical Tab clicked? Would it be possible for me to have the URL of a given page change depending on what Vertical Tab the user clicks on the page?

For example, when a user is on a complex node form on my site, there are many tabs, each one providing a separate group of information about the node. I'd like for the user to be able to click on a link inside one of the fieldsets, and be able to click the back button to jump straight back into the fieldset he was viewing previously.

Right now, since the fragment isn't in the URL, the user is always brought back to the first vertical tab, regardless of which was open when a link was opened.

If I manually enter the fragment of the #id of the vertical tab that should be opened (like example.com/node/200/edit#my-vertical-tab-id), that works. Is there a simple way to make it so that when a user clicks on a vertical tab, it's anchor fragment is appended to the end of the URL?

You could use JavaScript to change the URL fragment each time a tab is opened (click listener on the tab changes the fragment to that tab's ID). But that would only allow the user to go back and have whatever the last tab they opened before following a link remain open.

If you want to save the state of many opened/closed vertical tabs I can't think of a solution that doesn't involve reading/writing constantly to a DB. Maybe you could get away with using cookies instead? Either way its gonna be messy.


Move file uploads in webform into subdirectory using hook_webform_submission_presave I'm using the webform_multiple_file module to let users upload files in a webform. There is a second form component in that form. It's a number.
I want to change the upload directory, which is defined on webform admin and is 'webform/uploads' in my case. I want the uploaded files to be stored in subfolders named by the number in the second form field.
So the upload directory should be s.th. like 'webform/uloads/102'.

I first tried to accomplish it with hook_webform_submission_presave, but I only can change the file id.

Then I found hook_file_presave, which seems to be the perfect function to solve my problem, but now I'm stuck with the question, how to get the value from my form field into the presave function? The only parameter is $file.

Can someone help me on this? Submission- or file-presave? Is it possible to change the file- and upload-directory in hook_webform_submission_presave?

UPDATE:

I was able to get the form value with $GLOBALS in hook_file_presave.

$order_number = $GLOBALS['_POST']['submitted']['upload_formular']['upload_wrapper']['bestellnummer'];

Some string-functions on $file->uri do get the split point and first and second part of uri. Append first part with the value of 'bestellnummer' as the subdirectory.
Next I create the subdirectory with

file_prepare_directory($newdir, FILE_CREATE_DIRECTORY);

Then I change $file->uri and $file->destination to new URI, and dpm($file) shows, that it's changed. The new directory is created, but the file is still in the original folder after submitting the form.

It seems I'm missing something here...

I finally sorted something out. Now in hook_webform_submission_presave the files are moved into subdirectories named by the value of a number form field. The field is mandatory, so I don't need extra validation in my function.

Here is the code I use in a custom module with plenty of comments, mostly for me to remember what I did.

/**
 * Implements hook_webform_submission_presave().
 *
 * @param $node: The Webform node on which this submission was made
 *        $submission: The Webform submission that is about to be saved to the database
 *
 * - Move uploaded files to subdirectory based on order-id
 */
function custom_module_webform_submission_presave($node, &$submission) {

  if ( 15 == $node->nid) {
    // get ordernumber for subdirectory
    $subdir = $submission->data[4][0];
    // get files from submission and move them one by one
    $upload_files = entity_load('file', $ids = $submission->data[5]);
    foreach ($upload_files as $key => $file) {
      $uri_old = $file->uri;
      // find last '/' in URI to get filename
      $uri_break = strrpos($uri_old, '/') + 1;
      // extract filename
      $file_name = substr($uri_old, $uri_break);
      // replace filename in uri with subdirectory to get new directory
      $new_directory = str_replace($file_name, $subdir, $uri_old);
      // if not already exists create subdirectory
      file_prepare_directory($new_directory, FILE_CREATE_DIRECTORY);
      // move file in new directory and show message
      $moved_file = file_move($file, $new_directory, $replace = FILE_EXISTS_RENAME);
      if ($moved_file) {
        drupal_set_message(t('<i>@file</i> uploaded to server.', array('@file' => $file_name)));
      }
    }
  }
}


How to detect if field support multi values? It seems that field_info_instance doesn't return such info...

I believe the 'cardinality' is stored at the field (base) and not the field instance.  You should be able to use field_info_field to retrieve that information.


Views hook_views_data add multiple joins to custom table based on row condition I'm using hook_views_data to add a custom table and its fields to Views. The table relates to nodes, and looks like this:

+ node id   | my_value   | time_period  +
|-----------|------------|--------------|
| 1         | 100        | 1 year       |
| 1         | 200        | 1 month      |
| 2         | 300        | 1 year       |
| 2         | 400        | 1 month      |
+---------------------------------------+

I have defined an implicit relationship to my custom table, so I have a view with nodes as the base table and I can access the my_value field from my custom table.

The time_period column is new, however. Now there are multiple rows per node, with different time_period values, and each of these results in a different output row in my view.

Rather than having a my_value field for each row, I would like to have my_value (1 year) and my_value (1 month) fields, so that each output row represents one node - i.e. rows for the same node are collapsed and their fields are separated.

I've cobbled together the SQL that achieves this, but I can't figure out how to accomplish this with hook_views_data:

SELECT
    node.title AS node_title,
    node.nid AS nid,
    custom_table_1month.my_value AS my_value_1month,
    custom_table_1year.views AS my_value_1year
FROM
    node
LEFT JOIN
    custom_table custom_table_1month ON custom_table_1month.node_id = node.nid AND custom_table_1month.time_period = '1 month'
LEFT JOIN
    custom_table custom_table_1year ON custom_table_1year.node_id = node.nid AND custom_table_1year.time_period = '1 year'

I have tried to add two base tables to views, called custom_table_1month and custom_table_1year, but these value names are used verbatim as the table name whereas I really want them as aliases, so Views complains that these tables don't exist, and I can't seem to specify the correct table name anywhere.

I'm feeling like this has to be possible, because I've got the SQL for it! I just can't for the life of me figure out how to do this with Views.

You can try code

file my_module.views.inc

/**
     * Implements hook_views_data().
     */
    function my_module_views_data() {
      $data['custom']['views_handler_custom_field'] = array(
        'title' => t('Custom views field'),
        'help' => t('Field custom handler'),
        'field' => array(
          'handler' => 'views_handler_custom_field',
        ),
      );
    }

file my_module.module

/**
 * Implements hook_views_api().
 */
function my_module_views_api() {
  return array(
    'api' => 3
  );
}

file views_handler_custom_field.inc

class views_handler_custom_field extends views_handler_field{
  function query() {

    $this->ensure_my_table();
    $alias = 'custom_table';
    $this->query->add_field($alias,'node_id');

    // Month, you can copy it
    $aliasNode = 'node';
    $definition = array(
      'table' => $aliasNode,
      'field' => 'tid',
      'left_table' => 'custom_table',
      'left_field' => 'node_id',
      'type' => 'LEFT OUTER',
    );
    $join = new views_join();
    $join->definition = $definition;
    $join->construct();
    $join->adjusted = TRUE;
    $this->query->add_relationship($aliasNode, $join,$this->relationship);
    $formula ="";
    $this->query->add_field(NULL,$formula,'node_id');

  }

  function option_definition() {
    $options = parent::option_definition();
    $options['alter']['contains']['alter_text'] = array('default' => TRUE);
    return $options;
  }

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

  function render($values) {
    var_dump($values);
  }
}

The API


How to add highlighting to exposed views_autocomplete_filter in Drupal 8 Is there a way (a hook perhaps) that would allow me to modify the autocomplete fields returned by an exposed views_autocomplete_filter field?  I'd like to style the text typed into the field differently from the rest of the suggestion text.

Something like this:

------------------
| term_          |
------------------------------
| terminal emulators      |
------------------------------
| determination         |
------------------------------
| midterm exams      |
------------------------------

So it seems it is necessary to extend the ViewsAutocompleteFiltersController class to do this.  In order to override the routing so that a custom controller can be used instead, an entry must be added to /mymodule/mymodule.services.yml:

services:
  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

Then provide your /mymodule/src/Routing/RouteSubscriber.php file, which redirects to our local ViewsAutocompleteFiltersController

<?php

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {
    // Replace "some.route.name" below with the actual route you want to override.
    if ($route = $collection->get('viewsfilters.autocomplete')) {
      $route->setDefaults(array(
        '_controller' => '\Drupal\mymodule\Controller\ViewsAutocompleteFiltersController::autocomplete',
      ));
    }
  }
}

Finally provide your local /mymodule/src/Controller/ViewsAutocompleteFiltersController.php which filters for the view of interest, then modifies the output of the base ViewsAutocompleteFiltersController.  The tricky part of that process is that the data member of the JsonResponse output is protected, so we use a customized JsonResponse wrapper to perform the highlighting:

<?php

namespace Drupal\mymodule\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Overrides default ViewsAutocompleteFiltersController to provide highlighting of autocomplete suggestions
 */
class ViewsAutocompleteFiltersController extends \Drupal\views_autocomplete_filters\Controller\ViewsAutocompleteFiltersController {

  /**
   * {@inheritdoc]
   */
  public function autocomplete(Request $request, $view_name, $view_display, $filter_name, $view_args) {

    $response = parent::autocomplete($request, $view_name, $view_display, $filter_name, $view_args);
    if($response instanceof JsonResponse && $view_name === 'my_view' && $view_display === 'my_view_display') {
      $response = new HighlightedJsonResponse($response, $request->query->get('q'));
    }
    return $response;
  }

}

/**
 * Overrides default JsonResponse to provide highlighting of autocomplete suggestions
 */
class HighlightedJsonResponse extends JsonResponse {

  function __construct($jsonResponse, $q) {

    $data = \json_decode($jsonResponse->data);
    if(isset($q)) {
      $qPattern = '/(' . preg_quote($q, '/') . ')/i';
      foreach($data as &$datum) {
        if(isset($datum->label)) {
          $datum->label = '' . \preg_replace($qPattern, '$0', $datum->label) . '';
          $datum->label = \str_replace("","",$datum->label);
        }
      }
    }

    parent::__construct($data, $jsonResponse->statusCode, $jsonResponse->headers->all());

  }
}


Javascript "once is not a function" errors after library include I have a small module which contains the javascript library JSmol. This library renders molecular structures onscreen.
The main module is called jmol. It contains an element, a twig template, a small javascript file, and the official JSmol library.

When I create an element on the page the element renders correctly, but the admin toolbar does not. Javascript console highlights 4 places that the "once" function is used, all in the code after the vendor library was included. One example is this:

TypeError: $(...).once is not a function

  Drupal.behaviors.escapeAdmin = {
    attach: function () {
      var $toolbarEscape = $('[data-toolbar-escape-admin]').once('escapeAdmin');

my javascript file is quite simple:

(function ($, Drupal, drupalSettings, Jmol) {
  'use strict';
  Drupal.behaviors.jmol = {
    attach: function () {
      var Info = drupalSettings.jmol.mydiv.info;
      $('#mydiv').html(Jmol.getAppletHtml("jmolApplet0", Info))
    }
  };
}(jQuery, Drupal, drupalSettings, Jmol));

Is it possible that the vendor code breaks this, or is it something that I have done?

Edit: here's my jmol.libraries.yml file:

jmol:
  version: 1.x
  js:
    lib/JSmol.min.js: {}
    js/jmol.js: {}
  dependencies:
    - core/drupalSettings
    - core/jquery
    - [I've tried adding core/jquery.once here to no avail]

I had this happen in my custom module as well. I then noticed it worked when logged in but once I was unauthenticated my code would throw this JS error. In the end it was simply an issue where I needed the dependency you listed already in my custom module library file dependencies:

dependencies:
- core/drupalSettings
- core/jquery
- core/jquery.once

Once I added this the required JS file was included when unauthenticated as well.

For a little extra information that forced the following JS file to be included as well:

It looks like you solved your specific instance which ended up being multiple versions of jQuery being installed. I would avoid that if possible as it complicates things a bit.


How do I output the entire page template? I've created a custom module that defines a menu callback; that menu path will call a function which performs some actions and once it's finished, it needs to display the theme with a message as the body.

This used to be doable using theme('page', $message) but in Drupal 7 it only returns the HTML content that would normally appear within the BODY tags.

I know that there is now a html.tpl template, but I'm unsure how I can combine the two to generate a full page.

This is a wild guess but have you tried:

$html = array('page' => $message);
theme('html', $html);

(or something along those lines)?


How can I force a field to be required if another field has a certain value? I have two fields, a select list of checkboxes and a taxonomy term reference.  I would like the taxonomy term reference to be optional unless one of the checkboxes has a certain value, in which case a value must be entered into the taxonomy term reference field.

Is there a module that can accomplish this?  I tried the Field Validation module but I couldn't find a way to configure it for this use case.  Custom code is fine too if you could point me in the right direction.

With custom code you can do something like this:

add a new validation function using hook_form_alter()

your_module_form_alter($form, $form_state, $form_id) {
  if($form_id == 'the_form_ID') {
    $form['#validate'][] = 'your_custom_validation_function';
  }
}

then check to see if the conditions are met

function your_custom_validation_function($form, &$form_state){
  if( $form_state['values']['your_checkbox_name'] == 1 ) {
    // check to see if tags are set
    // use form_set_error('tags_field_id', 'error message') to set a error message
  }
}


How do I lazy load on a view? I have a view listing news items.
Is is possible to lazy-load them, so when I scroll to the bottom of the screen, it will load more news items?

There are many modules available for your requirements. You will need to decide which module fits your requirements.
These are some useful modules.

Views Infinite Scroll

Views Load More

Image Lazyloader


Views exposed filter, filter on multiple fields with dropdown and one textbox I'm working on a views integration where the table and its fields are exposed to views. I want to give users the ability to filter on results of this view based on 1 of 3 fields.

I want each of the three fields in a drop down, and one text field where the user can input search terms.

Then once submitted, views will filter on the specific field and terms entered.

Is this possible? I found this discussion which has no resolution: https://drupal.org/node/732458

I'm thinking I may need to just create exposed filters for each of the three fields, and then alter the form a bit to get it how I need it.

To clarify further:

I want to expose three filters, each one searches a field by the text a user entered. I can do this in Views no problem, and it produces three distinct text fields for each of the three filters. Instead, I want the user to have just one text field, and a drop down to select which one they want to search on.

If I understand correctly: you want to expose 3 dropdown filters, but allow only 1 of them for input.

You can hide or show filters by using views dependent filters: https://drupal.org/project/views_dependent_filters, but then you need a filter that sets up 3 values for showing 1 of your 3 independent filters.

But, why don't you use OR instead of AND with those filters? It would give results and you can sort it as you want.


Get prefix and suffix from a Number field So here is my issue;

I got a price in a Number (decimal) field in a node, I need to process this number in some ways depending on users interactions then send it back (via an ajax request) as an integer, but also formatted with proper currency sign which is stored in the fields prefix/suffix settings.

I should mention that this should also work with translations of the price and its prefix/suffixes.

I get the price now this way;

$node = \Drupal::entityTypeManager()->getStorage('node')->load($node_id);
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$translated_node = $node->getTranslation($language);
$price = $translated_node->get('field_price')->getValue()[0]['value'];`

So now I want to constuct a formated variable with the translated prefix/suffix depending on which language is curretly selected.

After some trial and error and cache problems I found the answer to this myself. Here is how I got the prefix/suffix;

$prefix = $translated_node->get('field_price')->getSettings()['prefix'];
$suffix = $translated_node->get('field_price')->getSettings()['suffix'];


query to fetch all path aliases's content type and title I want to know the titles and content types of all the aliases given in table   url_alias . For this, I'm writing query :

$connection = \Drupal::database();
    $query = $connection->select('node_field_data', 'n');
    $query->join('url_alias', 'u', '/node/n.nid = u.source');
    $result = $query->fields('n', ['changed', 'nid','type'])
                    ->fields('u', ['alias'])
              //->condition('n.type',$content_type, '=')
              //->orderBy('n.title', 'ASC')
              ->execute();

    foreach ($result as $rows) {
        $totalRows[] = $rows;

      }

But query is not giving the desired result. What's wrong with the query?

Can you try:

$connection = \Drupal::database();
$query = $connection->select('node_field_data', 'n');
$query->leftJoin('url_alias', 'u', 'n.nid = u.source');
$result = $query->fields('n', ['changed', 'nid', 'type']);
$result->addField('u', ['alias']);

$result->execute();

foreach ($result as $rows) {
  $totalRows[] = $rows;
}

I saw two main problems.

1) Basically you had a mistake that was causing runtime error:

$query->join('url_alias', 'u', '/node/n.nid = u.source');

2) Using join, where for this you need left join.

Different types of joins:
https://stackoverflow.com/questions/5706437/whats-the-difference-between-inner-join-left-join-right-join-and-full-join

Tip: Before running $result->execute(), you can run $string = $result->__toString().
This will give you the produced raw SQL. You can use it in a tool like adminer/phpmyadmin to debug in more detail.

Best regards,
Oleg


How do I get the router name from the internal path? If I know the internal path of my page (e.g. 'node/1') how do I get the router name?

I need it it to generate an internal url:

$url = Url::fromRoute($router_name);

I found Url::getRouteName, but I'm not sure if this is what I need?

Thanks.

Have a look at PathValidatorInterface::getUrlIfValid() or the version that does not check access. That is provided by the path.validator service:

\Drupal::service('path.validator')->getUrlIfValid('node/1')


Why is my cart empty after I click on the "add to cart" button? I'm trying to use the Secure Pages module in conjunction with Ubercart. The module works fine for the most part. However, there is something wrong with the https that prevents an item from going into my cart the first time. Here is my problem in detail:

Start on a product page which is not using https.
Click on the "add to cart" button. I am redirected to https://www.example.com/cart. My cart is empty.
Navigate to any other "unsecured" page, like the product page I came from. I receive a message stating that my item was added to my cart.
Go back to https://www.example.com/cart and I find an item in the cart.
Resume shopping as normal without any further problems.

What is happening in step 2? Why is my item not added to the cart until I go to a different page first? Its worth noting that no errors were reported either in watchdog or other system logs.

I attempted to fix this problem by removing the cart page from the secure pages list. Is there a reason the cart page should be using https?

Additional notes:

The old D6 / UC v.2 version of my site w/ Secure Pages worked without any problems.
I have added $conf['https'] = TRUE to my settings.php
Refreshing the cart page immediately after completing step 2 does not show any items in my cart.

I had the same issue in drupal 7. I disabled secure pages module and used .htaccess file for https stuffs.


How to include javascript code before ? I want to integrate infolink code. Finally I copied this code just before print $closure in page.tpl.php file at the bottom to make it work:

<script type="text/javascript">
   var infolink_pid = 326015;
   var infolink_wsid = 3;
</script>
<script type="text/javascript" src="http://resources.infolinks.com/js/infolinks_main.js"></script>

But why this code does not work when placed in the same place?

<?php
global $theme;
$js_fl_path=drupal_get_path('theme',$theme).'/infolink.js';

drupal_add_js($js_fl_path, 'theme', 'footer');
?>

I'm using a subthemed Garland in sites/all/themes/ui_garland.

If you had had that code directly in the page.tpl.php its normal, because your page is rendered in the same time as you try to add the JavaScript.

You should add your code in one file, at the root of your theme called template.php.


Optgroup in drupal 7 list field Now I'm having like

1|City name
2|Another city name
3|Little town name

in values field when creating content type field

How can I wrap some of them in a group that will appear as “optgroup” in html generated?

you can use a hook_FORM_ID_alter and then add code like this:

$form['FIELDNAME']['#options'] = array (

   'parent1' => array(
      3 => 'child1',
      4 => 'child2',
      5 => 'child3',
    ),
    'parent2' => array(
      8 => 'child1',
      9 => 'child2',
    ),
);


Services Views Multilangual I am totally new to Drupal trying to build a CMS just as a data entry level to gather data,
I built a Service View that will retrieve the content of the node and show it as a JSON object , I have a content type with field collection in it , this field collection contain a Text Field that has Field Translation enabled, users can enter the data in the enabled languages.
My service works well but it only retrieves the data according to the Field Language option under the Advanced tag when defining the service.

My Question is how can I get the data in the language I request ? Is this even possible ?

I figure it out, I have to choose 'Current User's Language' for Field Language option and enable the language detection in the URL, and I added a filter for the field language and expose it, that way i passed the locale in the URL and passed my filter as query string and got my result.


How to add "publish content" to a node view tab I'm developping a website where I'm asked to add a tab "Publish content" next to the Edit tab. I was told to use the hook_menu, but so far i didn't succeed in showing the tab.

Here is what I have done so far :

function mij_bo_add_menu(){
    global $items;
    $items['node/%node/edit'] = array(
        'title' => t('Publish'),
        'page callback' => 'node_page_view',
        'page arguments' => $items['#primary'][1]['#link']['page_arguments'],
        'access callback' => 'node_access',
        'access arguments' => array(1),
        'weight' => 5,
        'type' => MENU_LOCAL_TASK,
    );
 }

Any suggestions?

PS : I am still a novice in Drupal programming.

There's already a module called Publish Content that does what you exactly describe. You can browse the source code if you want to see how it's implemented there.


Is there a means for telling which module or template files generated a block? I am trying to find out what code generated a faulty looking devel block and want to know if there is a module that can tell where a block was generated or some other means.

Is there a module for that, something like the Module Summary, but with info on blocks?

If you haven't greatly overwritten the default block.tpl.php, you can tell by looking at the HTML attributes of the block DIV, which follow this naming convention:

<div id="block-MODULENAME-DELTA" class="block block-MODULENAME">
  ...
</div>


How to overwrite a file upload so that the filename is always the same? I am trying to implement a file upload form in which files are saved. I had written the following code

<?php

/**
 * @file
 * Contains \Drupal\avenue_product_import\Form\avenue_product_importForm.
 */

namespace Drupal\avenue_product_import\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;

class AvenueForm extends FormBase {

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

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

    $form['description'] = [
      '#markup' => '
Use this form to upload a CSV file of Data
',
    ];

    $form['import_csv'] = [
      '#type'              => 'managed_file',
      '#title'             => t('Upload file here'),
      '#upload_location'   => 'public://importcsv/',
      '#default_value'     => '',
      "#upload_validators" => ["file_validate_extensions" => ["csv"]],
      '#states'            => [
        'visible' => [
          ':input[name="File_type"]' => ['value' => t('Upload Your File')],
        ],
      ],
    ];

    $form['actions']['#type'] = 'actions';

    $form['actions']['submit'] = [
      '#type'        => 'submit',
      '#value'       => $this->t('Upload CSV'),
      '#button_type' => 'primary',
    ];

    return $form;
  }

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

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

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

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

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

    drupal_set_message('File Uploaded Successfully');
  }

}

But here the problem is if the filename in which I am uploading is same. It is getting renamed. But I want to replace old with the new one. How can I achieve this? I had seen file_move() and file_save_upload() function. What changes should I make to replace existing filename with the newly uploaded CSV file?

This would save always save the latest upload to public://importcsv/avenue.csv:

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

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

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

  $file_real_path = \Drupal::service('file_system')->realpath($csv_file->getFileUri());
  $file_contents = file_get_contents($file_real_path);
  file_unmanaged_save_data($file_contents, 'public://importcsv/avenue.csv', FILE_EXISTS_REPLACE);

  drupal_set_message('File Uploaded Successfully');
}


Filter articles by tag equal to the node title I'm trying to create view which will show all Articles which tag is equal to title of currently being viewed node (which content type is not Article).

Adding filter Has taxonomy term = [title] does not see token.
My question is how to pass current page title to filter or this is done with contextual filters?

For example, I have the Author content type. On Author nodes, I want to add a view which shows the last three articles which have tags equal to the title of the node. (In my case, it's the author's name.)

Author is not a type of user, nor a role assigned to users.

I managed to get something (but not good enough to work):

View:  Unformatted list of fields
Filter criteria: Content type (=Article)
Contextual filter: Content:Tags
Provide default value: Taxonomy term ID from URL
Validator: Taxonomy term (Tags) + Transform dashes in URL to spaces in term name filter values

When I try to preview the results (Preview with contextual filters), with "chuck-norris" it returns the result as expected, but it doesn't work with "author/chuck-norris", so it doesn't show result on page for Chuck Norris.
I also tried with different options (e.g. default value Rawvalue from URL, path component 2, with checked Use path alias).

I'm trying to create view which will show all Articles which tag is
  equal to title of currently being viewed node (which content type is
  not Article).

Instead of being equal to title, you can approach it like this.

Go to your Author content type, and in Manage fields, add a taxonomy term reference field. Select Tags.

Edit your Author Content Type and give it the same tag as the title.

In other words, you tag the Chuck Norris node with the Chuck Norris tag, which means now your Chuck Norris node as a term ID.

Then in your view


Conditional statement in custom template file using Display Suite I've been searching and scratching my head for a while on this one. I'm working on a blog page where the user can tag posts, but it is not required. I only want to output the label 'Category' if tags actually exist, so I need a conditional statement in my node template but I can't figure out the correct logic for doing so. This is what I have so far...

<?= if (isset($node->$content['tags'][0]['value'])): ?>

<?= t("Category"); ?>

<?= render($content['tags']); ?>

<?= endif; ?>

This code gives the following PHP error referring to the first line of the block of code

PHP Parse error:  syntax error, unexpected T_IF

I'm a Drupal novice so I'm expecting it to be something simple that I am missing or potentially just completely the wrong code.

First, you have a syntax error. Your server might not have been configured to allow short tags.

Try using <?php echo instead of <?=

Second, you could either use the Field formatter conditions module to add display conditions to your fields or create a custom code field in Display Suite.

EDIT: How to  add a Display Suite custom code field in your own module:

1- Create a new module and add this code in it (remember to change MY_MODULE with the desired name):

/**
 * Implements hook_ds_fields_info().
 *
 * We add the code fields to Display Suite here.
 * Then we specify a callback function that will handle the display logic.
 */
function MY_MODULE_ds_fields_info($entity_type) {
  $fields = array();

  // Add a new custom code field. It should be available in Display Suite.
  $fields['node']['tags_custom'] = array(
    'title' => t('Tags (custom)'),
    'field_type' => DS_FIELD_TYPE_FUNCTION,
    'function' => 'MY_MODULE_ds_field_tags_custom',
  );

  if (isset($fields[$entity_type])) {
    return array($entity_type => $fields[$entity_type]);
  }
}

/**
 * Callback to show the tags field only if it has a value.
 */
function MY_MODULE_ds_field_tags_custom($field) {
  $node = $field['entity'];

  // Get the tags field value.
  $tags = isset($node->content['tags'][0]['value']) ? $node->content['tags'][0]['value'] : NULL;

  // Return a string or nothing, depending on the tags field value.
  if (!empty($tags)) {
    return t('Category: ') . $node->content['tags'][0]['value'];
  }
  else {
    return NULL;
  }
}

2- Now, if you go to admin/structure/ds and click on the Manage display link, you will see your new field Tags (custom). Set its label to hidden and publish it in the desired area.


Why entity autoloading doesn't work? I'm trying to set up entity autoloading using hook_menu like this:

    $menu['e-shop/produkt/detail/%commerce_datasheet'] = array(
    'title' => t('Products'),
    'page_callback' => 'commerce_products_datasheet_detail',
    'page_arguments' => array(3),
    'access callback' => TRUE,
     );

function commerce_datasheet_load($datasheet_id) {
  return entity_load_single('commerce_datasheet',$datasheet_id);
}

function commerce_products_datasheet_detail($entity, $view_mode='full') {
    dpm($entity);
}

dpm() function doesn't return anything, so I assume, that $entity is empty.

I am using latest versions on Drupal 7 and Entity API module.

It was my mistake. I was using another module, which provided page callback with higher priority. For the next time - it's advisable to install devel module and go to devel/menu/item?path=<uri> where used page callback can be clearly seen.


How come there are different UUIDs for multiple environments? We have D8 site where we use Configuration Management to export and deploy to multiple environments. We recently created a new content type, Blogs where we added a few fields (field_url, field_country). When we export this in our local development environment it all exports to yml files.

When we push these configurations to our Dev and Test environment we are seeing that they are out of sync even after running drush @env cim. Doing further analysis we found that the UUID is different and causing the issue.

However even if we were to export the configuration from Dev environment into our local ones, we still see that the UUID is different.

The settings.php already contains $config_directories['sync'] = 'path/to/config-folder';

How can we get the UUIDs to be in sync? We don't have this issue with other content types nor fields.

The right way to do it is to create a config_sync folder, you can set it like this in the settings.php file.

$config_directories['sync'] = 'path/to/config-folder';

Then you can run drush cex to export current configuration, and run drush cim to import. I am doing this on all my drupal sites and have never ran into any issues.

You shall commit the config files if you are using git so you can import them on production.

UPDATE: As it is described on drupal.org the full export, on the config page is only to use if you move from one copy of a site to another.

  Or the full site configuration can also be dumped as yml files to a tar.gz file. This only works if you're moving configuration between two copies of the same site (e.g. development and production) and for that reason the sites UUIDs must match.

Try to use the drush cex command instead.


entity:file:undefined" plugin does not exist upload using curl to jsonapi I'm using php_curl to POST a binary image to my local D8.8 app but it keeps returning a 500 error:

  The "entity:file:undefined" plugin does not exist. Valid plugin IDs
  for Drupal\Core\TypedData\TypedDataManager are: helpful list of D8 entities.

Using the example "Flow 1" from this doc page, I started out with this:

     $binary = file_get_contents('Wilson.jpeg');
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL,'http://localhost/jsonapi/node/doctor/field_photo');
      curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
      curl_setopt($ch, CURLOPT_USERPWD, "admin:mypwd");
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_VERBOSE, 1);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $binary);
      curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/octet-stream',
        'Accept: application/vnd.api+json',
        'Content-Disposition: file; filename="Wilson.jpeg"',
        ));
      curl_setopt($ch, CURLOPT_POSTFIELDS, $binary);
      $result = curl_exec($ch);

Searching I read that D8 is more strict about entity bundles, I can report that my field_photo for the doctor content type is instantiated as an image. Examining my app's /admin/structure/file-types/manage/image/edit
I can see in the Known Mime Types section that application/octet-stream and image/jpeg exists and standing by. Rereading the error Drupal seems to perceive that this is a file but isn't clear what kind it is. I thought I was being clever and changed the Content Disposition from 'file' to 'image' but no such luck. Exact same error returned. Swapping it out to one of the suggested to 'entity:file:image' did not change the error message.
It suggests to me that I need to do something in this curl header to prompt Drupal to understand that this is a file that has a plugin established for it.

Digging into the stacktrace I see that it's generating "entity:file:undefined" because the Bundle property for this entity is "undefined". Working backwards, in context of the doctor node definition, the field passes through the MimeTypeGuesser class has figured out that it is a jpeg and its attributes. But this gets lost when passed to the TemporaryJsonapiFileFieldUploader where it attempts to validate the File.

I've attempted adding "application/octet-stream" as a second entry underneath the "image/*" on the /admin/structure/file-types/manage/image/edit page but nothing changes. How should I associate its bundle to "image" so that I end up with "entity:file:image" and I can move on?

One thing that bothers me is that file uploading was added to the 8x-2.x branch and I'm reading that it is part of core. I'm on 8.8.5 and am assuming I have the latest after running composer update.  I've checked some of the file diffs on jttps://git.drupalcode.org/project/jsonapi/ and it appears the files I'm working on are current, but it bothers me that I haven't resolved this. The json output from this module returns "jsonapi":{"version":"1.0" which is an indicator of the external jsonapi specification, not the drupal module.

The usual troubleshooting step when it seems to work for others is to spin up a minimal D8 app and see if it occurs there. The minimal app worked as expected, which points to a module conflict. For me, the contrib module file_entity was causing this trouble. It took several efforts to get it uninstalled, and only by following the #8 comment on https://www.drupal.org/project/file_entity/issues/3060204 where I try to install it would I be able to finally uninstall it.


Is there a hook to alter webform confirmation message? In Drupal 7 using webforms, is there a hook that can alter the outgoing confirmation message shown to someone who has just submitted a form?

My thoughts are to put a text placeholder inside this textarea and do a str_replace to update the output based the submission itself.

Like the @zhilevan told you can use hook_form_alter for placeholder and for str_replace you can implement hook_template_preprocess.

Here is an example.

function my_module_preprocess_webform_confirmation(&$vars) {

    $confirmation = check_markup($vars['node']->webform['confirmation'], $vars['node']->webform['confirmation_format'], '', TRUE);
    module_load_include('inc', 'webform', 'includes/webform.submissions');
    $submission = webform_get_submission($vars['node']->nid, $vars['sid']);
    $confirmation = _webform_filter_values($confirmation, $vars['node'], $submission, NULL, FALSE, TRUE);

   // Strip out empty tags added by WYSIWYG editors if needed.
   $vars['confirmation_message'] = strlen(trim(strip_tags($confirmation))) ? $confirmation : '';

}

Source Webform Token support on confirmation message.

you can also take a look on tpl file option.
Here webform-confirmation.tpl.php


Using regex path pattern on Themekey module Currently on the themekey config page for regex instructions it shows:

  regular expression, including delimiters and modifiers (see PHP
  Manual)

But is there an example of how to setup a url pattern whre I want to only match paths that end with /organize?

This should do it:

node-alias ~ /\/organize$/


Views, Display Suite - fatal error on allowed memory size - what could be happening? I am setting up my guitar lessons site which has categories via taxonomy and then lesson and exercise content types. Exercises are in a lesson, via entity reference. I am using Views and Display Suite. When I try to add a taxonomy view so I can list the lessons (along with the exercises therein), I get this:

Fatal error: Allowed memory size of 94371840 bytes exhausted (tried to allocate 64 bytes) in /home/user/dev.example.com/sites/all/modules/views/includes/base.inc on line 93

Here is what I did:

I created a view (content pane) for taxonomy terms of type lesson category. The goal is to have a display such as

Lesson 1
Lesson 1 Description
    Exercise 1 in Lesson
    Exercise 1 Description
Lesson 2
...

The view filters on taxonomy vocab (term Lessons), there is contextual filter on taxonomy id, and relationship Taxonomy term: Content using Category. I posted screen shot.

I chose view mode lessons_in_category.

Then I wasn't sure what to do in Display Suite. I went to taxonomy (Lesson) content manage display, and for the lessons_in_category view mode I put the lessons in category view in the content. Screen shot attached.

I keep getting the memory error. And seems to me it shouldn't actually be a memory problem. For instance, when I click on a category, it is not like that one category has so much content to generate a memory error. So I have a feeling there is some sort of infinite loop being generated somehow between views and display suite.

Ideas?

The PHP memory limit is being exceeded. In your drupal site, go to /admin/reports/status/php and look for "Loaded Configuration File". It should be one of the first 5 columns in the table.  In a plain text editor, or a code editor, open the file listed there. In it, search for memory_limit and replace the value next to it with, say, `128M'. Save that file and restart your web server. You may need to increase the memory limit again, if your server still errors out.


Track Individual User Page Visits Drupal 7 - Is there an easy way to track individual user page visits using Google Analytics or can I just do this within Drupal?

Worth noting that tracking individual users is against the Google Analytics terms of service:

  7.PRIVACY . You will not (and will not allow any third party to) use the Service to track or collect personally identifiable information of
  Internet users, nor will You (or will You allow any third party to)
  associate any data gathered from Your website(s) (or such third
  parties' website(s)) with any personally identifying information from
  any source as part of Your use (or such third parties' use) of the
  Service. You will have and abide by an appropriate privacy policy and
  will comply with all applicable laws relating to the collection of
  information from visitors to Your websites. You must post a privacy
  policy and that policy must provide notice of your use of a cookie
  that collects anonymous traffic data.

However, Drupal can track authenticated users using the core statistics module.

More info:

statistics_node_tracker
statistics_user_tracker
statistics documentation


Drupal Subscription Webforms I have Subscription webFrom which I need to use it with different products.

Subscription Webfrom will ask  Email and Name to be submitted.

When I click on the product it take to the subscription form where the user enters the name and the email. How do I know to which product the subscription form was submitted. How do I pass the product information to the subscription webform without user having to select the product again or avoid create a same subscription form to each product.

Thanks

B L Praveen

I found a solution to my problem it can be done by passing information through url as said here


Node author and body as plain text I need go get the node author as plain text and the same goes for the body field.  So that means NO html markup. I cant find the right answer on google for drupal fields.

<?php print $name); ?>

gives it with html...

By the time that a print $name is available, you are already in a template or other late stage theme item, correct?  This means the parts have already been passed through render methods to add all that html.

When I had a project that created pdf reports for download and printing, removing these items was important.  I added a helper function to my site module. (every one of my sites receives a site_[name].module, but you could add this to your template.php if you want to keep this all in the theme)

define('UNWANTED_REPORT_TAGS', 'span/h1/h2/h3/h4/div/strong');
/*
 * helper function for removing html from report contents
 * Strip only selcted tags in THEME_preprocess_node function below
 * strip defined constant tags if none given
 * Growth order of O(n) where n is the number of tags, so defaults to O(7)
 */
function module_strip_only($str, $tags = NULL, $keep = TRUE) {
  if ($tags == NULL) {
    // load the defaults
    $tags = explode('/', UNWANTED_REPORT_TAGS);
  }
  if (!is_array($tags)) {
    // we were passed a string, check format and parse
    $tags = (strpos($str, '>') !== false ? explode('>', str_replace('<', '', $tags)) : array($tags));
    if (end($tags) == '') {
      array_pop($tags);
    }
  }
  foreach ($tags as $tag) {
    // tag by tag, strip our given string
    if( $keep ) {
      $str = preg_replace('#</?' . $tag . '[^>]*>#is', '', $str);
    } else {
      // we want the usual text, drop tags and what they wrap
      $cleaning = TRUE;
      while( $cleaning ) {
        // regex probably doesnt work here
        $clipFrom = strpos( $str, '<' . $tag );
        $clipTo = strpos( $str, '</' . $tag , $clipFrom );
        $clipTo = strpos( $str, '>' , $clipTo ); // find end of closing tag
        $str = substr($str, 0, $clipFrom) . substr( $str, $clipTo );
        if( substr_count ( $str, '<'. $tag) < 1 ) {
          $cleaning = FALSE;
        }
      }
    }
  }
  return $str;
}

The function will need an appropriate name for you, of course.  Then in your template file your line would be <?php print html_strip_only($name); ?>

If you just want to strip all <> sets from the string, you can do that like this.  <?php print preg_replace('</?[^>]*>', '', $name); ?> and I am dont think that / needs escaped, but if it does then it would be \/.  The online test tools want it escaped.

$pattern = '/<\\/?[^>]*>/';
$replacement = '';
$subject = '
Updated: 1/14/2016

 Related businesses
';
echo preg_replace($pattern, $replacement, $subject, -1 );


Generate image styles on upload or in some other memory-conscious fashion? I have a D7 site that is hovering around 55mb on devel_shutdown(); for most uncached pages and has a lot of migrated content that has images linked to various styles around the site, many of which are currently ungenerated.

If I bump PHP memory usage allowance to 130mb (I'm on Dreamhost shared hosting, so 150mb is the top end for any individual process), images generate fine. If I leave it at the unmodified 90mb, image generation starts to fail.

It seems there are two options:

a. Get more RAM, through a virtual private server or some other hosting-related fix.

b. At my coworker's suggestion, find some fiddly way of getting images to generate ahead of a user running into them.

In terms of option B, we're using, gasp!, WordPress for an inspiration, which seems to handle images more intelligently in low-memory situations (Heresy! Madness! Spartaaaaaa!).

To explain — after the page has loaded and PHP has released memory, thumbnails are generated as they are uploaded, noticeable when WordPress says "Crunching" during the upload process. This way, there isn't any delay when a user then views them, and there's no worry that the combined memory load of the CMS and the image library will cause one of them to fail.

Is this at all possible in Drupal? Would a module like Cache Warmer do this if set up in a cron job? Is there even any benefit to doing things this way?

I don't like the "lazy" image style generation either. After I imported 100,000 photos I batch created image styles for all of them. I just looped over each image and created the 5 or 6 styles for each image.

I noticed that there isn't a big penalty for looping over images that already have all image styles generated. So you could just run a cron, say every hour, that loops over all images created or updated within the last hour (or two to be save) and create the image styles.

I used something like this to generate the image styles, just select which ones should get generated:

    foreach(image_styles() as $style) {
        if ($style['name'] = 'thumbnail' || $style['name'] = 'medium'){
            $dest = image_style_path($style['name'], $uri);
            print ' '.$style['name']. ', ';
            if (!file_exists($dest)) {
                image_style_create_derivative($style, $uri, $dest);
            }
        }
}

You'll just need to $uri variable, in my case I get it directly from the file_managed table since I ran a batch job.


How can I reduce the granularity of login time ago in Views (from minutes to days)? I have a view of users which displays fields, one of which is User: Last login.  I set the Date format to Time ago (with "ago" appended). By default, this returns values like:

1 hour 5 minutes ago
7 hours 23 minutes ago
3 days 17 hours ago

I am sorting the view by User: Last login as well, and for this I have set the Granularity to Day.  For a number of reasons, I would like to prevent users from seeing precisely how long ago another user logged in if that user logged in within the last 24 hours.  So instead, I would like to return values like:

1 hour 5 minutes ago-> Today
7 hours 23 minutes ago-> Today
3 days 17 hours ago-> 3 days ago

Is it possible to do something like this as a custom Date format in Views?

In the "dull ax" approach to things, you could do a combination of things here.

In the Views UI, under the Date Format, there is a If "Custom", see the PHP docs for date formats. If "Time ago", enter the number of different time units to display, which defaults to 2. Set this to 1.
Now, Views will only output 13 sec ago 13 min ago 1 hour ago etc instead of 1 day 13 hours etc.
This still doesn't get rid of your specificity of the time of the day if today, eg it is going to output 1 sec ago, 12 min ago or 3 hour ago, etc.
To take care of that, you can create a views template for that field, eg, here in D6 World it would be something like views-view-field--NAMEOFVIEW--login.tpl.php.
In there, do something along the lines of:

if (strpos($output, 'sec') !== FALSE || strpos($output, 'min') !== FALSE || strpos($output, 'hour') !== FALSE) {
  print t('Today');
}
else {
  print $output;
}

which will print out Today if it sees a sec, min or hour, or the default if not, eg, it sees day, week, month etc.


How do I bulk switch specific content from one content type to another? So I get a fair amount of spam on my site that gets a good amount of traffic. But the spam content doesn't fit what my main audience is looking for. So I created a content section called spam and downloaded the Node_Convert module, which has worked out well. I can easy change content from one type to another individually. But I want to bulk switch specific content from on type to another. I know I can bulk switch a content type using this module, but I don't want to switch a whole content type, just specific articles in one content type to the Spam content type all at once. It would make sense to to this from the admin content dashboard.

I know I can bulk switch a content type using this module, but I don't want to switch a whole content type, just specific articles in one content type to the Spam content type all at once. It would make sense to to this from the admin content dashboard.

Node Convert lets you create a custom action to perform this task. You may cherry-pick any items you want to convert and convert them. You need not convert all content from 1 content type.

This feature is in Admin -> Content.

Be sure you have tried installing the various dependencies. In this case probably Rules and maybe VBO:

  The module integrates with Actions, Rules, Views Bulk Operations and Admin Views nicely. It has support for exporting templates into Features using CTools Exportables.