Using 'return' with an ajax callback renders an entire page before my content is loaded I'm developing a module that uses Openlayers maps and Drupal Commerce. When you click on the map, you should see products that relate to those coordinates of where you click. I have this working perfectly.

I've got a 'foreach' inside of my function that creates each product row:

foreach($alldata as $data) {
    $content = '';
    $date = substr($data['_source']['ver_date'], -4);
    $content .= '
';

    $titleString = '';
    $titleString .= $data['_source']['longname'] . ' ';
    $trimmedTitle = strlen($titleString) > 80 ? substr($titleString,0,80)."..." : $titleString;
    $content .= '' . $trimmedTitle . '';

    $content .= '
';
    print $content;
}

This works exactly like it should and renders the rows of products exactly like I want.

The problem I am having is that there is an 'Add to Cart' button that was created within another function somewhere else in the site that I have to render in this foreach.

$arr = explode(".", $data['_source']['price']);
$inner_html = '$'.$arr[0].' Print';
$add_to_cart_btn = drupal_get_form('myModule_product_cart_button', $inner_html, (object)$data['_source']);
$content .= '
' . drupal_render($add_to_cart_btn) . '
';

The button loses it's Ajax properties when I use 'print $content'. So I changed it to 'return $content' and moved it outside the 'foreach'.

I get all of the content properly as well as a working ajax 'Add to Cart' button. However, I also get the entire page template rendered prior to all of my content that I'm returning.

<--- Content Rendered In Div via Ajax --->

Full Empty Page Template
---------------------------
Ajax content formatted properly and working properly

I've tried using ajax_render. I've tried using ajax_command_html. I've tried completely redoing my function and ajax to use drupal.behaviors. Nothing is working to remove that full page from rendering prior to my content. It only happens I when use 'return'. I've also tried adding drupal_page_footer().

Even when I have absolutely nothing in my foreach, if I use 'return $content', I get a full page rendered. And it's not the use of '$content'. I've changed that to other variable namespaces and it still renders an empty page template.

Here is my ajax call:

 $('.products').mousedown(function() {
    $.ajax({
      url: Drupal.settings.myModule.ajaxUrl,
      method: 'post',
      data: {
        longtitle : title,
        id : id
      },
      dataType: "text",
      success: function(data) {
        var markup = '';
        markup += data;

          $('.products-pane').html(markup);

      }
    });
  });

Anyone know what is causing this?

You are missing the Drupal settings that include the Ajax settings, which is why the server doesn't know it should be ajaxified. You should (may) be able to fix it by changing this:

$content .= '
';
print $content;

To this:

$content .= '
';
$scripts = drupal_add_js();
if (!empty($scripts['settings']))
{
    $settings = '';
}

print $content . $settings;
drupal_exit();


Why might the user's email address not show up in Views Send or as a Token? I have set up a User view, with User: Email as one of the fields (the others are username and some text fields) .  The email address of each user shows correctly in the view, either formatted as text, or as a link.

I was hoping to use Views Send to send an email from that view.  When I tick the Views Send tickbox and click 'send email' the dropdown displayed against 'Field used for recipient's e-mail' shows all the fields in the view apart from the email field.

I tried pulling in another text field and rewriting that to show [user:mail] or [mail] as a Token, but the rewritten field is empty.

I've been all around the houses trying to work out why that field is not showing in the dropdown and I'm stumped.  Any help would be greatly appreciated.

YAY!

I finally managed to find out why this was happening by comparing against two other Drupal sites where Views Send behaved as expected.

The issue was with the Views Contact Form module : https://www.drupal.org/project/issues/views_contact_form

If you have that enabled, it breaks Views Send by hiding the main user email address, even if you have the format of the field set to plain text.


How to call a search block I am newbie to drupal i have integrated the Apache solr search module and its working fine. I have disabled the drupal's core search.

Now I am creating my own custom module. How can I make the Apache Solr module search functionality work with my custom module? I need sorting and pagination along with search.

What are you doing in your module?, If you are building a new entity, you would to use hook_apachesolr_field_mappings() http://drupalcontrib.org/api/drupal/contributions!apachesolr!apachesolr.api.php/function/hook_apachesolr_field_mappings/7

An example is the implementation in http://drupal.org/project/apachesolr_commerce

Regards!


How to access replacement tokens present in views field rewrite output in its .tpl file of that field I've created a view and I want to manipulate the field output to show bar graph instead of field value.

I'm using bootstrap 3's progress bar as the bar graph, but I'm unable to set width of the progress bar to show progress as drupal doesn't allows style attribute inside "Rewrite the output of this field" in views.

So, I decided to create that field's tpl file now the problem is how can I access the Replacement tokens in the tpl file that are available in "Rewrite the output of this field"

$data = $row->{$field->field_alias} this prints numbers 1 2 3 4 5 ....

Under the Field settings, you can add a class to the field:

this can accept replacement tokens, so for example you could:

create 5 classes each with a different length
add a field prior to this field that will calculate the correct length
use the replacement token of the calculated field to include the proper class:  barsize1, barsize2, barsize3, etc


How do I add javascript to a node or block I've made a cost calculator script and want to use it on my Drupal 7 site.

I heard to use drupal_add_js, but I don't know in what context.

Use a function in the template.php file: yoursite.com/sites/all/themes/YOUR_THEME/template.php

Add JS file in a block:

function YOUR_THEME_preprocess_block(&$variables) {
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/scripts/path');
}

Add JS file to one page or node:

function YOUR_THEME_preprocess_page(&$variables) {
  if ($variables['nid'] == 'INSERT_NODE_ID') {
     drupal_add_js(drupal_get_path('theme', 'MYTHEME') .'/scripts/path');
  }
}

Add JS file to a content type:

function YOUR_THEME_preprocess_node(&$variables) {
  if ($variables['type'] == 'INSERT_CONTENT_TYPE') {
       drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/scripts/path');
  }
}

Add JS file to a view:

function YOUR_THEME_preprocess_views_view(&$variables){
  if ($variables['name'] == 'INSERT_VIEW_MACHINE_NAME') {
    // include javascript
    drupal_add_js(drupal_get_path('theme', 'MYTHEME') . '/scripts/path');
  }
}

As mentioned by @Pierpaolo Cira, you could always replace MY_THEME with MY_MOUDLE. To get the path to your module you would have to use drupal_get_path('module', 'my_module').

Note: MY_THEME and MY_MODULE needs to be lowered case if your module or theme name is lowercased. (E.g. MY_THEME would be replaced with zen if zen)

Source


How can I defined regions like default admin theme (Seven)? For example, visit admin/structure/block/manage/search/form/configure
config search block, in "Region settings", can see Seven (administration theme) "Dashboard(sidebar)" selected, but I find Seven Theme's file, there is no region defined as "Dashboard(sidebar)".

So how can I do the same thing as Seven Theme?

That functionality doesn't come from a theme, it's provided by the core Dashboard module.

The short answer to your question is: copy what the Dashboard module does. To actually do it will require a fair bit of development.

The regions are defined in dashboard_dashboard_regions(), and are eventually added to the page by dashboard_page_build(). The whole process bypasses the usual workflow of defining regions in the theme file.

I'm guessing it's been done like this so that the Dashboard can be used by any admin theme, not just the Seven theme included with core.


How to use tokens in a node? I added a new content type. How can I use tokens when editing a node of that content type?

For example, if I put "Hello [user:name]", the page shows the following:

As shown above, the "[user:name]" token in it is not replaced with the username.

You need a text filter to replace tokens in fields. You can configure them in admin/config/content/formats. In drupal 7 you can install the needed text filter with:

Token Filter

But this will not be ported to drupal 8 in the same way as in drupal 7:

Issue Token Filter in Drupal 8

As this is a very simple piece of code, there is an unofficial version for drupal 8:

token_filter-8.x


Show image on solr search result page I want to show image in my solr search result page.
For that, I have created one field in my content type called media.

In db, Images are saving in field_data_field_media table in the form of field_media_value

Any help very much appreciated.

Best,
Latika

Have you considered helping yourself with this similar question?

showing an image field from solr index on custom solr search page

To display image in your search-result.tpl.php you can follow below link also.

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


Implement a reset button per facet I'm using Search API with Facets and a view to display the results. Everything works as expected but I would like to have a reset button per facet, that could be used as a "Show all" button.

For the moment I'm using facets_preprocess_facets_item_list(&$variables) to create an extra item on the top of every list, eg.

Facet 1 : Region All regions, Region 1, Region 2, ...
Facet 2 : Financial support All financial supports, Financial support 1,
Financial support 2, ...
Facet 3 : Status All statuses,
Status 1, Status 2, ...
Facet 4 : Sector All sectors, Sector
1, Sector 2, ...

To construct the "All ..." links, I'm getting the parameters of the current page and I clean up the filters. For example if the user clicks on the "All financial supports" [facet 2] link while the current page parameters are
../organizations?[facet 1]organizations%5B0%5D=region%3A18&[facet 2]organizations%5B1%5D=financial_support%3A1&[facet 3]organizations%5B2%5D=status%3A10&[facet 4]organizations%5B3%5D=sector%3A28the parameters become ../organizations?[facet 1]organizations%5B0%5D=region%3A18&[facet 2][facet 3]organizations%5B2%5D=status%3A10&[facet 4]organizations%5B3%5D=sector%3A28

It works, but I'm not conviced that this is the best solution because I've managed to dramaticaly slow down the display of the view and, well... it's not very elegant.

Do you know if there is another, more Drupalish solution to implement a reset button per facet?
Thank you in advance for your help.

Have you tried the following?

Navigate to the facet setting page (/admin/config/search/facets/facet_name/edit)
under widget set it to List of Checkboxes or List of Links (not sure what you are using)
Within List of Checkboxes setting or List of Links Setting, there should be an option Show Reset Link.
Enabled it and it will show a Reset Text input box where you can add Reset Facet or whatever you need.
Apply other settings and click save.


How do you move a file/image reference attached to a current node to a different node? I found this previous question, but I'm struggling to adapt it to what I want to accomplish.

How can you take a file/image that is attached to one node, and move it to another or create a new node and attach it there?

I can't recommend this as finished code, and I certainly can't vouch for it's safety/usability, but I was able to accomplish this with:

<?php
function testymod_node_presave($node){

    if($node->type == 'image_gallery'){
        $nl = $node->language;//to shorten lines

        if(isset($node->field_image,$node->field_image[$nl],$node->field_image[$nl][1])){
            //Leave the first file, but move all the rest to indidivual nodes of their own
            for($i=1;$i<count($node->field_image[$nl]);$i++){
                $tmpNode = new stdClass();//Create a node object

                $tmpNode->uid = $node->uid;

                //Use the current node data
                $tmpNode->type = $node->type;
                $tmpNode->title = $node->title;
                $tmpNode->language = $nl;

                //Set some defaults
                node_object_prepare($tmpNode);

                //Add the file
                $tmpNode->field_image[$nl][0] = (array) unserialize(serialize($node->field_image[$nl][$i]));//Only way I know to do a deep clone

                $tmpNode = node_submit($tmpNode); // prep for saving

                node_save($tmpNode); // Should have an nid now
            }
            //Remove attachments from the original
            $node->field_image[$nl] = array_slice($node->field_image[$nl], 0,1);
        }

    }
}
?>

I may try to develop this into a usable module with a switch in the content type to enable it for a given content type, but I'd need to figure out how to automatically copy any relevant fields over as well.


Restrict search results to only documents user can see In my application, I have a content type called resource. In the resource content type, I have an entity reference that defines which roles should be able to view that resource.

When somebody is logged in as a certain role and does a search, he is able to view documents that don't belong to his role. How can I hook to the search results and remove the ones he should not be able to see?

Thanks

I think this module will help you Access by term and don't forget to enable Node access settings in search api settings.


When is hook_user_presave triggered? I'm trying to create a little module that operates on similar principals as a shopping cart, but has nothing to do with e-commerce. I want to add paired values to $user->data['cart'] on a very frequent basis. Everyone seems to agree that hook_user_presave is the way to do this. My question is this, when does hook_user_presave trigger? Can it be called from inside another fucntion or an .inc file, or does it happen on pageload? I am absolutely befuddled, since I thought hooks were basically event handlers for Drupal Core.

Can I, say, do the following?

test.module:
<?php
function mymodule_user_presave (&$edit, $account, $category) {
    $edit['data']['cart'] = $edit;
}
/* ... */

test.inc:
<?php
/* ... */
function mysavefunction () {
  $myvar = array('sweetdata' => 5);
  $account = user_load($user -> uid);
  mymodule_user_presave ($myvar, $account)
}
/* ... */

If you could even point me to some documentation other than this useless api page, I would be greatly in your debt.

hook_user_presave is an event listener that's called when a user account is saved.

It's invoked from user_save and shouldn't normally be called manually.

// Invoke hook_user_presave() for all modules.
user_module_invoke('presave', $edit, $account, $category);

If you want to save data on the user account, just use user_save


Commerce - Product and Total Price(s) on summary page not being updated by rule I am creating an e-commerce website for a restaurant, there will be extra toppings available on pizzas. I have achieved this partially by using taxonomy to create the toppings and by giving this taxonomy term a field for price.

The rule then updates the price by adding the price of the topping on to the total price for that pizza. This is working when I view the cart page, but on the summary page it is not taking affect at all.

There is also an issue with the Ajax add to cart module in that if I add to cart a pizza of one kind with no extra toppings, and then add to cart the same pizza with an extra topping, the price in the cart for both pizzas is updated to be the price of the pizza WITH the additional topping.

However the total price is correct in this. I have checked the view for both the cart page and the summary page and they seem to be the same, which makes me think that the issue is with rules

This is my rule at present. I have used to commerce tutorial for a pizza shop using the customisable products module.

{ "rules_pizza_toppings" : {
    "LABEL" : "Pizza Toppings",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_line_item", "commerce_product_reference" ],
    "ON" : { "commerce_product_calculate_sell_price" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "commerce-line-item" ], "field" :     "field_extra_toppings" } }
    ],
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-line-item:field-extra-toppings" ] },
          "ITEM" : { "pizza_topping" : "Pizza Topping" },
          "DO" : [
            { "commerce_line_item_unit_price_add" : {
                "commerce_line_item" : [ "commerce_line_item" ],
                "amount" : [ "pizza-topping:field-pizza-toppings-price:amount" ],
                "component_name" : "fee",
                "round_mode" : "1"
              }
            }
          ]
        }
      }
    ]
  }
}

It's best to use separate questions for separate issues here. The one from the title is almost certainly due to a regression introduced in Rules 2.8 and documented in the Commerce 7.x-1.11 release notes: https://www.drupal.org/node/2408705

You can downgrade to Rules 2.7 until a fix is put into Rules.


How to organize a lot of related blocks for facet search programatically? I am experimenting with Solr search and the Facet API, and I've created a search page that now has about a dozen facet blocks on it.

Right now it just looks like Block 1, Block 2, Block 3, Block 4, etc.

I would like to group these into categories, such as Category A (Blocks 1-3), Category B (Blocks 4-9), and Category C (Blocks 10-12).  Ideally these categories would be collapsible.

I already have way too many modules on my site so I want to avoid adding a new module (such as Block Group) to do this.

In this case, is CSS the way to go, or is there some aspect of Drupal that can help with this?

I ended up doing this with Panels.  I took the facet blocks and grouped them using mini panels, and then I used Panels Style Collapsible to allow them to be expanded or contracted as necessary.


CKEditor4: the image disappear when I switch from Rich text View to source view I am using the CKEditor4 module for Drupal7 (https://drupal.org/project/ckeditor) and I noticed that when I am in the "Rich Text" view and I upload an image using the Image button. Initially the image is there, but when I switch to the "source view" and go back to the "Rich Text" view the image disappears. Also when I save the page in the Admin and I come back to it the image disappears. The code for the image still exists in the source view and the image shows up in the Live post but NOT in the "Rich Text" view.

Any ideas what's the problem?

Thanks.

You need to make it clear that images are allowed content.

You may safely declare that images, only certain image attributes, all image styles, and all image classes are allowed content. You do that with the following line of JavaScript:

config.extraAllowedContent = 'img[!src,alt,title,width,height,style](*){*}';

To set these variables, navigate to Configuration → Content authoring → CKEditor and then press edit for the profile you want to configure. Expand Advanced options, and type the JavaScript directly into the textfield Custom JavaScript configuration as shown in the screen shot below (disregard the first line unless you also want to set custom format_tags);

PS: If you Google this, you'll often see the following JavaScript suggested to "fix" the disappering image problem:

config.allowedContent = true;

Yes, it will fix the problem of images disappeearing when you toggle between rich text and source. But it will also make all sorts of content allowed - which is a gaping security hole in your site if you allow untrusted users to create and edit content.  Don't use this quick "fix". Use the solution that uses the extraAllowedContent directive to spell out what shall be allowed (and allow only safe content).


How to display message (NDA, warning, etc.) before content can be viewed? Say a user wishes to view a certain piece of sensitive content. How can we have the site first respond with a notice, before the content can be viewed?

Specifically, I'm looking to have the site respond with a simple NDA (Non-Disclosure Agreement) before displaying certain nodes (and even then, only to registered users, of course). But I can imagine many more uses: displaying conditions and terms related to the content, displaying an age warning for... er, more delicate content, and so on.

In my case, I need every sensitive node to display an NDA; presumably, the notice would be dismissed by some sort of "Agree" or "Proceed" link, which would then take the user to the content. After that, the node would ideally remember that the user has permission for future viewings of that specific node (i.e., doesn't need to see and agree to the notice every time).

I can imagine other sites, though, that might want to enable agreements for whole groups of content (such as a node type): view the notice once, and then have free access to any of the affected nodes.

Also, it would be ideal to have the option of allowing unimpeded view of the teaser, with the notice coming into play only when a reader tries to view the full node.

Whatever the details, does anyone have ideas for enabling this? I've found many modules or techniques to prevent access to specific nodes by user role, or password access, etc., but not to grant access after displaying a notice. There's the Legal module (http://drupal.org/project/legal) for displaying terms and conditions upon registering to become a user, but that doesn't handle viewing specific nodes.

As always, I suspect I'm missing something obvious. My kingdom for a solution!

You've listed a nebulous group of requirements that somewhat overlap with existing module projects out there. FWIW, there's also the Premium Content module which also has elements of what you're asking for.

My guess is you're not going find one that 100% matches your current and ongoing needs. So you either find one that matches the most & work on patches to that project, or you build your own. Depending on how specific your needs are one might work better than another.

If you go the "build my own" path, look at hook_node_access() & hook_node_view() (D8: hook_entity_view()) which respectively allow you step in front of node permission checks and rendering. They will be the core of your strategy to determine when to allow full access & when to send your user through a NDA confirmation workflow.


Programmatically showing the summary of a post What's the PHP code to call summary of a post (teaser) in a custom page?

I use Drupal 6 and I want to show a small part of a specific post in a custom page.

You can use teasers from node. In node.tpl.php you can use $teaser variable to print it.
In other templates, you need to use node_load().

$node = node_load(211); // 211 is the Node ID
print $node->teaser;


Drupal 6 does not like it when an image tag's absolute path contains “http:” I'm using Drupal 6.28 and there's something i don't understand.

i have a page that contains an image tag pointing to an absolute path. e.g.

when the content is saved, drupal returns a "Page Not Found" error.

i found out that if i remove the "http:" at the start of the src attribute, there wouldn't be any problem. everything would be ok. i.e.

is there some setting that i may have messed up that causes this?

Thanks

the issue i reported was caused by a mod_security setting.
my host fixed it after i spoke to them.


Is there a module or method for processing and generating codes for music download cards? I'm looking for an easy way to add download card functionality to my Drupal 7/ubercart site.

In case you are wondering, by "Download Card" I mean an actual physical object that a band can sell at a gig. The card has a code on it and a URL. The buyer goes to the URL, enters the code and they are allowed to download MP3 files, etc.

There are plenty of pay options for this (CDBaby, Dropcards...) but a Drupal option would be fantastic. The Drupal site would need to both generate the codes and export them into a spreadsheet or similar so that we could print them out on to cards. The site would, of course, also have to be able accept the codes and only allow users with the correct codes to download their music.

Does something like this exist for Drupal?

Well I'm unaware of a turn-key (Drupal Distribution) for a Dropcard ecommerce site per se. The components exist to make such a site using some custom code. Some example modules that fit your use-case are:

TokenAuth

  Token Authentication provides a token for use in the URL to
  authenticate users to your site. It only works on paths configured in
  the settings page.

Commerce File

Ability to limit access to the file with limit settings
Default limits: duration, download count, IP address count
Limit default values can be inherited at the product level such that the product always uses the current default value
After purchase of a file, limits are statically recorded to the line item so that they do not reflect any changes to the product's file limits.
A user's limits reflect changes to an order, even after order is completed.
Order deleted, canceled
Line item deleted, update
Utilizes Rules to control workflow for:

File download access: controlling access and reacting to access denied
Order workflow: issuing access licenses and revoking access licenses in the order

Views Data Export -- export your authentication links to paper cutouts.

  This module is designed to provide a way to export large amounts of
  data from views. It provides a display plugin that can rendered
  progressively in a batch. Style plugins are included that support
  exporting in the following types:

  CSV, Microsoft XLS, Microsoft DOC, Basic TXT, XML.

Commerce Module

  uhh make an eCommerce site using drupal.

Many of these modules likely make use of Drupal core concepts for Entities, Cron Jobs and likely Queues. You may find the Queue API useful to build the authentication tokens for example every hour for new audio content.

The ingredients exist for a developer to create what you're asking for, good luck.


Pass node field value to view filter in a block Background

For the node type article I want to display a block view of map markers generated from a content type called sted (places). For the content type article I have made a entity reference field (multiple values allowed) called kartreferanse (map reference) where you can pick multiple nodes of the type sted (places). So far so good. I have also made a view in a block that displays markers for all the content types sted (places) using a Geolocation - CommonMap. Now I want to pass the reference field to the view to show only the places picked in the field kartreferanse (map reference) for the current node. I have tried using contextual filters (field_kartreferanse: Content) Content: ID with no luck, and/or tried building a relationship using field_kartreferanse: Content in the view.

The question

How can i pass the ID of the current node (article) to the view (in a block) and use the entity reference field in the article to show right node IDs in the map block view?
Do I also have to make some filter-criteria for this to work? (field_kartreferanse: Content) Innhold: ID (= [Content: Nid])
(Later I will have to make this view work in a multilingual site.)

(Drupal 8, local install / mamp, geo locationfield, views 8.1.10)

The easiest way to use a view in a block (or anything that uses a build array) is as a render element:

$node = \Drupal::routeMatch()->getParameter('node');

$current_nid = $node->id();

$view_arguments = [$current_nid];

 $build['news'] = [
   '#type' => 'view',
   '#name' => 'myviewname',
   '#display_id' => 'block_1',
   '#arguments' => $view_arguments,
   '#weight' => 30,
 ];

return $build;

The first argument passed in will be used as your content ID.

If you want to do it all through the UI, you set your contextual filter to pull from the content id.

then if you place a block based on the view, it will pull in from the current node.


How does one add revision information to custom built entities? I'm looking for help in gentle/simple terms for how to add revision information to my custom entities. This is maybe my fifth or sixth attempt to do this and every time I get lost and overwhelmed by all the info in the various online knowledgebases about the various ways of doing things for various iterations of Drupal.

I've used the EntityAPIController (sites/all/modules/entity/includes/entity.controller.inc) from the Entity API module and seen that this has the following method:

  /**
   * Saves an entity revision.
   *
   * @param Entity $entity
   *   Entity revision to save.
   */
  protected function saveRevision($entity) {
    // Convert the entity into an array as it might not have the same properties
    // as the entity, it is just a raw structure.
    $record = (array) $entity;
    // File fields assumes we are using $entity->revision instead of
    // $entity->is_new_revision, so we also support it and make sure it's set to
    // the same value.
    $entity->is_new_revision = !empty($entity->is_new_revision) || !empty($entity->revision) || $entity->is_new;
    $entity->revision = &$entity->is_new_revision;
    $entity->{$this->defaultRevisionKey} = !empty($entity->{$this->defaultRevisionKey}) || $entity->is_new;

    // When saving a new revision, set any existing revision ID to NULL so as to
    // ensure that a new revision will actually be created.
    if ($entity->is_new_revision && isset($record[$this->revisionKey])) {
      $record[$this->revisionKey] = NULL;
    }

    if ($entity->is_new_revision) {
      drupal_write_record($this->revisionTable, $record);
      $update_default_revision = $entity->{$this->defaultRevisionKey};
    }
    else {
      drupal_write_record($this->revisionTable, $record, $this->revisionKey);
      // @todo: Fix original entity to be of the same revision and check whether
      // the default revision key has been set.
      $update_default_revision = $entity->{$this->defaultRevisionKey} && $entity->{$this->revisionKey} != $entity->original->{$this->revisionKey};
    }
    // Make sure to update the new revision key for the entity.
    $entity->{$this->revisionKey} = $record[$this->revisionKey];

    // Mark this revision as the default one.
    if ($update_default_revision) {
      db_update($this->entityInfo['base table'])
        ->fields(array($this->revisionKey => $record[$this->revisionKey]))
        ->condition($this->idKey, $entity->{$this->idKey})
        ->execute();
    }
    return $entity->is_new_revision ? SAVED_NEW : SAVED_UPDATED;
  }

But with all the various sources of information out there on developing for Drupal I'm in a total tangle with my understanding. Am I just supposed to say "is revisionable" this link and others kind of gloss over it as though all one needs to do is set the "revision table" and "entity keys" "revision" element in the hook_entity_info implementation

This is where I'm unstuck - just as with node and node_revision in the db, can't entity and entity revision tables be different? Surely we need to overwrite something in one of the entity/controller/wrapper classes because it's not as simple as just copying all fields from one db table to another and auto incrementing a version id?

This post has lots of info, but I started reading through the links under "documentation" and I'm worried that I might be looking at some module which has hijacked the term revision in some higher layer.

So far this seems to be the best example to follow/debug and learn from, others just seem to lack that crucial sentance that actually helps to see what's going on:
https://www.drupal.org/project/typical_entity_example

Use typical_entity_example_5 and note the work on .install and .module.
The key elements are in hook_entity_info (.module)/ hook_schema (.install) and the typical_entity_example_5_form_submit(...) (.admin.inc) function where we have:

$entity = $form_state['typical_entity_example_5'];
entity_form_submit_build_entity('typical_entity_example_5', $entity, $form, $form_state);
$entity->is_new_revision = TRUE;
$wrapper = entity_metadata_wrapper('typical_entity_example_5', $entity);
$wrapper->save();

The power of this example is that the form of the schemas are more or less the same, but with differences in the columns used as primary keys.

I'm still trying to work out though whether it's better to have it in ->save() rather than using it in the admin form submit as above. So that any and every save invocation creates a new entity. Programmatical (non aforementioned admin UI) editing of an entity would presumably not create a new revision unless manually coded in.

NOTE: you can put it in either the custom entity class:

class YourClass extends Entity {
    public function save() {
        $this->is_new_revision = TRUE;
        parent::save();
    }
}

or custom controller:

class YourClassController extends EntityAPIController {
    public function save($entity, $transaction = NULL) {
        $entity->is_new_revision = TRUE;
        return parent::save($entity, $transaction);
    }
}

Or both, I guess. I'm still not 100% sure if there are use cases which neglect one way or another as from what I've seen so far it goes YourClass->save() >> into >> YourClassController->save() so I suppose I'll probably just put it in both just to be sure...


How can I make required cck date field "not required" by hook_form_alter? I could make some requited cck fields "not required"  by hook_form_alter a below but this doesn't work for date field.

for selection type

function hook_form_alter(&$form, &$form_state, $form_id) {
$form['field_smaple_1']['#required'] = 0;
}

or

for text are type

function hook_form_alter(&$form, &$form_state, $form_id) {
$form['field_sample_2']['0']['#required'] = '';
}

How can I do the same thing for date field?

To alter date field required to disable, you can use following snippet in your form alter

$form['#field_info']['field_date']['required']=0; //field_date use your field name


Change the default value of a checkbox element I have created 7 checkboxes using webform. I want the checkbox to be checked by default. For this I have used hook_form_alter() to change the checkbox as ticked by default. I have used the following code.

 function module_form_webform_client_form_31_after_build($element, &$form_state) {dpm($element);
     $element['submitted']['checkbox7'][1]['#checked'] = TRUE;
     $element['submitted']['checkbox6'][1]['#checked'] = TRUE;
     $element['submitted']['checkbox5'][1]['#checked'] = TRUE;
     $element['submitted']['checkbox4'][1]['#checked'] = TRUE;
     $element['submitted']['checkbox3'][1]['#checked'] = TRUE;
     $element['submitted']['checkbox2'][1]['#checked'] = TRUE;
     $element['submitted']['checkbox1'][1]['#checked'] = TRUE;

     return $element;
  }

this code works fine for me. If I add another checkbox, I have to add another line of code. Is there a way to change the default value of all the checkboxes without to add a new line for every added checkbox?

This code find the checkboxes in the 'submitted' element and check it by default.
If you make a screenshot of dsm($element['submitted']) message I can check if this code is correct ^^

function module_form_webform_client_form_31_after_build($element, &$form_state) {
  foreach ($element['submitted'] as $key => &$value) {
    if ( $value['#type'] == 'checkbox' ) {
      $element['submitted'][$key][1]['#checked'] = TRUE;
    }
  }
  return $element;
}


How to make sticky articles show up first in a list of articles? I have a view showing a list of articles, sorted by date. I tried enabling the sticky article option in the publishing options. This made an article I had jump to the top of the list, but then a new article I added pushed the sticky article to second place.

I want a sticky article (pinned) to be first in the list even if I add new articles.

How can I achieve this?

Enable of the "sticky" option within publishing options (for 1 or more nodes) is only part of the solution: within the "Sort criteria" of your view, you also have to add  "Node: Sticky" as your primary sort criterium (using the Views UI).

When adding this sort criterium to your view, you'll also see "...To list sticky nodes first, set this to descending." (which is what you seem to be looking for).


on submit does not allow login to occur When I add an additional "onsubmit" function to the login button, the login doesnt continue
this is my code function xxx_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
 if ($form_id=='user_login_form') {
    // Add a custom submit handler to save the array of types back to the config file.
    $form['actions']['submit']['#submit'][] = 'xxx_form_submit';
  }
}

and it goes through the submit but doesnt continue the login functionality.

Use $form['#submit'][] = 'xxx_form_submit'; instead of $form['actions']['submit']['#submit'][] = 'xxx_form_submit';.


Ckeditor missing buttons I'm using CKeditor as the Wysiwyg container. I configured it to show the full toolbar but when the user tries to edit it does not show the buttons configured.
I'm using the last version of the module available for drupal 7 and jquery 1.7.
Some buttons as iframe or letter size are not showing up.
What can I do to solve this.
Best regards
Eduardo

If it is showing for you (user one or admin) but not someone else logged in, it could be permissions.

I would create a test account with the same permissions as the person having issues. Do you see the ckeditor toolbar while logged into the test account?

If that is working, try the solution mentioned here.


Why is my Cache Expire "0" even when I set it to be time() + 3600? I'm caching our hefty menu output with the function show below, as each menu item loads two views (menu popups with sub-taxonomy data as a viewfield). This rids us of about 800 extra queries per pageload since Views Argument Caching doesn't work properly, and static caching seemed liked the easiest way to work around the problem. Also the data doesn't need to be that fresh.

Now the issue is, we want the data to be cleared whenever cron runs -- and I'm setting the expire timestamp to be +1 hour from the moment it gets cached, but when checking custom_data CID from cache table the expire timestamps shows a 0 (never), instead of the now + hour. Any ideas?

/*
 * Check  if we already have main navigation in cache, if not, render it
 */
function mymodule_render_main_menu() {
  $navigation = &drupal_static(__FUNCTION__);

  if ( !isset($navigation) ) {
    // Check if we have cached data
    if ( $cache = cache_get('custom_data') ) {
      dsm("Nav from cache");
      $navigation = $cache->data;
    }
    // Else render the main navigation
    else {
      // Get main menu block
      $navigation = menu_block_block_view('1');
      $expire = time() + 3600;
      dsm($expire);

      // Set it's caching to 60min
      $navigation['#cache'] = array(
        'cid' => 'custom_data',
        'bin' => 'cache',
        'expire' => $expire
      );

      // Render the menu
      $navigation = render($navigation['content']);

      // Push rendered data to cache
      cache_set('custom_data', $navigation, 'cache');
    }
  }

  return $navigation;
}

Worked using cache_set('custom_data', $navigation, 'cache', $expire);


Can You Render Data from Forced Fields in Views While Using format "Show: Content" Drupal 8.x

Is it possible to render fields in a view when the display format setting is set to format "Show: Content" ?

For my case, the contrib module I am using has some views integration that provides field data I would like to show, but have found to be difficult to access via preprocess. I also have some programmatically created data I need to show via my template provided by a HOOK_preprocess_HOOK().

I am kind of stuck in the middle. So I am curious if there is a way to render, or maybe get the data of, the forced fields while setting my view to "format: content"?

Yes, you have to decide whether you want to render Content or Fields. Those are two different concepts in Views. The first renders the entity template in the selected view mode and you configure the fields in the content type. The second renders Views field plugins which you configure in Views UI.

You can approach the issue from both sides:

Show: Content | View Mode

If you start with a View showing content, in the view mode you've selected, display a field for a second View dispay of the same entity. In the second View display select Show: Fields.

You need a module to add the View field to the content type, for example  EVA: Entity Views Attachment or Views Reference Field.

Show: Fields | Settings

Or start with showing fields,  add a field for the rendered entity

and select a view mode, which you then can configure, preprocess and theme like a normal node template.


Using Drupal 6's form ahah to have one dropdown field update the values of a second dropdown field I am working on a pair of form fields the directly effect one another. Specifically the problem I am dealing with is that we have thousands of groups users can join on this website that I have been working on. We are creating some administrative analytics forms for the site. Part of those forms is filtering by group.

The problem is that most of the people don't know the name of a group off the top of their heads, only what it starts with. So instead of using auto-complete we came up with two dropdowns. The first contains the options A through Z, letters of the alphabet which the group names begin with. The second dropdown contains all of the groups beginning with the selected letter.

The concept is simple enough and we were able to implement the AJAX pretty easy with jQuery. But this causes validation errors. After some research I found that this has to do with Drupal form caching. The solution is to use the ahah functions.

The problem with that is that all the instructions I have found so far deal with ahah actions for the specified field updating itself, not another field. So I am trying to figure out how to get the list of letters to update the group list using ahah and registering the new values with the form cache.

One solution I found was to simply load all the values on the page in a hidden dropdown and then just load up those in the set in the visible one as needed. But that creates a bunch of problems because the client uses almost exclusively IE and we have seen IE choke when given huge lists like that. Especially with the lists stored in JavaScript. So we need a light-weight solution.

Any thoughts? Ideas?

There's comprehensive example code in the Examples module that shows how to do this.

In the dependant_dropdown.inc file of the ahah_example module, you'll find an example form that does exactly what you're looking for. It's very well commented and should guide you through the process pretty well.

There's also a companion tutorial for the ahah_example module which would be worth looking it as it has more code examples.


Cannot edit any content Panes in Panopoly installation, getting JS error When I try editing any pane on my site, I get this:

The following error is in my Web Inspector console:

  TypeError: 'undefined' is not a function (evaluating '$('.panopoly-textfield-autosubmit, .panopoly-textarea-autosubmit', context)
        .once('ctools-auto-submit')')

  TypeError: 'undefined' is not a function (evaluating '$("select.ctools-master-dependent")
          .once('ctools-dependent')')
  `

I've tried changing Jquery Update settings, updating Panopoly to the newest version (along with the modules). No luck.

I had a such problem with the module jquery_update when we used a library upper jQuery1.7 . Try use different jQuery versions for User interface and the Admin interface. And do not mix them.


Send prefill message PrivateMsg I need a feature for my website, I want that users can send pre-filled messages to others users.

Like in an user's profile page, they just have to click on a button and then, the pre-filled message is sent.

I'm using PrivateMsg module, I don't know if this module could do the job

(By the way I'm new to Drupal).

Thanks for your help !

You may implement this: hook_privatemsg_message_presave_alter.

  Change the message before it is stored.

The $message variable contains the message's body (as well as much more parameters) ready to be edited. Note that you can include html tags in your message. Here is a code sample:

/**
 * Implements hook_privatemsg_message_presave_alter().
 * Change the message before it is stored.
 */
function my_module_privatemsg_message_presave_alter(&$message) {
  // dsm($message); print out the $message contents
  $name = $message->recipients['user_1']->name; // use foreach for many recipients
  $message->body = "Dear $user,\n you rock!";
}


How do I generate an order using the "Add to Cart" button in a custom PHP page? In Drupal Commerce Kickstart, I used custom PHP page in Drupal root folder. As per requirements, I chose custom PHP Code to show products in different logic pattern. I am getting product id value for each product in that page. Now, I need "Add to cart" button which should generate order number and redirect it to checkout page directly.

How do I generate an order using the "Add to Cart" button in a custom PHP page?

Though I prefer the Commerce Add To Cart Filter module to adding a "Add to cart" button anywhere in my content by mentioning the product ID with the suggested method, since you need PHP code, I am copying my old code which I don't use anymore; maybe it can help you.

function MYMODULE_commerce_menu() {
  $items = array();
  $items['mysite/trial-buy'] = array(
    'title' => 'Trial Plan',
    'page callback' => 'MYMODULE_add_single_product',
    'access arguments' => array('view published content'),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function MYMODULE_add_single_product(){
  global $user;
  $product_id = 59;//This is my product ID, place your's here.
  $order = commerce_order_new($user->uid, 'checkout_checkout');
  commerce_order_save($order);
  $product = commerce_product_load($product_id);
  $line_item = commerce_product_line_item_new($product, 1, $order->order_id);
  commerce_line_item_save($line_item);
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $order_wrapper->commerce_line_items[] = $line_item;
  commerce_order_save($order);
  drupal_goto('checkout/' . $order->order_id);//Forward to checkout. You can have your method here.
}

This is the code I came out with the help of Commerce guys documentation when I was working with some custom need like yours.


Unable to use user fields from the global variable $user I have created a module where I am declaring $user as global variable in hook_init().  I can access the values of $user->x_field in page.tpl.php. When I try to use $user->x_field in hook_contents($display), it causes the following error:

  Undefined variable:x_field

Can I use the user fields in hook_contents()? Am I doing it the wrong way?

The global $user variable doesn't contain all the values you would find from a user object loaded from the database; in particular, it doesn't contain any field associated with the user entity. If you need a full-loaded user object for the currently logged-in user, you should use the following code.

$account = user_uid_optional_load();
// Use $account to access the user fields.

If need to load a full-loaded user object knowing its user ID, then you should use the following code.

$account = user_load($1);
// Use $account to access the user fields.

Also in this case, you could use user_uid_optional_load(); since it only passes the given user ID to user_load(), you can directly use user_load() and use user_uid_optional_load() when you don't have always a user ID, and need the user object for the currently logged-in user in that case.


How to add additional tabs to user profiles I'm trying to find a way to add another tab to the tabbed menu under each user's username on the user/* page.

I want to have View, Edit, and an additional link. I'm not sure where I need to be looking in the code to edit this menu and I can't find any documentation thus far. Any help would be great.

Thanks

I believe you can implement hook_menu in a custom module and use MENU_LOCAL_TASK as the type, and the path needs to start with user/

function HOOK_menu() {
  $items['user/mypage'] = array(
    'title' => t('My Tab'),
    'type' => MENU_LOCAL_TASK,
    //'page callback' => 'mymodule_mypage', //mymodule_mypage should be a function that returns HTML for the content area
    //'page arguments' => array(0, 1, 2), // 0 is arg(0), 1 is arg(1) etc...
  );
  return $items;
}

For all the array elements see this page


Setting up Multisite on windows server with IIS7 First off I'm not a server person. New windows box spun up, IIS7 was used to install one instance of Drupal 7. Great :)

However I need to have multiple sites running. I've read several tutorials on getting this to work, tried several solutions, and continue to gets errors (from page not found to "this drupal site is already set up"). Does anyone know if there are step by step instructions somewhere on exactly how to set up multisite on a windows box with IIS7?

The "base" drupal install is /inetpub/wwwroot/Drupal/DrupalTest/

Having very little knowledge of Windows servers is probably part of the issue. I really need basic step by step instructions and I have yet to locate any that assume you know essentially zero about windows. I've been taking notes so I can write some out if I eventually figure it out :)

One example I've followed: http://drupal.org/node/554336 : Yielded the "site already setup" when I tried to access the install.php from the second site.

I'm at the point where multisite would be nice, but if I need to use multiple instances of Drupal that's fine, I just need to be able to move forward with the content and be finished messing with the dang server, but I have no idea how to accomplish that as well.

After much digging, found out the combo of msSQL and PHP 5.3 caused the site to break. Reinstalled with PHP 5.4 and mySQL and it's running swimmingly!


Drupal 8 MVC: is there a Model? Coming from a Drupal background, I am quite thrilled at the idea of working with drupal 8 and symfony proper OOP and MVC practice.
Right now I I am building a module with a service and a controller and I am at a loss regarding where to put my data fetching logic (that should be used by both).
Understanding MVC policy I should put it in some kind of "model" structure but I can't find anything about that in Drupal documentation (sadly a bit lacking at the moment).
So what is the Drupal way for this?

Your data-fetching logic should be in its own service(s).

Symfony and by extension Drupal are not traditional implementations of the MVC architecture as there's no separate Model layer, like for instance in CodeIgniter.

One of the most important features in Symfony and Drupal are services, which are (or should be :p ) independent and reusable implementations of various functionalities.

So if you want data-fetching logic, then you can create your own service that does that and use that service in your controller, instead of polluting it with the queries (entity queries or otherwise).

I'll leave with a comment from Fabien Potencier (the creator of Symfony):

"It's up to you to create your model by hand or use any other tool, like an ORM" [...]I don't like MVC because that's not how the web works. Symfony2 is an HTTP framework; it is a Request/Response framework."

This statement might be debatable, but what I want to show here is the intent behind the choice of leaving out a well defined Model layer.


Printing fields from View using query The query below is taken from the related View. How can I get the field value for 'field_data_field_news_link', 'field_data_field_news_source', and field_data_field_news_date' for each row (news content type that is published and featured)? I prefer to use what I already have, which probably means changes are needed to the JOIN statements? Right now, all that is printing are the node titles.

If there is a more straight forward approach, I'm open to that too.

<?php
    $query = "SELECT node.nid AS nid, node.title AS node_title, field_data_field_news_date.field_news_date_value AS field_data_field_news_date_field_news_date_value, 'node' AS field_data_field_news_date_node_entity_type, 'node' AS field_data_field_news_link_node_entity_type, 'node' AS field_data_field_news_source_node_entity_type
        FROM {node} node
        INNER JOIN {field_data_field_news_is_featured} field_data_field_news_is_featured ON node.nid = field_data_field_news_is_featured.entity_id AND (field_data_field_news_is_featured.entity_type = 'node' AND field_data_field_news_is_featured.deleted = '0')
        LEFT JOIN {field_data_field_news_date} field_data_field_news_date ON node.nid = field_data_field_news_date.entity_id AND (field_data_field_news_date.entity_type = 'node' AND field_data_field_news_date.deleted = '0')
        WHERE (( (node.type IN  ('news')) )AND(( (node.status = '1') AND (field_data_field_news_is_featured.field_news_is_featured_value = '1') )))
        ORDER BY field_data_field_news_date_field_news_date_value DESC
        LIMIT 5 OFFSET 0";

?>

<?php $results = db_query($query); ?>

<?php $i = 0; ?>
<?php foreach ($results as $row) : ?>
    <!-- Custom HTML here -->

<?php endforeach; ?>

Some background. I am upgrading a project that I inherited to Drupal 7. The Drupal 6 version has all hard coded templates (not my doing!). The specfic page I am working on is of Page content type. This is the News node. On this node, I need to render all News content types and the selected fields. I also need to render this into custom HTML. I prefer not to go the Rewrite results route.
Changing anything in Manage Display would be changing the Page content type which I do not want to do.
Additionally, it seems print render($content['field_news_link']) would only render that field from one News content type?
So if I already have a template file for the News node (of Page content type), what would be my approach? Would I create a template for the view and then just print the view in my existing News template?

This is not good approach for Drupal.
Try to make the query in VIEWS UI, after that you have 2 options:

In the view add this option Show:Content | Teaser.
Create tpl file for that specific node (node--news.tpl.php), add if statement for the DISPLAY(view) MODE of the content type (full or teaser).
In the correct display mode you have all node fields that are enabled in the content "Manage display" tab (as admin structure->content type->news->manage display)
and use " print render($content['field_news_link']) ".
In the view add this option Show:Fields. Rewrite the option of the field "Rewrite results"->"Rewrite the output of this field" in the view and add there html + token of the field.


Search keyword with selectable exposed filters I'm trying to make a search view with one textfields and two checkbox filters (body, tags). The search text would only search the selected fields and would show results as summaries.

I've tried combined fields filters in Views, but the filters selected are all enabled. Is there was a way to toggle the filters via checkbox?

I think this is the module that you are looking for....

Better Exposed Filters

  The Better Exposed Filters module replaces the Views' default single-
  or multi-select boxes with radio buttons or checkboxes, respectively.
  Description fields and Select All/None links can be added to exposed
  filters to make for a better user experience.

  Views Filters is a powerful tool to refine the results returned by a
  given view. When you expose a filter, you allow the user to interact
  with the view making it easy to build a customized, advanced search.
  For example, exposing the node type field as a filter lets your site
  visitor limit their search queries to just blog entries. Better
  Exposed Filters gives you greater control over the rendering of
  exposed filters.

  Why use this module? Because it provides a better user experience than
  the default option. Try telling a client that they should click on an
  option, then scroll to the next option and ctrl+click on it. Don't
  just click 'cause you'll lose your first selection. Oh, and ctrl+click
  again to unselect an option... Yeah, not user friendly.


Improve extremely slow 'drupal_process_form' I am having problem investigating why our profile edit page is damn slow.

Call Stack
#   Time    Memory  Function    Location
1   0.0003  276344  {main}( )   ...\index.php:0
2   1.6889  39666816    menu_execute_active_handler( )  ...\index.php:21
3   1.6899  39668968    call_user_func_array:{C:\wamp\www\hyperDrupal\includes\menu.inc:527} ( )    ...\menu.inc:527
4   1.6899  39669448    entity_ui_get_form( )   ...\menu.inc:527
5   1.6901  39696720    drupal_build_form( )    ...\entity.module:1282
6   1.7842  40984120    drupal_process_form( )  ...\form.inc:385
(7) 17.3247 58502824    form_execute_handlers( )    ...\form.inc:903
8   17.3247 58503344    profile2_form_submit_handler( ) ...\form.inc:1519
9   17.3265 58492400    profile2_save( )    ...\profile2.module:621
10  17.3265 58492528    Profile->save( )    ...\profile2.module:311
11  17.3265 58491736    Entity->save( ) ...\profile2.module:918
12  17.3265 58492096    EntityAPIController->save( )    ...\entity.inc:333
13  17.3737 58517352    EntityAPIController->invoke( )  ...\entity.controller.inc:462
(14)    23.5502 90243232    module_invoke_all( )    ...\entity.controller.inc:355
15  23.5511 90247648    call_user_func_array:{C:\wamp\www\hyperDrupal\includes\module.inc:951} ( )  ...\module.inc:951
16  23.5511 90248096    bdEvent_entity_update( )    ...\module.inc:951
17  23.5511 90248832    bdE\bdEvent->dispatch( )    ...\bdEvent.module:44
18  23.5567 90332840    bdE\Services\profileService->run( ) ...\bdEvent.php:38
19  23.5568 90333120    bdE\Services\profileService->entity_get_values( )   ...\profileService.php:24

I created a stack trace in a new module and times are huge. Check step 7 and 14 both are after long operations.

What could be taking so much between

6   1.7842  40984120    drupal_process_form( )  ...\form.inc:385
7   17.3247 58502824    form_execute_handlers( )    ...\form.inc:903

and between

13  17.3737 58517352    EntityAPIController->invoke( )  ...\entity.controller.inc:462
14  23.5502 90243232    module_invoke_all( )    ...\entity.controller.inc:355

Based on the backtrace, you won't know why your site is slow.

You should run a proper PHP profiler and analyse the results which can identify the slowest components.

It doesn't have to be Drupal it-self, but could be lack of caching or misconfiguration.

Some suggestions:

disable modules which you don't need (e.g. Devel, core Database Logging module, etc.),
upgrade your PHP to the latest or higher branch,
recompile your PHP for 64-bit or higher architecture depending on your CPU,
use the faster storage device for your db files or whole LAMP environment (e.g. SSD or memory-based filesystem),
use PHP debugger or profiler to find out any performance bottleneck (e.g. XDebug Profiler, DTrace or NuSphere PhpED PHP Profiler),
run some time-consuming drush command under gprof profiling tool, so you can find some performance bottleneck as well.

If disabling slow modules or profiling won't help, see: How do you improve Drupal performance?


all modules that use the field api module Sorry if this is a basic question, is there a way to browse all modules created with the fields api. I am looking for some interesting ways to format and use fields.

You can find all the info to format fields in the field API

If you want to know how core modules implements the Field Api, you have to enter in every hook info page and there you will find the modules that implement this concrete hook. You can also follow the links to see the code.
Here an example of hook_field_delete and the location on web page:

On the other hand, if you want to know what contributed modules have implemeted the field API, you will have to look in the contributed modules page and make a filtered search with core = 7.0 and module categories = Fields.


Why is there quality loss on my image styles? This is the original image (610x405)

This is the image after applying image style (scale and crop) to 290x190.

Both image have the same aspect ration, yet there is visible quality loss on downsizing. Am I applying the right image style? What should I be doing?

Under admin/config/media/image-toolkit there is an option to set the JPEG quality. By default this is 75%, so you should be able to up that to whatever you want.


Drupal site that points to a non-drupal .html page I'd like to configure my Drupal 6's site's front page to be "foo/index.htm", a hand-coded html file. But when I put that relative URL into Home › Administer › Site configuration › Default Front Page, it complains "The path 'foo/index.htm' is either invalid or you do not have access to it." It's a unix filesystem and everything is world-read, and the directories are world-execute. What could be the problem here?

The issue is the path in question here must be a valid Drupal path, not a Unix path/filename.  I'd suggest investigating hook_menu() as a first step of learning about Drupal paths, callbacks and so forth.


How send a node as a newsletter by rules in Drupal 7? I want to fetch a node of custom content type that one of its fields has a specified value and send all node's fields to all users that have a specified role with rules when cron maintenance tasks are performed. Any idea?
Thanks

I will only provide some pointers as it would take me an hour or more to write out the steps.

It would be best to use Rules scheduler, rather than a views loop to
send this info. Every cron run you don't want to have to loop
through all of your node to check to see if one needs to be sent.
Enable Rules Scheduler.
Create a Rules component with an action of send email. This will
contain all of the email structure including your field tokens for
your node. The to field will be all users of role "INSERT YOUR
ROLE".
Then create a rule to schedule that component when a node is saved.
Use condition "entity has field" to pull your "trigger field" into
scope. Then add a second condition, "Data comparison" or "data is
empty" (negate if needed as I do not know what type of field your
going to trigger this off of).
Set the schedule time to be the current date. Rules scheduler only
happens on cron anyway, so this will ensure the next cron run it
will send.

Note: Rules and more specifically core does not support html emails out of the box, so use something like mime mail, Html mail or mandrill module to do this. If your nodes contain images that need to be sent, then you are going to need to add a special filter for those fields so that add your site root is added to all images and links. This way it doesn't use relative paths and break your images/links. Use the Pathologic module to do this.


Content Type with People (list of people) in Select List to Choose From diving deep into Drupal 7 as a noob and wondering how can I create a field (select list) in a new content type that pulls in all the users in the system? I'd like to be able to associate certain content with a person, not necessarily as the author, but as the "person in charge of this area" for example. I'd like to show the persons name and some other info from the "people" area of the Drupal 7 core.

I am thinking I should use the people area rather than create a new content type for people. I added new fields to the "new user" form.

Any thoughts or ideas?

EDIT:::

Did find https://drupal.org/project/references module that seems to work great. However, I still would like to know if using People area is best for storing all users / people associated with my Drupal site. Thanks :)

Personally I often use Entity Reference, but I think this answer is the same regardless of the choice between Entity Reference and References modules. Both modules allow you to define a relation between two entities. If you need a reference from a node to another entity, this is a good solution.

  I still would like to know if using People area is best for storing all users / people associated with my Drupal site.

When you say "People area", I think you mean Drupal's built-in user management. Users are fieldable entities, just like nodes. If you need to store data about a person, you can use both the user entity or define a "Person" node type. If the persons you're adding should be able to log in, now or in the future, you definitely want to create users. If they will never need to log in (for instance, you're building a site about people in ancient Rome), I would choose nodes.


User registration silently fails - how to debug? On our Drupal 7 site, user registration silently fails.
Drupal doesn't even reach the form's validation functions.

What we checked:

disabling javascript didn't help.
Removing installed modules related to registration such as : logintoboggan, user_registrationpassword didn't help.
Error logs show nothing.
The user module is of course enabled, people are able to login as usual.

Please advise where to put tests to see where execution is stopped.

Thanks in advance

Amnon

Recommended steps to trace the error:

Look at watchdog (which you did)
Look at the systems php and apache (or whatever you use) error logs
Take a local copy of the site and start digging

You can find your system logs (php and apache) by looking at the php info under "Admin > Reports > Status > PHP".

For local debugging: http://ratatosk.net/drupal/tutorials/debugging-drupal.html

My first point of entry would be the form definition. You could try for example to add an #after_build callback that get's called once the form has been fully build, and then check which validation and submit handlers are registered.

In your case I would suppose though, that you don't need to go that far. It's probably pretty basic error that will show of in the system logs.


How can i configure the core search module to also show results for incomplete words? I see that the results page only shows results if the "keys" parameter matches a complete word. how Can i configure the core search engine to also show results for incomplete words?

I am using core search module .

Actually there's a quick way to set this up with the Search API and the Search API Database Search modules. No need for Solr.

Enable both the modules and go to the Search API configuration page
(admin/config/search/search_api)Add a server and give it a recognizable name (such as "MySQL"), make sure it's enabled.

Choose the following service class: Database service (normally the only option. If you don't see it, make sure that the "Search API Database Search" module is enabled).

Selecting this service class will provide you the option Search on parts of a word (make sure you enable it). Now hit "Create server".

Next, go back to the Search API configuration page, and add an index. Again give it a recognizable name, such as "Contentindex", and make sure it's enabled.
Select the server you recently created (in this example "MySQL").
Datasource options: check the content types you want to index (the description of this field may be a bit confusing, but make no mistake: you should check the content types you want to index, not the ones you want to leave out).

You could check "Index items immediately", but that depends on the size of your content. This option is alright for smaller websites. In the other case: let cron take care of it. Hit "Create index".

Next, you want to enable the fields (in the fields tab) to that very index, e.g.: content type, title, status and author - and hit "Save changes" (we'll take care of the related fields later).

Then you want to configure the filters (in the filter tab). Here you can enable the bundle filter, if you want to finetune the content types once again (probably won't need to).
Down below you'll find the highlight filter, to highlight the search word in the results.
Now return to the fields tab and unfold the "Add related fields" tab. Add all the fields of which you want to get the content indexed, and hit Save.

Finally go to the "view" tab of the index, and index now all the items.
The last step is to create search results page and search block in Views, which only takes a few minutes.

Make sure the submodule Search Views is enabled and create a view page which will show "Contentindex" (select the name you gave to your index configuration instead of "content" which is selected by default.

Add all the fields (make sure your format is "fields") that every search result should consist of (title [link to content], body, …).

You'll notice that these fields look like this Indexed Node: Title
Add an exposed filter: Search: Fulltext search; and select the following in its settings: Contains any of these words, and use as: Search keys.

You're done!


How to restrict access to edit image file while still giving permission to edit image title? I want to restrict the possibility to edit or delete the image file, but still make it possible for users to edit the alt and title attribute.

What is best approach to do that?

It can be done using Image Field Permissions module.

The Image Field Permissions allows you to set permissions to view, create and edit the image file, title and alt attributes.


How can I use a Drupal 6 database in Drupal 7 without upgrading that database? I am new in Drupal. Currently I am working on one project where I am using Drupal 7.12. My client had one project in Drupal 6 of which database he wants to use in the Drupal 7 project. I can not upgrade the Drupal 6 to 7 as it's a completely different instance but he wants to have same userbase and other things in the new project i.e Drupal 7. As per knowledge DB structure of Drupal 6 and Drupal 7 is very different and hence it's not going to be very easy to use the Drupal 6 DB in 7.

Please suggest me any way to use Drupal 6 DB in 7.

Simply put, you cannot unless you are willing to rewrite a lot of Drupal 7 parts.

One thing you can do, is to implement cron jobs to export changes in version-independent format like XML on source site, and import them from XML at target site.

Alternatively, you can use Services module and make one page call the other to perform certain tasks, like user login or article reading.


Is there a way to set block visibility programmatically without using the PHP Filter module? By enabling the core PHP Filter module, I can use PHP code to set the visibility of a block in the block configure page.

But I don't want to enable the PHP filter module for security measure. So is there a way to do it in custom module? I can't find a hook doing so. And a close hook hook_block_view_alter can only change the block content.

Yes. Setting the blocks content to false will hide it from the display and will hide the region if there are no other blocks present. I'd imagine you would need a setup similar to the following:

$block['content'] = _my_module_custom_block();

...

function _my_module_custom_block(){
    if( HIDE_CONDITION )
        return false;
}


How to show the edit form of a page just below the page itself in the frontend? Just wondering if is there a way to expose the edit form of a page just below the page itself in the frontend.

Let's say I have the page Services, if you click a the edit tab you go to the admin page where you have the fields title and body for this page, here you can change its values and save.

I need to show the edit form (fields title, body and the button save) in the frontpage, just at the bottom of the page.

UPDATE: base in neok's answer: But I can not use $output var in utilities_block_view($delta = '') {

    function utilities_preprocess_page(&$variables, $arg, $delta=0) {

      if(arg(0) == 'node' && is_numeric(arg(1))) {
        $nid = arg(1);
        //you need to include node.pages
        module_load_include('inc', 'node', 'node.pages');
        $output = node_page_edit(node_load($nid));

        return $output;
      }
    }

    function utilities_block_info() {
      $blocks['edit_node_form'] = array(
        // info: The name of the block.
        'info' => t('Edit node Form'),
      );

      return $blocks;
    }

    function utilities_block_view($delta = '') {
      // The $delta parameter tells us which block is being requested.
      switch ($delta) {
        case 'edit_node_form':
          // Create your block content here
          $block['subject'] = t('Edit node Form');
          $block['content'] = $output;
          break;
      }

      return

 $block;
}

You can output edit form of current node with node_page_edit function. So you can create a block programmatically(show this block only on node pages of your content type - Services for example) and output edit form with node_page_edit.

  if(arg(0) == 'node' && is_numeric(arg(1)) {
    $nid = arg(1);
    //you need to include node.pages
    module_load_include('inc', 'node', 'node.pages');

    $output = node_page_edit(node_load($nid));
    return $output;
  }

Here you can find an example how create block.


Open inline link in modal/colorbox I have the colorbox module installed so I assume there's a way to do this with it, but I've had no success. Pretty much what I'd like to do within the WYSIWYG editor is have a link to an external website open up in a colorbox modal. I have forms hosted on a third party website, so instead of having users leave my site, I'd like the ability to have them just see that external form in the colorbox.

How do I achieve such a thing? I've tried adding the colorbox-node class to no success and also tried creating my own class and then in a custom js file have the following code:

 (function($){
    $(".custom-class").colorbox({iframe:true, width:"80%", height:"80%"});
 }(jQuery));

The above code fails when I inspect it with the following error:
TypeError: $(...).colorbox is not a function.

I'm also using a bootstrap sub-theme but I don't think the modal component would be of any use, would it?

You just need to make sure the library is added to the request.

For example, to include the library on every page:

function THEME_page_attachments_alter(array &$attachments) {
  $attachments['#attached']['library'][] = 'colorbox/colorbox';
}


How to place two Fivestar widgets on the node for voting? I would like to place the fivestar voting widget both to the beginning and to the end of my node. I do not talk about two different ratings, I'd like to let my readers vote in both positions. I read the code of Fivestar, but I did not find the solution in the module source. I think the JS code would get wrong if two voting widgets were present on the page.
Do you have any idea how to solve this problem, how to duplicate the voting widget somehow..?

I'm using Drupal 6 btw and Fivestar 1.19.

you can use a PHP code like this

$node=node_load($nid);
print fivestar_widget_form($node);

the forms will have different ids so the javascript will work

you have to create a custom php/tpl file for this node-CONENENTTYPENAME.tpl.php by copying the contents of your node.tpl.php  and include there the custom code...


How to assign a new icon to a pager? The current default pager in Views Paging Drupalgap is easily neglected.

Can I assign it a new icon or create my own pager button? Currently, what I know is to put it at the top or the bottom using pager_pos: 'bottom', but nothing else.

Thanks to Tyler. I follow his suggestion and have solved this by adding the theme_pager_link() to app/themes/my_theme/my_theme.js. Here is what I added:

function my_theme_pager_next(variables) {
  try {
    var html;
    variables.page = parseInt(variables.results.view.page) + 1;
    var link_vars = {
      text: 'Next Page',
      attributes: {
        'class': 'pager_next',
        'data-icon': 'fast-forward'
      }
    };
    html = theme_pager_link(variables, link_vars);
    return html;
  }
  catch (error) { console.log('my_theme_pager_next - ' + error); }
}

function my_theme_pager_previous(variables) {
  try {
    var html;
    variables.page = parseInt(variables.results.view.page) - 1;
    var link_vars = {
      text: 'Previous Page',
      attributes: {
        'class': 'pager_previous',
        'data-icon': 'fast-backward'
      }
    };
    html = theme_pager_link(variables, link_vars);
    return html;
  }
  catch (error) { console.log('my_theme_pager_previous - ' + error); }
}

now the pager become like this:


Enable all languages for multilingual site I notice I can add languages one by one on this page
mysite.com/admin/config/regional/language/add

Is there an easy way for adding all languages?
Maybe there is a command with drush?

No - there is no drush command for this and you would want to do this one by one because you're going to need to upload your specific po translation files from Drupal.org (one reason its not practical to make this an option with the base install for n languages)


Thousands separator (comma) in term id I'm rewriting the results in a view. I've added taxonomy term ID field and hidden it from displaying.

This is the rewriting code:

[name]

This is the result generated:

Constitution

The problem is the comma in [tid]. I want Drupal to not to insert comma there i.e.. instead of 1,007 I want 1007.

Go to your view. and Click on Taxonomy term to configure the field. Make sure to select the Thousand marker as <none>.

Then you can use this as replacement pattern in your href path


How to calculate user scores based on 3 variables to assign an appropriate text label? I need to calculate a score for users in D7 based on 3 variables and then assign an appropriate text label and a CSS class.

So, using data from Voting API, time ago joined, and number of nodes published, it needs to select and display one of 15 text labels such as "Promising newcomer, reliable veteran, etc".

Given that I am a site builder with limited PHP skills, where should I start? Should I setup 15 different rules to set a value on a list field?

Before investing time in Computed Field, Display Suite Custom Field or Views PHP, I would love advice from the Drupal community.

Looking for something similar to SE badges.

A possible answer is to trigger Rules Actions based on a combination of Rules Events that happen asynchronously, and optionally after they were repeated multiple times. Which also requires some type of recording of the progress being made. Pretty challenging specs, but there is a solution (module) for it, as further explained below.

Goals module

You may want to look at the Goals module (disclosure: I'm its maintainer) as a possible alternative. To start using it only requires typical administration tasks (configuration), though it does come with various hooks also for custom module development (if you want to).

Since the Goals module is entity based, it has out-of-the-box integrations with modules such as Views, Rules, Flag, etc.

Requirements mapping

  I need to calculate a score for users in D7 based on 3 variables and then assign an appropriate text label and a CSS class.

calculate: that's what Goals will do for you, by recording the progress made on the completion of each task required to reach a goal.

3 variables: that sounds like 3 tasks to be completed to achieve 1 goal.

assign an appropriate text label: you can optionally attach a (custom) image to each goal. The goals completed by a user, can be shown on a Views block included with Goals, with title "Your completed goals".

  So, using data from Voting API, time ago joined, and number of nodes published, it needs to select and display one of 15 text labels such as "Promising newcomer, reliable veteran, etc".

using data from...: if you can think of a Rules Event to discover these events, you use the appropriate Rules Action (provided by Goals) to record progress on the completion of a task. E.g. if 1 such task would be to "create 10 nodes of type XYZ", then each time such nodes are saved (there is a Rules Event for it!), then Goals will record so. And if 10 such nodes were recorded, the task is considered completed. And if all tasks of a specific goal or completed, then the goal is reached.

Here is a screenprint of a rule to record a task activity about posting comments:

15 text labels: that sounds like 15 goals you'd have to configure using the admin interface of the Goals module (no custom coding involved).

More details

For more details about the Goals module, refer to my answer to "How to implement gamification in a Drupal site and award incentives?".


How to sync two different content types? I'm going to build a website for a magazine.I have two different content types. In the first one, I will post the first page of magazine. But in the second one is for articles.
Now, my problem is:
I want to show just articles which are related to the issue which displayed on the top. I know how to show latest content [for first content type which includes first page], but i don't know how to show its articles under it. I guess,I would use views, but I don't know how.
to be more clear: I want something like this site.

Assuming you have an Issue content type, and an Article content type

Install References and enable Node References.  On the Article content type, Add a Node Reference field (could name it "issue") and restrict its options to nodes of type Issue.

Then create a View of Articles and add (under Advanced) a Contextual Filter of Content: Issue (and if you are using url aliases for the Issues, then provide the Contextual filter with a default value of Content ID from URL).  Make it a Block display.

Then display the block on Nodes of type Issue, and it should work great for you.


Refer to value in field in body UPDATE: Although the answers below were correct, I ended up resolving the issue by editing the stylesheet to refer to those specific locations.

If I create a custom field and set it to hidden, is there any way I can call the values from those specific fields in the body?

For example if a field called color in an article is set to red, is there any way I can make the background of a div red.

Try what I suggested here: Getting a field's value from an entity

Replace field_get_items('entityform', $entityform, 'field_myfieldname')

with

field_get_items('node', $node, 'field_myfieldname')


Render taxonomy type custom fields individually I'm kind of a twig newbie so I'm hoping that someone can point me in the right direction.

I've added a custom field field_url to a taxonomy type called field_type_poi. How would you render that taxonomy type's individual field in node.html.twig?
I know that I can use {{ content.field_type_poi }} to render the entire contents of the taxonomy type, but I'm looking for a way to render one field specifically.

{{ content.field_type_poi }} doesn't necessarily render the entire content of the taxonomy term. You can select the field in the tab Manage Display where you've added the field field_url to the vocabulary.

If you need multiple field selections, here only this field, but in all other places the default selection, then add a custom view mode in Custom Display Settings at the bottom of the page.

Finally go to the content type and configure the  field field_type_poi in the tab Manage Display to be rendered in the view mode you've configured above.

Edit:

If you want to use different fields from the taxonomy in different locations you would need to clone the field, see Show field twice in node page, or install the module Twig Tweak and render single fields in Twig:

{% set tid = node.field_type_poi.target_id %}
{% if tid %}
  {{ drupal_field('field_url', 'taxonomy_term', tid) }}
{% endif %}


How do I create a route that is specific for a subdomain? I'm looking to create a "subdomain" path to my custom controller running on a Drupal 8 site, with routing and hopefully without the need for an additional module.

The idea is to for example have a route like account.example.com or dev.example.com point to a custom controller I've made in my module. Or a path like api.example.com for external REST queries.

All the documentation describe just the traditional example.com/path methods, and googling resulted to nothing, but the domain module, which seems excessive and maybe for a different purpose even.

What I wish to achieve is not a separate installation sharing the content, but just a path to my controller that is domain-specific, like the i18n module is able to provide the language parameter as subdomain or path prefix.

If you want to set a controller for subdomain you just create a subdomain and handle it by DNS and web server, then set your subdomain path as root path for the subdomain on your web server, I mean both main domain and subdomain will be the same. As you said, you can create a route/controller for them (because the code and modules are the same, so routes will be available on both).

If you don't want the subdomains available on your main domain, on your handler check the domain name; if a request comes from the main domain, don't return the result for it. (Redirecting it to the homepage could be an idea.)

But the power of Symfony shows itself to us: Instead of manually handling the domain and subdomain filtering on the route, use host in the route definition.

   host: "dev.example.com"

Take a look at How to Match a Route Based on the Host for further help about using that directive.


Altering Create New account tab link in user login page I tried using form alter for menu of tabs in /user page, that shows

"create new account", "login", request password

is it possible for us to alter the link so that the create new account can go to "customlink" instead of "user/register"

in drupal 7?

thank you!

Well, you could use hook_menu_alter() to change the call back function of that menu item:

function MY_MODULE_menu_alter(&$items) {
  $items['user/register']['page callback'] = 'my_custom_function';
}

And then you could redirect to a new page in the callback:

function my_custom_function() {
  drupal_goto('customlink');
}


Add user picture to profile 2/any entity for that matter... I've disable user pictures in User account and want it displayed in Profile2.  I can add a field for Image.  But, it's not recognized as the official user picture; so it can be used in comments, node views, etc.  How can I do that?

You have two options.

You can use theming to make whatever you want use the profile picture.

Another options would be to add the picture from the profile to the user object on load.

Third option would be to sync the user picture with the profile picture whenever the profile entity is saved.

If you want it to take effect everywhere, you need to use the third options, which adds the headache of having the same data store twice and the problems such a thing can bring,


Menu links duplicated on node/%node/edit pages I've a strange problem.
I've a multilingual site with many menus configures as "Translate and localize".

Everything works, every menu link has his language, but ONLY when I go to a node/%nid/edit page the system prints all links, on both language (on every language)

This behaviour there is on every theme. I've i18n modules enabled.

What's wrong?

I'm not sure i fully understand the question, but please take a look to this post:

https://drupal.stackexchange.com/a/96963/30465

It seems related to your question.

I this it will be related to the language configuration fallback (since there is no language suffix inlcuded)

You could for example try

http://www.example.com/en/node/%nid/edit

if that works correctly (and only shows the engish menu links), you know that it will be a problem with language fallback.

Hope this helps, feel free to let me now if you need more!! :)


Artifical part of URL path, not corresponding to node, triggering view attaching Hello Drupal enthusiasts,

I have a menu structure, which has its equivalent in url paths. Example:
department/area/project. This path works fine and now I want to attach some View when last part of url is "releases" (department/area/project/releases).

Any ideas? Should I rather take closer look at Views options or some other module (Pages?) or programatically by hook_menu and some wildcards?

=========================================================
EDIT (thanks to lack of ability of answering my own question):
I think I figured out something close to what I need. I create View, type Attachment (thanks to EVA module). I configure contextual filter, and specify validation criteria with PHP code pasted to UI of Views:

$path_arr = drupal_get_destination();
$path_str = $path_arr["destination"];
$path_explode = explode("/", $path_str);
$path_last = end($path_explode);

if( $path_last == "releases" ) {
 return true;
}

And after that the certain view would be shown in case of last part of path equal to releases. Now some ENTITY CONTENT SETTINGS to cover only selected content type.

If function arg would accept -1 this could be done as fast as

if(arg(-1)=="releses") { ... }.

How about performance of such a solution? Is it much slowing down the whole thing?

In the Page settings section of the view editing form, there is an item labeled Path. Click on this item. It allows you to enter the path under which the view will be accessible.


Why is Views "Query Execute Times" so high? I have a basic view that shows a list of members and their user points. The views query output show that this query takes over 1500ms to run.
Query build time    24.71 ms
Query execute time  1546.84 ms
View render time    88.29 ms

SELECT users.picture AS users_picture, users.uid AS uid, users.name AS users_name, users.mail AS users_mail, users.created AS users_created, userpoints_total.points AS userpoints_total_points, 'user' AS field_data_field_motorcycle_user_entity_type, 'user' AS field_data_field_review_count_user_entity_type, 'user' AS field_data_field_address_user_entity_type
FROM  {users} users LEFT JOIN {userpoints_total} userpoints_total ON
users.uid = userpoints_total.uid WHERE (( (users.status <> '0') AND
(users.uid NOT IN  ('1')) )) LIMIT 10 OFFSET 0

When I copy and paste that query into myphpadmin and run it there it takes less than 5ms. What else is happening in the "Execute Time"? I coudn't find any good help about that on the web.

When testing be sure to turn off the query cache  SET SESSION query_cache_type = OFF

Next step is to run EXPLAIN on the sql.

EXPLAIN SELECT users.picture AS users_picture, users.uid AS uid, users.name AS users_name, users.mail AS users_mail, users.created AS users_created, userpoints_total.points AS userpoints_total_points, 'user' AS field_data_field_motorcycle_user_entity_type, 'user' AS field_data_field_review_count_user_entity_type, 'user' AS field_data_field_address_user_entity_type


How to execute a specifc job after some time interval like 5 minutes? I want to perform a job after 5 minute, I explain what I mean with an example:

"I connect to bank gateway, register my order there,they give me transactionId and told me  I should verify transaction after 5 minute,

I wrote register (register_my_order) and verification (verfiy_myorder) code, but I want set interval 5 minute between them.
My Pseudocode:

transctionId= register_my_order(myorder)
delay(5minute)
verfiy_myorder(transctionId)

One of my solution was using rule scheduler (a sub-module of Rules),

I try below solution but not worked

Create a rule component and get transctionId as parameter
In action run my verfication fuction with provided parameter as transction Id

then in my code between register_my_order(myorder)  and verfiy_myorder(transctionId) I create  rule task schedule with below code

    //$result = rules_invoke_component('rules_run_after_5_minute', 'param1');
     $state = new RulesState();
    $state->addVariable('tref', 'test', array()); //tref is name of parameter and test is passed parameter to it
    // 3rd parameter is called $info it must be an array, but i don't know it's function
   $task = array(
    'date' => time(), // timestamp
    'config' => 'rules_run_after_5_minute', // it is my component machine name
    'state' => $state,
);

$result=rules_scheduler_schedule_task($task);

any idea that how can I create task schedule programmatically and work correctly ( my code create it but not getting  run  )

Using the "Rules Scheduler" sub-module of the Rules module seems indeed a possible approach.

However, be aware that the actual trigger wil only happen the next time your Cron job runs, similar to what's mentioned in the question about "Is there anyway to get more control over when CRON runs?". Maybe that's what the missing part is that you're looking for?

So at least as a way to check if the logic of your code is running as you want, try to trigger running your cron job from the admin panels. If that's how such check is performed at least 1 time, then your question is like simplified similar to the question I referred to in my link above.

PS: I don't it says in your question (correct me if I missed it), but if the first time your "verify order" indicates that the verify didn't pass yet, make sure to reschedule the same rule to be executed 5 minutes later on also.


Drupal queue task sequencing Is there a way to use Drupal Queue API to sequence the execution of tasks, like in a pipeline?

My use case is pretty simple: I have a number of tasks executing in the background, doesn't matter their order because they are self-contained. However, I'd like a single task (of a different function) to execute after all the others are done.

How would this be done?

Together with a bunch of other people we created the queue runner and it does support this use-case and we use it internally. You can add a collector task that includes all your small tasks and you add a second collector task so it is executed after the whole lot of small tasks. See the API file for the queue runner to figure out how you should do this exactly. It works with the default Drupal queue class so you can even extend it with external queue systems such as http://drupal.org/project/aws_sqs (amazon queue class) or others.

http://drupal.org/project/queue_runner Works for D6 and D7


How to create User Account Registration form with Webform? I am using Drupal 7. I have Webform with 6 fields:

Your name
User name
password
Email
phone number
Website

If we submit it will store in database, but here I need username & password should store in "User Account Registration" form also.

We can add fields from Configuration -> People -> Account settings for other fields, but it doesn't work in this situation. I need to store the User name & password values to "User Account Form" and then to login with that username and password.

Storing the password as a regular Webform field is not nearly as secure as using Drupal's built-in user registration password. I would recommend instead of trying to create user registration via Webform, that you use something like Profile 2 to add additional information fields to the core registration form.


Webform: How to prevent rendering of private fields I'm using Webform. Because I wanted to add custom flag for submitted data, so I used this approach with private fields https://drupal.stackexchange.com/a/137847/24385

Is it possible to render such form without private field only on my web? In admin section is everything ok and don't want to change nothing here. Private fields are shown only to users with results access. But what can I do if I want to display the same form for all users. On the web it doesn't matter for me whether user is anonymous and logged in. I need to display form without private fields here. Private fields are important to see only in admin section.

Thanks a lot :)

I've found that best solution is to use hook_form_alter to remove element from rendering. It can be achieved by this workaround: $form['submitted']['my_field']['#access'] = FALSE;


How to adjust the login pages with bootstrap? Components used:

Bootstrap 3.7.1.
Drupal 8

I would like to adjust the size of the login screen (and related screens) to a size of 6 grids. So I think adding the following bootstrap class

col-md-6 offset-md-3

to

.block-user-login-block

will do the trick. I can add this to the block css.

But bootstrap needs to have .row class just before this. How can I easily solve this?

Solved by changing the bootstrap class to

col-md-6 col-md-offset-3


Watchdog file growing out of control My ISP has a 1Gb limit and blocked my site.
The file grew to 16 Gb in less than a week. I emptied the watchdog sql file in the database with phpAdmin. This overcame the block and the site restarted, with an SQL error on the front end and hundreds of SQL errors on the back end, which still, nevertheless, will start.
In less than 10 minutes after emptying the file, the size had returned to 1 Gb. 45 minutes later, there were 250,000 rows occupying 3 Gb.

The site is normally quiet. It has had little in the way of addition in the last 6 months and serves about 200-500 pages a day.

The logged error is the following.

  Deprecated: assert(): Calling assert() with a string argument is deprecated in Drupal/Core/Plugin/DefaultPluginManager.php on line 151

You have a few options here.

For the short term, you can disable database logging on /admin/modules/uninstall until you can get the full situation under control.

You can disable assertions.  Search yout settings file(s) and set

assert_options(ASSERT_ACTIVE, FALSE);

You should also edit your php.ini file to set zend.assertions=0.

You can then enable database logging again.

That said, it seems like you are running an old version of Drupal.  PHP 7 changed the way assertions work, this was fixed in core in late 2017 and was part of Drupal 8.5.  You should update your site to fix this, and get the security updates that have been made since then.


Adding a dependencies in theme info file Can I use dependencies[] = module name in the theme.info file? I want to create a drupal theme where I using some dependencies module, if I able to mention the dependencies in theme info it will easy to install the theme.

Nope, themes do not have such a directive in their info files.

Themes are supposed to be module independent. The "designed" way to do it is to move all module-dependent code to a custom module, and in relevant parts of your theme simply test for existence of data your custom module was supposed to provide.