Module to do an action based on content type user sees

Assuming you're using Drupal 7 you can do all of this in hook_node_view(), e.g.

function MYMODULE_node_view($node, $view_mode, $langcode) {
  // Check the node type and that the user is viewing a full node page
  if ($node->type == 'article' && $view_mode == 'full') {
    // Get some field values from the node
    $field_items = field_get_items('node', $node, 'field_name');

    // Get the first field value.
    $first_field_item = array_shift($field_items);

    // The index will depend on the type of field; for taxonomy term refs it's 'tid'
    $value = $first_field_item['tid'];

    // Perform some complex operation on the value.
    $new_value = MYMODULE_complex_op($value);

    // Add the new value to the node content, to be found in the $content array
    // in node--article.tpl.php
    $node->content['my_new_value'] = array(
      '#markup' => $new_value
    );
  }
}

In your template file you'll be able to call print render($content['my_new_value']); to output the variable to the page.

Obviously that'll need some adjusting for your own needs but hopefully it'll help.


Drupal 8 - some child pages are not visible on particular book using view

I'm not too experience in Drupal.  But normally I would not use Views for the child pages.  If the book module is enabled, the BOOK NAVIGATION block will be available to list with hierarchy like a table of content.  You can select in the option to display only for book pages under a particular book.  Not sure whether this helps.


Is it possible to accidentally enable all views at once?

Accidentally? Possible, but not likely. But I guess it depends what you mean by "accidentally" exactly...

There are perhaps 3 obvious ways to programmatically enable/disable a view (see https://drupal.org/node/820110), plus I'd imagine a few derivatives and/or lower level methods. But enabling a View isn't that straightforward, some manipulation of serialised PHP vars needs to happen somewhere, so I'd say the chances of it being done accidentally are slim at best.

But yes, it's possible to programatically enable all Views at once. It's also technically possible for it to be done via a DB query (i.e. outside PHP), but it would be messing with a serialised PHP array, which MySQL et al don't know how to process, so you can probably rule that out.

Now, if there's a legitimate code/process in your site that intentionally enables one or more Views in certain contexts, and it's being called accidentally, or without your knowledge, that's a different story. If that's the case you're probably in audit mode; get a backup of the site from before the update running, switch off modules until the problem disappears, and when you find the culprit, dig into the code to see what's happening.


How do I define this simple views relationship?

The very first point is that, the table itself should be defined in order for Views to access it. It's not necessary to define all the fields in the table; just define what you want to access.

You can however, define additional fields that are not in the table. The default convention in the $data array is the table name => column_name but you still can add non-existing keys to the array without Views looking for that field in the query.

Try this:

<?php

$data['person']['addresses'] = array(
  'title' => 'Addresses',
  'help' => 'Load persons address information',
  'relationship' => array(
     'title' => t('Person\'s address'),
     'base' => 'address', // base table
     'base field' => 'person_id',
     'relationship field' => 'id',
     'handler' => 'views_handler_relationship',
     'label' => t('Address information'),
     'help' => t('Address information'),
  ),
);

You will now see a new relationship, Address, to join the table, along with a checkbox to make it an INNER instead of a default LEFT join.

Similarly, you can add additional fields, arguments and filters without having a real field with the array's key in the table.


Generally this is a matter of figuring out which preprocess function or functions are setting those classes and then implementing those preprocess functions within your own theme and modifying the $variables['classes_array'] variable to meet your needs.

Without knowing what theme you're using as a base theme I can't say for sure how this is being done. But using the following steps you should be able to figure it out.

Figure out which template file (*.tpl.php) file contains the markup where the classes are being printed out, and note the name of this file. Example, 'comment-wrapper.tpl.php'.
Working backwards up the chain you should be able to find the preprocess function that's setting these classes.

YOURTHEME_comment_wrapper_preprocess()
BASETHEME_comment_wrapper_preprocess()
template_comment_wrapper_preprocess()

This will at least confirm that you're on the right track, and allow you to see in what context those classes are set and what other classes may be set.

Implement HOOK_comment_wrapper_preprocess() in your own theme. (Comment wrapper being the example here, you'll need to know the appropriate template file that's being used to know which preprocess function to implement.)
Modify the $variables array inside your template file to change the classes.

Here's some additional information about preprocess functions: https://www.drupal.org/node/223430


Unique field value per multivalued field collection

I had to do this the other day and found it easiest with a custom validation function.

Using hook_form_alter add a new validation function:

function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  //drupal_set_message("Form ID is : " . $form_id);
  switch($form_id) {
    case 'YOUR_FORM_ID':
      //dpm($form);
      $form['#validate'][] = 'validate_unique_field_collection_names';
      break;
  }
}

And then in your new validation function:

function validate_unique_field_collection_names($form, &$form_state) {
  $used_ids = array();
  foreach($form_state['values']['field_people_collection'][LANGUAGE_NONE] as $k => $item) {
    if($k === 'add_more') continue; // skip loop if key is add_more
    $user_target_id = $item['field_name'][LANGUAGE_NONE][0]['target_id'];
    if(in_array($user_target_id, $used_ids)) { // check if UID is in used array
      form_set_error('field_people_collection]['.LANGUAGE_NONE.']['.$k.'][field_name', t('Names must be unique.')); // if it is set an error
    } else {
      $used_ids[] = $user_target_id; // else add it into the used array
    }
  }
}


hide repeated data from my view table for some specific field

you need to remove the month and aggregate the salary field as SUM,
if you only want to suppress display of 2+ column values try the views merge rows module


Add a new colum with a button to field collection

Use the Link Module to add a link field to your field collection

  With this module links can be added easily to any content types and profiles and include advanced validating and different ways of storing internal or external links and URLs. It also supports additional link text title, site wide tokens for titles and title attributes, target attributes, css class attribution, static repeating values, input conversion, and many more.

And add the relevant bootstrap class to the output through the manage display UI.


How to show a views count for nodes that ar not available to anonymous users

Go to edit screen of your view. In right column, Advanced section, click Query settings.
Check Disable Query Rewritting. Now Drupal permissions will not affect views results.


AJAX doesn't work in custom form element

I believe you may need this syntax as your callback, I think because everything went to being 'static' when you moved your demo code from a form to a Element.

 $btnSendCode = [
  '#type' => 'ajax_button',
  '#value' => $element['#btnSendCodeTitle'],
  '#ajax' => [
    'callback' => ['\Drupal\aqr_basic\Element\EmailElement', 'email'],
    'event' => 'click',
  ],
];


I think that you are looking for JavascriptTestBase::createScreenshot() https://api.drupal.org/api/drupal/core!tests!Drupal!FunctionalJavascriptTests!JavascriptTestBase.php/function/JavascriptTestBase%3A%3AcreateScreenshot/8.2.x

See the following snippet from a core test:

  /**
   * Tests creating screenshots.
   */
  public function testCreateScreenshot() {
    $this->drupalGet('<front>');
    $this->createScreenshot('public://screenshot.jpg');
    $this->assertFileExists('public://screenshot.jpg');
  }


How do you include a translatable string in an update hook

No. Just call t().

get_t() was actually for early install and things like that, update functions AFAIK didn't need it (calling t() there is however often pointless, as it is highly unlikely that there is a translation for it already when you run the updates.)

t() calls a service now, and it will use the correct one depending on the situtation automatically.


Try something like (supposing "weight" module is used and weights are stored in the "weight_weights" table - to be adapted for another module ) :

$query = db_select('node', 'n');
$query->fields('n', array('nid', 'type'));
$query->join('weight_weights', 'w', 'n.nid = w.entity_id');//join can not be chained
$query->condition('n.type', 'portfolio', '=');
$query ->orderBy('w.weight', 'ASC');


Menu link to the most recent article with a certain taxonomy term

For your first question:

As your are displaying "Teaser" view of the node in your view, so you are getting two title of the node. If you want to hide the "Title" of the node and display the override title, then you can follow the below step.

Go to Administration -> Structure -> Views
Edit your views "latest"
Click on "Content" in "Show" setion under "Format" section of your views, it will display the popup.
Select "Fields" from form which is opened in popup and save the form.
Now, you will see "Title" and "Body" in your "Fields" section.
You can remove the "Title" from views or Edit "Title" fields and check "Exclude from display" check-box, so it will not display in views.

For Question 2:

If you want to append latest node title with path (latest), then I do not think, there is solution for this.

But, if you install "pathauto" module, then you can create url alias for the same or you can append term name with view path and can get term id for the term name.


Group Module: Join & Remove users from user account/profile 2?

I solved this. :)

I used the views_rules module to create a view that filtered a list of exactly what i needed (filtering the group type per user).

I then created a rule:

Before saving a user account
Condition if previous is equal to new saved (Negate). So it will only run if there are changes in the field in question.
Added View Loop i created. Add action > Delete entity mid from the view loop.

Done. This deletes or unsubscribes any unchecked boxes/groups.

Now to create any new memberships/subscriptions to selected groups...

I added condition...

-If field empty... do nothing

-Else

-Loop the field in question (gmem_created)

-Create new entity of type group membership

-Save a data value

Data: [gmem-created:group], Value: [account:field-yourgroup]

-Save a data value

Data: [gmem-created:user], Value: [account]

-Save entity

Entity: [gmem-created], Force saving immediately: true


Well I figured out that the field_evt_mat_download is actually in field_data_field_evt_mat_download so I solved the problem myself.


Are views cached through the core caching mechanisms or should I be setting the caching directly in each view?

WHAT: Core performance caching stores and serves the whole rendered page with a cache id of the URL. Views caching goes beyond this to cache just the view output.

WHY: It's great for logged in users; other blocks on the page may be more dynamic but the view doesn't have to run a query every time for every user... just the occasional user who generates the page cache upon cache lifetime expire.

SETTINGS: Allowing the "rendered output" to be fresher than the query is useful for things like marking content as new, otherwise just match them up.

BIG PICTURE: Drupal serves page dynamically, using a server to build pages in PHP and access a database (or in-memory cache). This allows awesome features and content editor velocity... but the trade off is needing to understanding caching and do it right.

MODULES!

There's also a lovely Views Content Cache module which clears views cache on content edit. If you want to go further you may want to check out Cache Actions as well, I'd recommend Rules to fine tune this.

Additionally, Blockcache Alter allows you to set "per role", page, user, etc. caching options for each block on your site.

You can also add Page manager and Panels. This allows you to do interesting things like setting the cache "per user", "per role", or a number of other very useful configurations. Though I personally avoid panels.

DOCUMENTATION: For caching and performance in general check out the Drupal.org page.


Rewrite negative number into positive numbers

For Drupal 7 you could use the Global: Math expression field to perform a mathematical operation. Load the initial field first, suppress it from display and use the replacement token within the Math field: (abs([initial_field])).

For Drupal 8 this field does not exist (yet), though there is a sandbox linked in post #10 here: https://www.drupal.org/node/2544670. It might work.


Listen and respond to ajax_command_replace()

From what I can tell, Drupal behaviors are simply callback functions that are called in two cases: 1. when the page is loaded initially, and 2. when content is added/removed via ajax.

You add your callback function to the global js object Drupal.behaviors (US spelling), namespaced by your module's name. My module is called 'watch' so I attach my callback functions to Drupal.behaviors.watch. Drupal.behaviors.MODULE_NAME is itself an object and has two elements that may be named 'attach' and 'detach'.

'Attach' is called during the initial page load and whenever Drupal's ajax adds new content. 'Detach' is called when is Drupal's ajax removes content, either before adding replacement content or removing it forever.

For the record my javascript looked like this:

(function($) {
  Drupal.behaviors.watch = {
    attach: function(context, settings) {
      // This code is fired both when the page is 'ready'
      // in the jquery sense, and when new content
      // is 'attached' via Drupal ajax. The settings
      // values that are available to us here
      // are provided in the third parameter of
      // ajax_command_replace() as an associative array.
      // My new content is already part of the dom
      // so I can act on it here.
    },
    detach: function(context, settings, trigger) {
      // Example detach callback.
    }
  }
})(jQuery);

I'm guessing Drupal behaviors can be extended to include all sorts of other behaviors beyond attach and detach and is probably very flexible besides, but that's beyond me right now.


How to pass variable to a view after submitting?

I'm only assuming but I would imagine that the form is redirecting somewhere after your submit handler, that's why the result of example_page is not being displayed. Also I'm not sure if you're copying the code or written it on StackExchange but you're missing a return from your hook_menu

This is how you'd normally pass variables to pages:

function example_menu () {
  $items['example'] = array(
    'title' => 'Example',
    'page callback' => 'drupal_get_form',
    'page_arguments' => array('example_form'),
    'type' => MENU_CALLBACK
  );

  $items['example/page/%'] = array( // % means variable
    'title' => 'Example arg',
    'page callback' => 'example_page',
    'page_arguments' array(2), // 0 is example, 1 is page, 2 is the % variable
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function example_page($arg) {
  return '$arg is: ' . $arg;
}

function example_form($form,&$form_state) {
  $form['name'] = array(
    '#type' => 'text',
    '#default_value' => t('Enter your name')
  );
  return $form;
}

function example_form_submit($form,&$form_state) {
  // No return from submit handler, but set redirect
  $form_state['redirect'] = 'example/page/' . $form_state['values']['name'];
}


I think you'd be better served using Syslog for logging without cluttering your database.


Commerce 2: Can Cash and Check payments be implemented?

You can do this by adding an additional payment gateway.

Add a role, Pay with Cash or whatever you want to call it.
Add a new payment gateway (at /admin/commerce/config/payment-gateways/add).

Name: Cash or Check
Plugin: Manual
Customer: Limit by Role: Pay with Cash role

The "Manual" gateway does not ask for any payment information, so orders with the manual payment selected (which only users with the Pay with Cash role will be able to select) will automatically be processed as completed when this payment method is selected.

If you want to record bank info for checks, you can make two separate gateways, one cash and one checks, and then customize the check gateway with additional fields.


How can I get final URL of newly added node from hook_node_insert()?

If you also implement hook_module_implements_alter then you can change when your insert hook fires, like this:

function mymodule_module_implements_alter(&$implementations, $hook) {
    if ($hook == 'node_insert') {
    // Move my_module_node_insert() to the end of the list.
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}

So now when your insert code executes the path alias should be available.


answering my own question.  was able to figure this one. the guest email is prepopulated in orderEventsSubscriber.php.


I can't change the currency to € for the Drupal Commerce module

I've experienced this bug myself in an older version of Commerce.
Updating to the latest stable version of Commerce fixed the issue.

Also make sure to change the currency on your product(s) too, as changing the global currency won't change it on any already defined products.


Use Field maxlength alter module

  Creating an update hook that alters the field tables
  Installing this module and simply edit the max_length in the admin    interface
  Installing this module and run the Drush command to modify the    max_length


Adding #ajax to checkboxes and getting selected values in callback

There is a module that can trigger an ajax callback on a form (content type) maybe that modules solves your issue http://drupal.org/project/conditional_fields.


Composer won't update Drupal Core, can't determine what is stopping it

I found some other threads that highlighted webflo/drupal-core-require-dev as being an issue,
In CLI I ran

composer show

This showed me that webflo/drupal-core-require-dev was set to 8.6.3

So I ran update in CLI:

composer update drupal/core webflo/drupal-core-require-dev --with-dependencies

This updated the require version to 8.6.5.
Upon checking Drupal Status Report it also triggered a warning requiring Database updates, so I ran:

drush updatedb

and approved"yes" to the 2 updates.

This removed the Database error from Status Report and I then ran the core update CLI again:

composer update drupal/core --with-dependencies

This time it worked, so I cleared cache and turned off maintenance mode:

drush cr
drush sset system.maintenance_mode 0

and the Status Report is now clear of errors and warnings.


How to use Views and Rules to activate a new node flag for existing OG members?

Step 1: Fix your rules Component

The "... seems to do nothing ..."-part of your question, is like a variation of "it doesn't work" ... which is extremely hard to debug without access to your site.

However, what I find bizarre about your Rules Component is:

You're using token site:og-context--node, but there is nothing in your rule that assigns a value to it. So wild guess: it's value is blank or something like that. If my guess is correct, then your rule "works as implemented, ie "it is doing nothing", because not both Rules Conditions are satisfied.
It is related to user = site:current-user. So you've to be a bit lucky to have this Rules Condition satisfied (it depends if the current user is yes or no member of some group which might be blank).

What I think is needed, at a minimum, is that you use appropriate parameters for this Rules Component, actually for all of your tokens you're using that start with site:.

To do so, have a look at this improved version of your Rules Component. The main difference with yours is that I introduced 2 parameters, and replaced all site:

{ "rules_using_parameters" : {
    "LABEL" : "A Rules component using parameters",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "flag", "og" ],
    "USES VARIABLES" : {
      "flagging_user" : { "label" : "Flagging user", "type" : "user" },
      "node_to_flag" : { "label" : "Node to be flagged", "type" : "node" }
    },
    "IF" : [
      { "NOT flag_flagged_node" : {
          "flag" : "subscribe_og",
          "node" : [ "node-to-flag" ],
          "flagging_user" : [ "flagging-user" ]
        }
      },
      { "AND" : [
          { "og_user_in_group" : {
              "account" : [ "flagging-user" ],
              "group" : [ "node-to-flag" ],
              "states" : { "value" : { "1" : "1" } }
            }
          }
        ]
      }
    ],
    "DO" : [
      { "flag_flagnode" : {
          "flag" : "subscribe_og",
          "node" : [ "node-to-flag" ],
          "flagging_user" : [ "flagging-user" ],
          "permission_check" : "1"
        }
      }
    ]
  }
}

You should be able to just copy the exported rule above, and simply import this Rules Component in your own environment.

After you did this, navigate to admin/config/workflow/rules/components in your own site, and then use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says Switch to direct input mode. Then you'll be able to enter some Node to be flagged. Use a similar technique to specify the Flagging and hit the Execute mode.

If both Rules Conditions are satisfied, then the node you selected will be marked as flagged by the user you specified.

So please do some QA-testing of this variation of your rule. And make sure to select accurate testcase (different from your own userid, aka site:current-user).

And if this QA-testing results in "... it still does nothing ...", then perform appropriate Rules debugging, as explained in my answer to "How can I display the value of a variable inside a condition?".

Move on to Step 2 after your QA-testing is completed (and you're sure the rule works as designed).

Step 2: Let VBO do the bulk of the work

This step is pretty easy ... Just create an appropriate view of all your nodes to be processed, and transform it into a Views Bulk Operations view. The clue to what you want VBO to do as an operation is ... you guessed it: Execute the Rules Component from Step 1.

If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.

Attention: to process many nodes at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...

Happy VBO-ing while Rules-ing!


How to move whole Drupal website on USB for localhost use using XAMPP?

If you are married to the idea of running your website via a USB Drive, you can always just download a lamp stack to your computer and configure it to look at usb drive as it's default home directory.

There are several options for this.

Xampp: General one size fits all lamp stack
DEV Desktop: A Drupal specific lamp stack
Mamp
Wamp

This is great for doing dev work on a duplicate copy of a site for testing in order to not screw up the production. The only problem with this is if you are trying to plug the usb to multiple computers you will have download the software each time and configure it look at the usb for it's root directory.

On the plus side using a local lamp stack you won't lose you ability to edit the site. It'll operate exactly the same way. With the exception that ftp ability will vary. Also it's good practice for doing standard Drupal Migrations.

NOTE: I would suggest if you try these options you operate from a desktop and not a USB. The USB could be for just keeping backups.

If this is something you deem acceptable I can expand on this idea.


You'll need to set your pathauto pattern settings to rewrite your URL. Goto Configurations > Search and metadata > URL aliases > Patterns. Set the pattern for your content type to:

[node:title]/[node:field_...]/[node:field_...]

Where the "node:field_..." is replaced with the respective tokens for your taxonomy fields.


Do page arguments in hook_menu get sanitized?

In D6

menu_execute_active_handler() calls the callback. However it gets it's arguments from menu_get_item(), which uses arg.

I can't see any sanitizing in any of that. So it looks like the answer is no.

In any case extra sanitizing can't hurt.


Why bootstrap navigation button does not expand?

The problem is in JavaScript: you should not include jQuery (and generally other libraries) through your theme.

Bootstrap requires newer versions of jQuery (I think v1.8+) and you should use jQuery Update module to upgrade it on your site.


Can I make interaction between views relations and views arguments?

Thanks for the suggestions Andrew, I ended up creating a custom argument-handler. It adds one (or more) extra conditions to the join. LEFT JOIN ... AND ....

function query($group_by = FALSE) {
  $this->ensure_my_table();

    $this->query->table_queue[$this->table_alias]['join']->extra = array(
      array('table' => $this->table_alias, 'field' => $this->real_field, 'value' => $this->argument),
    );
  }
}


Which module hook to use for CRUD operations on custom table?

You don't need to call any special hooks. You just need to create menu items for insert/edit/delete/list of data.

Here is an example module that create basic crud using custom table.

If you want to create listing with views instead of custom listing callback function you will need to use view_api and hook_views_data in your module for that.


How can I remove everything from a Commerce cart if a certain product is added, except that product?

This is the code I ended up using:

function MYMODULE_commerce_cart_product_add($order, $product, $quantity, $line_item) {
  if ($product->type == 'directory_subscription') {
    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);

    // Loop through the line items
    foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
      // If this is the product we're keeping, make sure the quantity is always 1.
      if ($line_item_wrapper->commerce_product->product_id->value() == $product->product_id) {
        $line_item_wrapper->quantity->set(1);
        $line_item_wrapper->save();
      }
      else {
        // Remove any other product from the order
        commerce_cart_order_product_line_item_delete($order, $line_item_wrapper->line_item_id->value());
      }
    }
  }
}

If anyone has any suggestions on how to improve the above I'd be grateful.


I agree with Clive, that this seems like a great deal of trouble, but what you should be doing generally, is calling field_attach_form(), and more specifically for nodes, node_form(), which calls the former. The arguments it expects are

You can see an example on the first here: Is displaying a working Field Widget Form on its own possible?


How to use the view_mode in hook_preprocess_flag?

view_mode key is not in variables object, which you get as argument. You can check for the same, by printing variables object.

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

However if u still want to get view mode, you can use somewhat like below.

function bartik_preprocess_flag(&$variables) {
  $arg_1 = arg(1);
  if( isset($arg_1) && !empty($arg_1) ) {
    $menu_obj = menu_get_object();
    $menu_obj_content = $menu_obj['content'];
    foreach($menu_obj_content as $menu_key=>$menu_val) {
      $node_view_mode = $menu_val['#view_mode'];
      break;
    }
    print $node_view_mode;
  }
}

Here node_view_mode will return "View Mode" of current node.


Is there a way to quickly disable caching for all views? (for dev work)

If You ask about drupal 7 can use

cache_clear_all('*', 'cache_views', TRUE);

in template file.

Refreshing page that is using the file will clear all views cache.


It seems that these orders, where in the shopping cart when the current user log off, and never proceed to pay. In order to not lose this product in the cart for the next login, there has to be a relation to the user and product.

If your eCommerce module doesn't have any configuration to delete products on logout, try using hook_user_logout

  Note that when this hook is invoked, the changes have not yet been written to the database, because a database transaction is still in progress. The transaction is not finalized until the save operation is entirely completed and user_save() goes out of scope. You should not rely on data in the database at this time as it is not updated yet. You should also note that any write/update database queries executed from this hook are also not committed immediately.


Header region causing the page to be too wide

Its because of your fb_reset facebook iframes.

If you remove the css rules in the style and change to

Add to css:

.fb_reset {
display:none;
}


How to grant user User Points equal to certain field's value / calculated value?

I finally found a solution! I completed the second scenario (the amount of User Points is calculated) successfuly! Apparently, the User Points module didn't know that the calculation was an integer. Therefore, I had to add an extra action Convert data type: Target type: Integer, Value to convert: [result], Rounding behavior: Always down. I called it 'total' and granted the user this amount of User Points.


I can't see any 'term' in your where clausole, so it's probably because you forgot the single quote around $nid.

oh, when i have query problems, the first thing i do is printing them on screen to see what I'm sending to the db, you wont believe what i managed to write some times, but i blame my keyboard >_>


Programmatically add fields to content type

The second piece of code creates a field in the Form API. This means that you do that when you create a custom form with several fields in it and then you have to handle its submission in your custom way. If this is what you want to do, fine. In this case you would need to add your custom form in your hook_menu().

Instead, from what I can understand with your question, you would like to add a field of the Field API to tour custom node type. For this matter you would need to use the field_create_field() and field_create_instance() functions. The excellent examples module provides very neat examples of how to accomplish that.


Drupal accounts with dead addresses: how to de-activate?

Drupal's LoginToboggan module does this. In the settings, there is an option to "Delete unvalidated users after:" and then you select a time period. It runs with cron so you can "set it and forget it."


How to overriding specific Omega_Kickstart CSS files in a subtheme?

A few things you may want to check (since none of these items are incuded in the question):

make sure you cleared the cache (if not that explains what you experienced).
make sure the file permissions are correct (if not the webserver will not be aware of the newly created subtheme).
make sure you enabled the sub-theme (only creating it is not sufficient).


Import site from HTML pages (currently static files in directories, not in a CMS)

I'm surprised that you didn't find Import HTML yet. Personally, I haven't used it since the Drupal 5 days, but just give it a try and see if it does what you need.


Is there a way to get a default e-mail recipient by default when adding a new webform node?

You can do this with a custom module and hook_node_presave(). After you have a custom module created, you can use code like this to create a default e-mail configuration for any created Webforms.

Assuming your module were called myexample.module, the hook would look like this:

<?php
/**
 * Implements hook_node_presave().
 */
function myexample_node_presave($node) {
  // Add a default e-mail configuration for new nodes.
  if (empty($node->nid) && $node->type == 'webform') {
    $node->webform['emails'][] = array(
      'email' => 'example@example.com',
      'subject' => 'default',
      'from_name' => 'default',
      'from_address' => 'default',
      'template' => 'default',
      'excluded_components' => array(),
      'html' => 0,
      'attachments' => 0,
    );
  }
}
?>


Public and Private file system path is the same

The private files path should always be outside the webroot directory since users can directly access all those files through just adding /sites/default/files/private/.. to your URL. Private files means that they are delivered through Drupal to add some access permissions.

What you should do now:

Backup your databse and put your site into maintenance.
Go to your files_managed table and find all files stored as private files.
Move those files to a new directory outside your webroot.
Change your private files path to the new path and test if everything is working.


The file outside your module should be named (in your example) something.tpl.php.


I can't figure out the difference/relationship between menus and menus

hook_menu : Is used to define a path in Drupal. It also says what should be present in that path, who should have access to it and so.

Documentation of hook_menu

Menus : Is a list of links that fall under a category. For example Admin Menu(Admin Links), User Menu(Account, Logout) and Primary Menu(Home, Contact and so on)

Documentation of Menus


Using hook_menu() with hook_permission() - Access denied

It's access arguments not access arguements :)


How to create related links list in Views

Create a new view showing content, check "create a block".

Click in advanced and, in relationships, add "a bridge to the content entity that is referencing content via your_field_name". The identifier will be something like: "Content referencing Content from your_field_name"

Then add a contextual filter with a relationship to the filter you just created. Select provide default value (Content ID from URL) when filter value is not available.

You can also filter nodes by type to make the view more efficient.

Save your view and add your block to show in the corresponding pages through the block display manager, context or display suite.


How can I see what visitors are searching for?

Unfortunately it's pretty limited.

View top search phrases (in Drupal 6.x):
yoursite.com/admin/reports/search

The data originates from the watchdog table, which means that how much data is provided depends on how far back your watchdog data goes (usually not far).

The Search Log module will provide more robust results. Or use Google Analytics, as the commenter above suggested.


text_format field value not appearing in full_html mode

You don't need to eliminate the #format.

The format and value of the text_format are stored as an array. So in the same way as you retrieve the value you can retrieve the format.

See this example:

public function blockForm($form, FormStateInterface $form_state) {

  $body = !empty($this->configuration['body']) ? $this->configuration['body'] : '';
  $form['body'] = array(
    '#type' => 'text_format',
    '#title' => 'Body',
    '#format' => isset($body['format']) ? $body['format'] : 'full_html',
    '#default_value' => isset($body['value']) ? $body['value'] : '',
  );
  return $form;
}

public function blockSubmit($form, FormStateInterface $form_state) {
  $this->configuration['body'] = $form_state->getValue('body');
}


Why does jQuery slideToggle revert back to initial hidden state after running?

Try this code below.

$('#content').hide();
$('.sf-depth-1 a' || '.sf-depth-2 a' ).click(function() {
  $('#content').toggle('slow', function() {
    // Animation complete.
  });
});


you need to trigger resize when the map is shown.

Try this code:

 $(document).ready(function () {
      $('#mymodal').on('shown', function () {
        google.maps.event.trigger(map, 'resize');
      });
    });

Hope this will help you.


Is there a way to create a sort option for search results that works together with facets?

Indexing the Price:

Go to Administration -> Configuration -> Search and metadata
Edit your Search Index and click on Fields tab.
Select Product->Price from the Add related fields drop down in bottom of form and click on Add fields button. It will add fields for Product -> price in index.
Enable check-box for the field Product » Price » Amount (decimal) and save the form.
Now, you will find Product » Price » Amount (decimal) (Min) and Product » Price » Amount (decimal) (Max) field in your list. Enable these fields and save the form.
Reindex your search.

Adding sorting in views:
Go to Administration -> Structure -> Views
Edit your view.
Add field Indexed Node: Product » Price » Amount (decimal) (Max) or Indexed Node: Product » Price » Amount (decimal) (Min) to sort view and save the view.


How to add a CCK field to custom template file?

Add to your print.tpl.php code like next for printing certain field:

<?php print render(field_view_field('node', $print['node'], 'field_shirtcolor')); ?>

If field is multiple:

<?php
  $field = field_get_items('node', $print['node'], 'field_shirtcolor');
  $delta = 0;  // Put here index of multiple field or use `foreach ($field as $val) {}` for scanning multifield values.
  print render(field_view_value('node', $print['node'], 'field_shirtcolor', $field[$delta]));
?>

If field is image:

$image = field_get_items('node', $print['node'], 'field_image');
print render(field_view_value('node', $print['node'], 'field_image', $image[0], array(
  'type' => 'image',
  'settings' => array(
    'image_style' => 'STYLENAME',
    'image_link' => '',
  ),
)));

p.s. Drupal 6 CCK in Drupal 7, 8 called as just Fields.


How can I install modules using the FTP method?

As kalabro said:

Make sure the folder /sites/default is OWNED by the user that executes the drupal scripts.

On most Ubuntu installations, this is the user Apache user www-data.

chown www-data sites/default


Submitted values are contained in $form_state['values']:

function my_submit_handler($form) {
  $selected_options = array_filter($form_state['values']['my_field']);
}

e.g. if you select '1' and '2' on the form, $selected_options will be array('a', 'b')


You're probably looking for the EntityFieldManager service. It is available from the container as entity_field.manager. Its EntityFieldManager::getFieldDefinitions() method returns the field definitions for all fields that belong to a certain entity type and bundle (content type), keyed by their field names:

$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'page');
if (
  isset($definitions['field_to_check'])
  && $definition = $definitions['field_to_check']
  && $definition->getSetting('target_type')
  && $definition->getSetting('target_type') == 'paragraph'
) {
  // Is a field of a 'node' entity, belongs to the bundle
  // 'page', has the 'target_type' property, and finally
  // references paragraphs.
}

If you load the field storage definition using FieldStorageConfig::loadByName() only, you need to be careful: Field definitions can be different for the various bundle (content) types. So you'd need to additionally check, whether your bundle (content type) matches the bundle of the node you are investigating the reference field for.


Form with throbber not responding to validate or submit methods

According to the Drupal official documentation on drupal_build_form.

  method: The HTTP form method to use for finding the input for this form. May be 'post' or 'get'. Defaults to 'post'. Note that 'get' method forms do not use form ids so are always considered to be submitted, which can have unexpected effects. The 'get' method should only be used on forms that do not change data, as that is exclusively the domain of 'post.'

I would recommend you using POST method rather then GET method, so please remove the line $form["#method"] = "get";

Also, you should rewrite your ajax callback.

function hook_models_update($form, &$form_state) {
   unset($form_state['input']['model'], $form_state['values']['model']);
   $brand = $form_state['values']['brand'];
   $brand_desc = "";
   $results = db_query("SELECT description FROM {taxonomy_term_data} tax WHERE tax.tid = :tid", array(":tid" => $brand));
    foreach($results as $row) $brand_desc = $row->description;

    if($brand_desc != "") $form['model']['#options'] =      _hook_list_models($brand_desc);
    unset($form['model']["#attributes"]['disabled']);
   $form['model']['#disabled'] = FALSE;
   $form["model"]["#attributes"]["id"] = "edit-model";

   $form_state['rebuild'] = TRUE;
   return $form['model'];
}

IMPORTANT NOTE:

If you can, I would suggest you rename your function or module name to avoid using hook_ prefix. It would cause unexpected function name conflict in future, because hook_ prefix is reserved for building hook API in Drupal.


How to replace drush_download_file in Drush 9

With Drush 9 dropping support for the drush dl command, the need for keeping a download function was dropped.

The remnants of drush_download_file() were dropped into the SyncViaHttpCommands.php example class to demonstrate creating a custom a Drush commandfile. You could copy that as a template if you're looking to mimic the old drush_download_file(), or you could use the Guzzle client or some other PHP function; use what works best for your command's download needs.


How to get 'add more items' / multiple fields working when creating a custom content type's create/edit input form using templates and theming (D7)?

The successful answer I found would be not to build the form from scratch as described in: https://drupal.stackexchange.com/a/68975/1082

But instead to use the standard default content type entry form and to customise it to only show certain fields, using the php unset function to hide the input fields that you don't want to be displayed (provided they are non-mandatory of course).

In theme code, template.php

function theme_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'machine_name_of_your_form')
  {
    unset( $form['field_email'] );
  }
}

The benefit of this approach is that you start with a working form and take things off that you don't need.

Contrast that with building a custom form from scratch which doesn't have that guarantee of working - well I found this anyway - as it seemed that even though here I included the essentials, things like multiple field handling didn't work and the submit didn't work either.

So starting with the complete form and tweaking worked for me.

Update

An approach better than unset (and in fact is the official Drupal approach), is to use the #access property on form fields to hide them. For example, in your-theme_hook_alter function (hook_form_alter) in your theme's template.php you would do:

$form['field_email']['#access'] = false;

More details here: http://themery.com/dgd7/advanced-theming/forms/with-templates
(which is an excerpt from THE DEFINITIVE GUIDE TO DRUPAL 7 ebook and paper-based physical book from apress - see http://dgd7.org/ and http://apress.com)


How to hook into file upload and remove button

The file managed_file field is used to upload files I am not sure if it can be used to delete a file from the server if that is what you are trying to do.

The process actually works as follows

When you click the upload button it uploads the file to the server and stored the fid to the field itself and this is the only value we need in the submit function to handle the file as we would using the file_load function to load the file and get the file object using the fid alone.

Now when the user clicks the remove button the field value is set to 0. But the actual file is not deleted from the server and the fid is still stored in the file table.

the '#default_value' should be set to variable_get('image_example_image_fid', ''), this would be used in our form submit function when the field is 0.

The documentation is talking about deleting the file from the temporary table and the server. You would need to remove it in your submit function.

Please check the example from the examples module

if ($form_state['values']['image_example_image_fid'] != 0) {
    // The new file's status is set to 0 or temporary and in order to ensure
    // that the file is not removed after 6 hours we need to change it's status
    // to 1. Save the ID of the uploaded image for later use.
    $file = file_load($form_state['values']['image_example_image_fid']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);

    // When a module is managing a file, it must manage the usage count.
    // Here we increment the usage count with file_usage_add().
    file_usage_add($file, 'image_example', 'sample_image', 1);

    // Save the fid of the file so that the module can reference it later.
    variable_set('image_example_image_fid', $file->fid);
    drupal_set_message(t('The image @image_name was uploaded and saved with an ID of @fid and will be displayed using the style @style.', array('@image_name' => $file->filename, '@fid' => $file->fid, '@style' => $form_state['values']['image_example_style_name'])));
  }
  // If the file was removed we need to remove the module's reference to the
  // removed file's fid, and remove the file.
  elseif ($form_state['values']['image_example_image_fid'] == 0) {
    // Retrieve the old file's id.
    $fid = variable_get('image_example_image_fid', FALSE);
    $file = $fid ? file_load($fid) : FALSE;
    if ($file) {
      // When a module is managing a file, it must manage the usage count.
      // Here we decrement the usage count with file_usage_delete().
      file_usage_delete($file, 'image_example', 'sample_image', 1);

      // The file_delete() function takes a file object and checks to see if
      // the file is being used by any other modules. If it is the delete
      // operation is cancelled, otherwise the file is deleted.
      file_delete($file);
    }

    // Either way the module needs to update it's reference since even if the
    // file is in use by another module and not deleted we no longer want to
    // use it.
    variable_set('image_example_image_fid', FALSE);
    drupal_set_message(t('The image @image_name was removed.', array('@image_name' => $file->filename)));
  }


Ignoring accents/diacritics in apachesolr

So, I think it was a mixture of problems/issues that arose, but they were more broad/were somewhat indirectly related to the symptoms. I'll mention the steps to fix it/figure it out:

On the web amin interface, I selected the core from the dropdown, then "Schema Browser" below it.
From there, I could tell which ACTUAL filters/tokenizers were getting loaded. The ASCIIFoldingFilterFactory was listed on the index analyzer for the text fieldtype, but not the query analyzer.
When I attempted to reload the core, it got an error, and failed. It said something about one of the diacritics already being loaded (it was talking about the mapping-ASCIILatinwhatever.txt file that I'd tried earlier)
I cleared that file, since I was trying to use a different filter, and the core was able to reload, reindex, and everything's working great now (and the filter is on the query analyzer.)

So, anyone else dealing with this issue, in suhort: Check your "Schema Browser" in the web gui for Solr on the core you're having trouble with!


You can exclude other contexts. In the default (sitewide?) context, add a Condition: Context, and use the ~ character to exclude the specific contexts that should not be in effect.

E.g., ~rich_subfoot (if rich_subfoot is the name of the context providing the rich subfooter content)


In response to various comments and other answers, here is some code that ought to work:

$number = $entity->field_max['und'][0]['value'];

$array = array(
  "7mm Shorty over 7mm Jump" => 10,
  "7mm Shorty over 5mm Jump" => 14,
  "7mm Jump" => 13,
  "5mm Shorty over 5mm Jump" => 16,
  "5mm Shorty over 3mm Jump or 7mm Shorty over 3mm Jump" => 19,
  "5mm Jump" => 19,
  "3mm Shorty over 3mm Jump" => 20,
  "3mm Shorty over 2mm jump" => 24,
  "3mm Jump" => 24,
  "2mm Jump" => 27,
);
$smallest_value = PHP_INT_MAX;
$closest_value = -1;
foreach ($array as $val) {
  if(abs($val - $number) < $smallest_value) {
    $smallest_value = abs($val - $number);
    $closest_value = $val;
  }
}
$entity_field[0]['value'] = $closest_value;

After this code is done, $closest_value should be set to the value closest to the initial value.  You can output this however you like.  In the display value field, there should be something like $display_output = $entity_field_item['value'];


You can only use that method to override a theme function in a theme (template.php).

To override the callback function for a theme using a module, you need to implement hook_theme_registry_alter(), e.g.

function MYMODULE_theme_reigstry_alter(&$registry) {
  $registry['field']['function'] = 'MYMODULE_theme_field_override';
}

You might need to change other things too (file path, preprocess functions, process functions, etc, depends on your use case). The above method will help with all of that too.


If you don't know how to add your js code to drupal, there are two ways:

Create js file in your theme_folder/js, e.g, scripts.js, put your code into that file, open .info file of theme and add scripts[]=js/scripts.js
Create a js file as I wrote above and open template.php of your theme and put

drupal_add_js(drupal_get_path('theme', 'YOUR_THEME_NAME') . '/js/scripts.js', array('type' => 'file', 'group' => JS_THEME));

in YOUR_THEME_preprocess_page().
(This is not an ideal way, but it shows how you can use a drupal_add_js() function)

also read documentation for more info.


taxonomy name filter to get terms with special characters

It was only the & charter there was making problems.
This was the solution:

$terms = taxonomy_get_term_by_name(str_replace('&amp;', '&', $title), 'places');


How to trigger a popup window/overlay in my module?

Take a look at the Colorbox module.

You can find a few examples here.

Usage Example:

open URL in Colorbox (iframe)


How can I link back to Term's page using Node Auto Term [NAT]?

This is the closest I've come but it's still sort of hack-ish.

 function MYTHEME_preprocess_field(&$vars) {

        $termid = "none";
    if (
        isset($vars['element']['#object']->nat) &&
        $vars['element']['#field_name'] == 'body' &&
        $vars['element']['#object']->type == 'instructor_profile'
        )
    {

    list($termid, $value) = each($vars['element']['#object']->nat);
    $vars['term_id'] = $termid;

    /* Use EFQ to determine how many nodes may have this taxonomy attached
    to it. I'm only interested in the count()*/
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_related_instructor_mention', 'tid', $termid)
    ->addMetaData('account', user_load(1));
    $count = $query->count()->execute();

    /* If there is information ($count>0), then show. If no links
    don't worry about it */
    if($count > 0) {

        $vars['items'][0]['#markup'] =
        "
" .
        "
More News
" . "
" .
        $vars['items'][0]['#markup'] ;
    }

}

    }


How to show a View field depending on roles?

Check the permissions for the role of "administrators" (D7: admin/people/permissions, D6: admin/user/permissions).  If the user has permission to edit the node, the edit link will be visible, if not, the edit link will not be shown. Views takes into account a user's (role's) permissions.

D7 Example:  Say you are creating a list of Stories. If the administrators role has the permission "Story: Edit any content", the user will be able to see the "Edit" link for that node in the listing, while if the role only has the permission "Story: Edit own content" the "Edit" link will only be shown if the current user created the Story.


Take a look at the api. It states:

  $arg An array that corresponds to the
  return value of the arg() function,
  for modules that want to provide help
  that is specific to certain values of
  wildcards in $path. For example, you
  could provide help for the path
  'user/1' by looking for the path
  'user/%' and $arg1 == '1'. This
  given array should always be used
  rather than directly invoking arg(),
  because your hook implementation may
  be called for other purposes besides
  building the current page's help. Note
  that depending on which module is
  invoking hook_help, $arg may contain
  only empty strings. Regardless,
  $arg[0] to $arg[11] will always be
  set.

Example:

function hook_help($path, $arg) {
    if($path == 'user/%'){
        if($arg[1] < 10) {
            return 'one of the early users';
        }
        else {
            return 'foo';
        }
    }
}

Doing this without the $args would be ugly.


How to issue 404 from a KernelEvents::REQUEST event

You can set a response early in a request event:

 public function my404Check(GetResponseEvent $event) {

    // only return a response for a master request
    if (!$event->isMasterRequest()) {
      return;
    }

    // Do some logic here to check if it should be a 404.

    $response = new Response('', Response::HTTP_NOT_FOUND);
    $event->setResponse($response);
  }

The event dispatcher checks if a response is already set and returns this response without executing any more code to build a Drupal response.


You're missing one of either access callback or access arguments:

From the hook_menu() docs:

"access callback": A function returning TRUE if the user has access rights to this menu item, and FALSE if not. It can also be a boolean constant instead of a function, and you can also use numeric values (will be cast to boolean). Defaults to user_access() unless a value is inherited from the parent menu item; only MENU_DEFAULT_LOCAL_TASK items can inherit access callbacks. To use the user_access() default callback, you must specify the permission to check as 'access arguments'

Sorry to paste so much but it's all relevant, the last sentence in particular.

Choose a permission that applies to your site and added it to your menu item:

function kameleon_create_report_menu() {
  $items['admin/reports/orderreport'] = array(
    'title' => 'Order Report',
    'page callback' => 'create_report',
    'access arguments' => array('access content'), // This is almost certainly NOT the permission you want to use, choose one with restricted access.
    'weight' => 1,
    'type' => MENU_LOCAL_TASK
  );

  return $items;
}

Also as Attiks points out you've forgotten to return $items from the menu hook.

Finally, simply refreshing the page won't work when you add a menu item (they are cached), so you need to clear Drupal's caches to see the new item.


You need a condition() so that it knows which record to update.  When you don't give a condition, it just doesn't update anything.  More Info on db_update()

The following says, "Update firstname to formvalue, lastname to formvalue WHERE the last name as stored in database is 'Bolli'".  To avoid conflicts, your table should have a field that contains a unique value for each entry, such as an auto-increment primary key.  That way, you can say "UPDATE ... WHERE id = unique_id".

$update_zoho = db_update('zoho')
  ->fields(array(
     //'title' => $form_state['values']['title'],
     'firstname' => $form_state['values']['firstname'],
     'lastname' => $form_state['values']['lastname'],
  ))
  ->condition('lastname', 'Bolli', '=')
  ->execute();


How to sort images in Views by their position?

sort your view with field_image:delta, ascending


How do you contribute patches to Drupal core?

If the bug is in Drupal 7, do I have to also fix it in Drupal 8, and submit two patches?

If the bug is present in the version being developed (in this case Drupal 8), and the previous version (Drupal 7), then the bug should be first fixed the currently developed version, and then on the previous version(s).

If the bug is not present in the latest developed version, for example because the bug is for a function that has been removed, or that has been already changed, then the patch should be provided for the version before the currently developed one.

The workflow that is followed is:

First the patch is created, and submitted for reviews, for the most recent version, even if still under development (such as in the case of Drupal 8)
Once that patch is applied to Drupal, a patch that applies for the previous version is created, and submitted for reviews

You can create patches for two Drupal versions at the same time, but since the patch for the latest Drupal version could require changes, it is better to work on the patch for the currently developed version, than working on two different patches that both require to be changed.

See also: Backport Policy.

  Does this also apply to documentation bugs/improvements?

Yes, it does. Also in this case, if the currently developed version removed the function/method to which the documentation is referring, then the patch needs to be provided for the previous version.

  Do all patches also require a unit test?

If the patch is for the documentation, it doesn't require tests. The test bot running on http://qa.drupal.org checks the Drupal code after the patch is applied; if the patch introduces syntax errors (for example because the comment is closed before the needed), then the test bot will report an error about the patch before tests are run.

If the patch is for a new feature, then the tests are required.

If the patch is to fix a bug, then the tests could be required from the maintainers, if there isn't already a test checking a specific feature. The test is generally necessary to avoid re-introducing the same bug when changing in future the same code. If the bug is merely a variable that is initialized, but never used from a function/method, then chances are the tests are not required.


How to add more information about authors with the Bibliography module?

Create another content type like "BookAuthor" with 1 node for each such Author. Then add fields to this content type for attributes such as picture, biography and nationality.

Assume you have a content type like "Ressources" (or just create one). Add a field in that content type using the Entity reference module for it (probably with multiple values allowed). That way you can add one or more "links" in each Ressources-node to relevant nodes of type BookAuthor.

PS: just to avoid possible surprises, I would not call the content type "Author" (which has a special meaning in Drupal, so better to not confuse Drupal with the same name for your extra content type).


Image style doesn't rebuild after image style flushed

Problem solved!!!

After checking that Drupal manages itself 404 errors by checking .htaccess file :

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

I had to put this line into my settings.php... This is in the Drupal 7.20 release notes :

$conf['image_allow_insecure_derivatives'] = TRUE;

This thread saved my day.

Wish helps others.


Error when trying to upload a Configuration Synchronization file

what you need to do is make few changes on settings.php file

$config_directories = array(

CONFIG_SYNC_DIRECTORY => 'sites/default/files',

);

On production sites, and if your account has permission to do so, it's a good idea to move the configuration sync directory outside of the webroot entirely. As your sync directory should be under version control, this means having your version control repository's root be one level higher than your webroot.  please check out more details at  https://www.drupal.org/docs/8/configuration-management/changing-the-storage-location-of-the-sync-directory


How can I get the width or height of an image field image into a twig template?

You can't access the array values because it is protected. But you don't need to, because you can get the properties from a field item directly:

{% set image_width = content.field_image.0['#item'].width %}

BTW the content variable is a render array with no fixed structure. The presence and position of #item changes dependent on the field formatter and other core, contrib or custom code.

So it's better to use the entity object, for example the paragraph entity in a paragraph template:

{% set image_width = paragraph.field_image.0.width %}


Migrated D8 site breaks when cache_discovery is truncated

Did my normal process of installing a clean site on the new server,
  and then copying the modules, themes, and file folders from the old
  dev site to the new dev site,

In D8 all information from annotations and yaml files are newly discovered on a cache rebuild. And your mix from the clean site install and the copied files did not fit together. This could be one file, which is left over from an older core or module version and you get this problem. So the solution is, to copy complete site archives or when updating remove the old code completely before replacing it.


How to invoke a custom callback function in Javascript

For very basic Commands, you likely do not need to implement CommandWithAttachedAssetsInterface or CommandWithAttachedAssetsTrait.

Here is a good blog post tutorial for a custom Command: https://www.mike-miles.com/blog/creating-ajax-callback-commands-drupal-8

Here is another example: https://www.mediacurrent.com/blog/loading-and-rendering-modal-forms-drupal-8

Here are a couple modules that implement Commands for an example:

iGrowl
SweetAlert

You are not going to want to override core Drupal JS, as it is easy to add your own and communicate to your plugins or third party plugins as demonstrated above.


The information about the blocks are saved in the "block" table. The block information is saved in the admin form handled by block_admin_display_form() using the following code.

  foreach ($blocks as $i => $block) {
    $key = $block['module'] . '_' . $block['delta'];
    $form['blocks'][$key]['module'] = array(
      '#type' => 'value',
      '#value' => $block['module'],
    );
    $form['blocks'][$key]['delta'] = array(
      '#type' => 'value',
      '#value' => $block['delta'],
    );
    $form['blocks'][$key]['info'] = array(
      '#markup' => check_plain($block['info']),
    );
    $form['blocks'][$key]['theme'] = array(
      '#type' => 'hidden',
      '#value' => $theme,
    );
    $form['blocks'][$key]['weight'] = array(
      '#type' => 'weight',
      '#default_value' => $block['weight'],
      '#delta' => $weight_delta,
      '#title_display' => 'invisible',
      '#title' => t('Weight for @block block', array('@block' => $block['info'])),
    );
    $form['blocks'][$key]['region'] = array(
      '#type' => 'select',
      '#default_value' => $block['region'] != BLOCK_REGION_NONE ? $block['region'] : NULL,
      '#empty_value' => BLOCK_REGION_NONE,
      '#title_display' => 'invisible',
      '#title' => t('Region for @block block', array('@block' => $block['info'])),
      '#options' => $block_regions,
    );
    $form['blocks'][$key]['configure'] = array(
      '#type' => 'link',
      '#title' => t('configure'),
      '#href' => 'admin/structure/block/manage/' . $block['module'] . '/' . $block['delta'] . '/configure',
    );
    if ($block['module'] == 'block') {
      $form['blocks'][$key]['delete'] = array(
        '#type' => 'link',
        '#title' => t('delete'),
        '#href' => 'admin/structure/block/manage/' . $block['module'] . '/' . $block['delta'] . '/delete',
      );
    }
  }

Using $form_state['values']['blocks'][$key]['module'], and $form_state['values'][$key]['delta'], you can find the block information from that table, and set the form fields to the  values found in the database. In the submission handler for that button, you should also set $form_state['#rebuild'] to TRUE to rebuild the form with the restored values.


How do I display data in a dynamically created page

I've managed to do it by using Views module.

On first submit, I would dynamically create view, and on each concurrent submit I would create additional view display (page).


Entity Reference auto complete user name with different field

I took Mikey's suggestion and made a ctools plugin.
Here's what I came up with:

I'm using a custom module to house the plugin, but technically you could put the plugin into the entity-reference module itself. This would be ok because this method doesn't replace any module code (which would break updates).

Assuming you make a custom module you will need to put this hook into your .module file:

/*
 * Implements hook_ctools_plugin_directory
 */
function custom_module_ctools_plugin_directory($module, $plugin) {
  if ($module == 'entityreference') {
    return 'plugins/' . $plugin;
  }
}

Then you will make a file thats located within your module's ctools plugin directory:
.../modules/custom_module/plugins/selection/realname.inc

The file can be called whatever you want but the file path matters. You could also make the file in .../modules/entityreference/plugins/selection/ as well (as mentioned above).

Contents of realname.inc:

<?php

$plugin = array(
  'title' => t('Use realname'),
  'class' => 'EntityReferenceSelectRealname',
  'weight' => 10,
);

You will then make another file in the same directory as this one. The file uses the name of the class provided above then .class.php so it will be EntityReferenceSelectRealname.class.php for this one.

Contents of EntityReferenceSelectRealname.class.php:

<?php

class EntityReferenceSelectRealname extends EntityReference_SelectionHandler_Generic {

  /**
   * Implements EntityReferenceHandler::getInstance().
   */
  public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
    $target_entity_type = $field['settings']['target_type'];

    // Check if the entity type does exist and has a base table.
    $entity_info = entity_get_info($target_entity_type);
    if (empty($entity_info['base table'])) {
      return EntityReference_SelectionHandler_Broken::getInstance($field, $instance);
    }

    if (class_exists($class_name = 'EntityReferenceSelectRealname_' . $target_entity_type)) {
      return new $class_name($field, $instance, $entity_type, $entity);
    }
    else {
      return new EntityReferenceSelectRealname($field, $instance, $entity_type, $entity);
    }
  }
}

/**
 * Override for the User type.
 *
 * This only exists to workaround core bugs.
 */
class EntityReferenceSelectRealname_user extends EntityReferenceSelectRealname {
  public function buildEntityFieldQuery($match = NULL, $match_operator = 'CONTAINS') {
    $query = parent::buildEntityFieldQuery($match, $match_operator);

    // The user entity doesn't have a label column.
    if (isset($match)) {
      //This line uses the regular username:
      //$query->propertyCondition('name', $match, $match_operator);

      //This was added to use the "realname" field instead of the regular username:
      //CHANGE THIS:
      $query->fieldCondition('field_er_realname', 'value', $match, $match_operator);
    }

    // Adding the 'user_access' tag is sadly insufficient for users: core
    // requires us to also know about the concept of 'blocked' and
    // 'active'.
    if (!user_access('administer users')) {
      $query->propertyCondition('status', 1);
    }
    return $query;
  }

  //Not sure if this is necessary, but I'll add it in to be safe.
  public function entityFieldQueryAlter(SelectQueryInterface $query) {
    if (user_access('administer users')) {
      // In addition, if the user is administrator, we need to make sure to
      // match the anonymous user, that doesn't actually have a name in the
      // database.
      $conditions = &$query->conditions();
      foreach ($conditions as $key => $condition) {
        if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'users.name') {
          // Remove the condition.
          unset($conditions[$key]);

          // Re-add the condition and a condition on uid = 0 so that we end up
          // with a query in the form:
          //    WHERE (name LIKE :name) OR (:anonymous_name LIKE :name AND uid = 0)
          $or = db_or();
          $or->condition($condition['field'], $condition['value'], $condition['operator']);
          // Sadly, the Database layer doesn't allow us to build a condition
          // in the form ':placeholder = :placeholder2', because the 'field'
          // part of a condition is always escaped.
          // As a (cheap) workaround, we separately build a condition with no
          // field, and concatenate the field and the condition separately.
          $value_part = db_and();
          $value_part->condition('anonymous_name', $condition['value'], $condition['operator']);
          $value_part->compile(Database::getConnection(), $query);
          $or->condition(db_and()
            ->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + array(':anonymous_name' => format_username(user_load(0))))
            ->condition('users.uid', 0)
          );
          $query->condition($or);
        }
      }
    }
  }
}

You will want to go in and change field_er_realname to your field's name. Which is field_complete_name in your case. Btw, I used the Computed Field module to generate my "realname" field based on the first and last name provided.


Changing generated html of a module. (Search API)

I finally got around to do this using the MYTHEME.THEME file, I used this function:

function nestle_theme_suggestions_input_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  if ($element['#id'] == 'edit-submit-search-content') {
    $suggestions[] = 'input__' . $element['#type'] . '__' . 'mainsearch';
  }
}

Basically, it gets the element by its ID then changes its twig suggestion to kinda force twig to ditch the normal method of choosing the twig template based on naming conventions, Instead, it gives it a twig template to use!


According to the documentation page for hook_views_query_alter(), this hook works in Drupal 8, but (as you can see in comments for the referenced article) you should place it in mymodule.views_execution.inc, not in mymodule.module.


Detect when 'Remove' is clicked on a file widget form element?

You can use javascript onclick() function

<button onclick="myFunction()">Click me</button>

or jQuery

$("#remove").click(function(){
    alert("The remove was clicked.");
});


Hide new topic link based on the forum topics

I got it working.
Here is the code

function theme_advanced_forum_node_type_create_list(&$variables) {
  $forum_id = $variables['forum_id'];

  // Get the list of node types to display links for.
  $type_list = advanced_forum_node_type_create_list($forum_id);

  $forum_ids = array(1,2,3,4); // Ids of forum1
  $forum2_ids = array(5,6,7,8,9,10);  // Ids of forum2

  $output = '';

    if (in_array($forum_id, $forum_ids))  {

      $output .= '
';
      $output .= theme('advanced_forum_l', array(
        'text' => 'New topic',
        'path' => $type_list['forum']['href'],
        'options' => NULL,
        'button_class' => 'large',
        ));
      $output .= '
';

  }
  elseif (in_array($forum_id, $forum2_ids))  {
    $output .= '
';
      $output .= theme('advanced_forum_l', array(
        'text' => 'New topic',
        'path' => $type_list['forum2']['href'],
        'options' => NULL,
        'button_class' => 'large',
        ));
      $output .= '
';
    }
  else {
    // User did not have access to create any node types in this fourm so
    // we just return the denial text / login prompt.
    $output = $type_list;
  }

  return $output;
}


Sessions / Cookies not working for user login, registration or shopping cart

This is a very old question, but I stumbled on it while having the same issue.

In my case, the "rewrite" Apache module was turned off. I re-enabled it with:

a2enmod rewrite

I could access /user, but could not login (it would loop back, with no error message). I assumed that since I could access /user, my rewrites and htaccess were OK. I could login with "drush uli", but no form would work. Even weirder: in some pages that had query parameters (GET, ex: foo?test=1), the GET parameters would not be passed to PHP. I was searching all over the place, and the solution was pretty trivial :)


How can i add .pdf extention on the default upload files

Go to Structure > Content types, click manage fields for the article content type, then edit on the Image field. There you can edit the allowed file types.

However, note that this is an image field. It does not make sense to upload PDF files to an image type field. Instead, you might want to add a new field with type file and configure that to allow pdf files.

Also note that you can't leave the allowed values empty, that would not allow any file types.


Upload a file to Drupal server from (external) desktop client application (in c#)

You may want to create something with the Services module. The services module gives you an easy way to add REST / XMLRPC services to your drupal site. http://drupal.org/project/services

See also the documentation: http://drupal.org/node/736522


The trick is to add a view of taxonomy terms, and then add a relationship to the content. You'll also have to hide some fields and add a grouping field in the unformatted list settings. Details are below.

Create a new view that shows "Taxonomy terms" of type "expert [vocabulary]" sorted by Unsorted
Continue and edit
Add a relationship under Advanced > Relationships
Choose "Taxonomy term: Content with term" (Relate all content tagged with a term) & apply to all displays
You'll now be able to add a field and the content will show up. Click add next to Fields and select the Content Title or whichever field the name is stored at.
Uncheck "Create a Label" and apply.
Click on Format > Settings, and select "Taxonomy term: Name" in the "Grouping field Nr.1" dropdown, and click Apply. This will create a heading of the taxonomy term.
Hide the taxonomy terms from showing up extra times by clicking on the "Taxonomy term: Name" field, and click "Exclude from display."
Uncheck "Link this field to its taxonomy term page" so that the taxonomy term is not linked to it's page.
Save the view, and view the page.


Views filter: Filter by number of field values

did you look if you have access for your designated field to the "delta" version of this field ?

This will do the trick.

If you don't, I'd advise to use aggregate and COUNT values of the field. Will work the same. Create a filter with that field, activate aggregation, count.


If I understand you correctly the  Aggregate Household Contribution Report is what you are looking for.  If that is not sufficient, it may provide a good basis for a custom report.


"WHERE NOT IN ( SELECT... )" with SelectQuery?

What you're looking for is SelectQuery::exists(), unfortunately it doesn't seems to work with "common way" to build such clause:
Normally in a EXISTS clause you put a JOIN on tables outside of your sub query like this:

SELECT n.nid
FROM node n
WHERE EXISTS (
  SELECT NULL
  FROM users u
  WHERE u.uid = n.uid
  AND u.status = 0)

This returns the nodes of blocked users (yes it can be built easily without the EXISTS but it's for teaching purposes ;).

The problem here is that the exists condition doesn't support "outside linking", the u.uid = n.uid part so you have to build a completely independent query which is not very efficient IMHO.
In Drupal you will write this:

$query = db_select('node', 'n')
  ->fields('n', array('nid'));
$subquery = db_select('node', 'n2')
  ->fields('n2', array('nid'))
  ->join('users', 'u', 'n2.uid = u.uid'
  ->condition('u.status', 0);
$query->condition('', $subquery, 'EXISTS');
$result = $query->execute();

You can also use db_query() like you used to do in Drupal 6 and of course SelectQuery::notExists() is available.


How to pass a form and other variables to theme functions?

As you rightly say you can't pass variables to a theme function that uses a render element, but then you don't need to.

One of the points of the render element is that the element already contains all of the properties/variables that it needs to perform the render, without having to get them from anywhere else.

A themed form is actually a good example for this: if you need to add extra variables in order to render that form, then they should be arguments to the form function itself. e.g.:

function deductible_form($form, &$form_state, $var1, $var2) {
  $form['#theme'] = 'deductible_form';
  $form['#var1'] = $var1;
  $form['#var2'] = $var2;

  // etc...

  return $form;
}

Then in your form's theme function you can easily access those vars:

function theme_deductible_form($vars) {
  $form = $vars['form'];

  $var1 = $form['#var1'];
  $var2 = $form['#var2'];

  // Render the form
}

All you need to do to get that form to render properly now is to call drupal_get_form() with your extra variables:

$form = drupal_get_form('deductible_form', $var1, $var2);


Services module: What is 'Index' operation?

'Index' in services module will list out an entity(node, users, taxonomy..)  in descending Order of its created time, vid, name etc based on the arguments that are passed. The common arguments for the Index are

page  - Page number of results to return (in pages of 20).
fields - The fields you want returned.
parameters - An array containing fields and values used to build a sql WHERE clause indicating items to retrieve. (array)
pagesize - number of items to be returned. (Integer)

In case of retrieve, it returns the complete entity object of the passed 'entity_id'

UPDATED:

Sample URLS for Index is

http://domain/endpoint/node?fields=nid,vid&parameters[nid]=7&parameters[uid]=1&page=2
http://domain/endpoint/taxonomy_term?fields=tid,name&parameters[tid]=7&parameters[vid]=1
http://domain/endpoint/user?fields=uid,name,mail&parameters[uid]=1
http://domain/endpoint/node?pagesize=3

For documentation you can see Services: An API for remote applications.


How often is settings.php called? And is $user available to it?

The settings.php file is included on the first bootstrap phase (DRUPAL_BOOTSTRAP_CONFIGURATION), while the global $user is initialized on DRUPAL_BOOTSTRAP_PAGE_CACHE or DRUPAL_BOOTSTRAP_SESSION, which are both later bootstrap phases.

The settings.php file is included each times Drupal bootstraps, which means every time Drupal serves a page, including the ones served from its cache. As such, the settings.php file can use plain PHP functions or a restrict set of Drupal functions; in both the cases, the code cannot access the user variable. It is not even possible to initialize it using the database, since the database connection is initialized after the file has been included. (The obvious reason is that the database settings are contained in the settings.php file.)

Reference

drupal_bootstrap()


Webform, rename files to a constant name and bypass validation

By looking at the source in /components/file.inc (in Webform module), you will see that the Webform declares a custom element validation callback that performs the check you want to avoid. In order to override this, you will have to hook into the settings form, and provide your own callback for this element.

Below is the code you would use to achieve that. Pay attention to the comments.

function YOUR_MODULE_form_webform_component_edit_form_alter(&$form, &$form_state) {
  // Override the element validation callback for renaming the file uploads.
  if (isset($form['extra']['rename'])) {
    // Loop through the validation callbacks and remove the one we want to
    // override. This way we will not affect any other module that alters this
    // part of the form.
    foreach ($form['extra']['rename']['#element_validate'] as $key => $validation_callback) {
      if ($validation_callback == '_webform_edit_file_rename_validate') {
        unset($form['extra']['rename']['#element_validate'][$key]);
      }
    }
    // Note: since the original validation callback provided in Webform module
    // only makes sure that the file names are unique, you don't need to provide
    // your own element validation callback. However, I would recommend doing so
    // just in case you have other webform nodes that will need this validation.
    //
    // Add our custom element validation callback.
    $form['extra']['rename']['#element_validate'][] = 'YOUR_MODULE_edit_file_rename_validate';
  }
}

function YOUR_MODULE_edit_file_rename_validate($element, &$form_state, $form) {
  // I recommend still limiting this only to specific nodes, content types, and
  // not disabling completely.
  if ($form['#node']->nid != YOUR_NODE_ID) {
    $rename = trim($form_state['values']['extra']['rename']);
    form_set_value($element, $rename, $form_state);
    if (strlen($rename) && !count(token_scan($rename))) {
      form_error($element, t('To create unique file names, use at least one token in the file name pattern.'));
    }
  }
}


How to pass contextual id value from one view page to another through Drupal menuing system

The "connected" exposed sorting criteria is implemented in the Facets module and Search API.
Here's a tutorial that can help get you started: Creating a Faceted Search View in Drupal 8 using the Search API Modules

Before you start testing new modules maybe the "ordinary" Exposed Sort criteria in Views can help. Create only one Page display, but add all 3 Sort criteria you want and Expose them. You can use the Expose form in Block to show those options in some region of your theme instead of above the results.

The Better exposed filters module allows you change the widgets from drop-downs to Radio buttons or links. You can also rewrite the filter options to make them more relevant for your cases, and combine the "sort order" with "sort by".

Having an exposed form block can serve like Menu items, showing the user what has been selected, which is what the active menu trail does.

To clean up the URLs there is the Query Parameters To URL module but it's still being ported to Drupal 8. (Help advance it if you can.) Without it I guess you can set up some path redirects manually, although it might be tedious if you have a lot of combinations to cover. You can do that in .htaccess or with the Redirect module.

Yet another approach I can think of is the Views Global Filter module. You might use the "topic" globally, then sort links might work with menu trails (I haven't tried it).


Conditions are only used in dynamic queries; the query() method is for running static SQL.

The dynamic version would be something like:

$result = $database
  ->select('acl_node', 'n')
  ->fields('n', ['nid'])
  ->condition('grant_update', 1)
  ->condition('acl_id', $acl_ids, 'IN')
  ->execute()
  ->fetchField();

And the static:

$result = $database
  ->query("SELECT nid FROM {acl_node} WHERE grant_update = :grant AND acl_id IN (:acl_ids[])", [':grant' => 1, ':acl_ids[]' => $acl_ids])
  ->fetchField();


Can't set a file->description field in a paragraph programmatically

The answer was incredibly simple

$paragraph->field_files->description = $file_title;


How to split Webform in multi menus/tabs?

There's the Webform Navigation module which allows you to let users navigate back and forth between steps of a multi-step form via the progress bar. How you design these steps in the progress bar is up to you. If you want them look like tabs, style the steps to look like tabs. That's all.

The goal of this module is to provide the ability to navigate forward
and backward through a web form using the Webform Progress tracker
(aka wizard progress bar) supplied by the webform module on multi-page
web forms. It also allows for the ability to bypass validation when
the user presses the "next" button as they navigate through the form.

Alternatively use collapsible fieldsets to contain sections of your webform.


Print edit/create/delete node link with jQuery

If I understand correctly you need the urls to the node creation/edit/deletion.
So, here it goes.

The link to add a node is:

node/add/your_content_type_name

to delete a node

node/node_id/delete

to edit a node

node/node_id/edit

You can fetch the node ID with jQuery from the url, But your kinda stuck with the content type name.


Dealing with node language when manually updating node

Yes - it is safe to assume this. The locale module will deal with this by setting it to the language code of the default language, ex 'en'.

Citing from: http://drupal.org/update/modules/6/7#drupal_language_none

In Drupal 7, the LANGUAGE_NONE constant should be used for nodes or other items that do not have a specific language associated with it.

http://api.drupal.org/api/drupal/includes--bootstrap.inc/constant/LANGUAGE_NONE/7


Creating a link like this will not create the desired output. When looking at the l() function comments on the Drupal API page, the following is suggested to make internal anchors work:

l(t('Comments'), $_GET['q'], array('fragment' => 'comments'));

What happens is you tell Drupal to create a link to the current page, and add #comments as an anchor (fragment).

This means you can also link to the comments from other pages, by simply changing the $_GET['q'] parameter to the desired path.


drupal_mail sending wrongly encoded special characters in mail subject

There are no bugs. Maybe lazy code from the developers.

Just simply put this line

mb_encode_mimeheader($params["subject"],"UTF-8", "B", "\n");

for the subject and works in all languages and codifications (chinese, etc.). It is tremendous that phpMailer class in itself handles perfectly, but when you use the phpMailer module, this encapsulating dissapears and you have to hard-code in the mymodule_mail() function.

Sincerely, Drupal is not suited for big projects.


How do I change the salt used for the user password when creating an account?

In site/default/settings.php  there is a config for salt

$settings['hash_salt'],  passwords are hashed with this salt. you can change it to whatever the client has asked you.


can't upload files from computer in any wysiwyg editor

The IMCE project provides upload capabilities to a variety of WYSIWYG editors. Check the project page for the appropriate way to install it for your particular editor.


I would check your date/time settings, specifically the sites default time zone.  I have seen similar errors when that is set incorrectly.


Select address functionality during checkout for Drupal Commerce 2.x

There is a patch in progress to add this feature.

To apply the patch to the most recent version of Commerce (2.1 as of this writing), based on this comment, you can add this to your composer.json:

"drupal/commerce": {
      "reverse profileSelect change to allow PR 760": "https://www.drupal.org/files/issues/2844920-reverse-profileSelect-temp-fix.patch",
      "reuse profiles": "https://patch-diff.githubusercontent.com/raw/drupalcommerce/commerce/pull/760.diff",
      "reuse profiles enhanced": "https://github.com/fliegen/commerce/commit/57c11175d279fe55db9454b4274608195211aeb8.diff",
      "checkbox same as billing": "https://www.drupal.org/files/issues/checkbox-same-as-billing-2852207-69.patch",
  }
  "drupal/commerce_shipping": {
      "profile select enhancement": "https://github.com/fliegen/commerce_shipping/commit/797b5ef351851d60b2cb6c1a55837501c2a036a5.diff",
      "profile in shipping method widget fix": "https://www.drupal.org/files/issues/profile-reuse-enhanced-2908683-1.patch",
      "auto-recalculate shipping": "https://www.drupal.org/files/issues/commerce_shipping-autorecalculate-2849756-35.patch"
  }

You don't need to add the checkbox same as billing and commerce_shipping part if you are not collecting a shipping address.


How to set an AJAX callback for my drop down list select in my form?

This is untested but at least, you get the logic. I'm sorry if I edited your coding style convention.

function value_form(&$form, &$form_state)
{
    $form = array();

    $countries = _prepare_countries_list();
    $selected_country = isset($form_state['values']['country'])?$form_state['values']['country']:key($countries);

    // Country dropdown list
    $form['country'] = array(
        '#title' => t('Country'),
        '#type' => 'select',
        '#options' => $countries,
        '#ajax' => array(
            'event'=>'change',
            'callback' =>'country_state_dependent_dropdown_callback',
            'wrapper' => 'dropdown-states',
        ),
    );

    // Wrapper for state dropdown list
    $form['state_wrapper'] = array(
        '#prefix' => '
',
        '#suffix' => '
',
    );

    // State dropdown list
    $form['state_wrapper']['state'] = array(
        '#title' => t('State'),
        '#type' => 'select',
        '#options' => _country_state_get_second_dropdown_options($selected_country),
    );

    return $form;
}

/**
* Function for handling ajax request
*/
function country_state_dependent_dropdown_callback($form, $form_state){
    return $form['state_wrapper'];
}


How do I output view (page display) content in page--.tpl.php?

I use the following function to solve the issue

print views_embed_view('NAME_OF_VIEW','page');


Hide already purchased products (or allow purchasing the product only once)

I would use Content Access to restrict access to nodes by role, then I would make a special role that is required for viewing this product. Then I would create a Rule where buying that product triggers that  role being removed from the user.


D7 views 3, display content based on path

Please watch Learn Views with NodeOne, part 19: Contextual filters with paths.


Go to the template directory of Billy PDF (commerce_billy/modules/commerce_billy_pdf/templates) and copy the file

commerce_order--commerce_order--pdf.tpl.php

to your theme directory. Thats the template of the generated pdf. You can simply edit this template and add the billing method i think.

You can access the order object via

$order = commerce_order_load($variables['elements']['#entity']->order_id);

inside of the template.


PHP code for Block visibility by Vocabulary ID

If you want to do this on the term pages you should be able to use this code from Drupal.org. Just replace the function call taxonomy_get_term with taxonomy_term_load.

The code is copied below:

 <?php
  $desired_vocab = 1; // put here the vocabulary ID you're interested in

  if ( ((arg(0) == 'taxonomy')
    && (arg(1) == 'term')
    && is_numeric(arg(2))
    && ($term = taxonomy_term_load(arg(2)))
    && ($term->vid == $desired_vocab )) ) {
      return TRUE;
  }
?>


Is there a way of completely replacing the SQL of a View with my own custom string?

Don't do that. You've got two options: either use Views or don't.

Option 1: Use a custom block/page handler

You can build your own query and theme it any way you want it. Just build it as a block or a custom page and do it the "old-fashioned" way. It will be much cleaner than trying to use views.

Option 2: Use Views

If you want views, then you should build any additional plugins, handlers, or add any alters you need and do it right (that includes using the DB abstraction layer). This isn't hard and there is plenty of documentation floating around that can help you with this.

If you circumvent the systems you have (e.g. Views), you will end up producing code that isn't maintainable by someone else or could unknowingly introduce problems. Please don't look for shortcuts, do it well and do it right.


You need to edit the following view: Shopping cart form (Commerce Order).
And add a the field: Commerce Line Item: Product Attributes, this will show the product with the extra attributes.


Unable to fetch image after using Content Import and IMCE module

Your folder path should be "CONTENT-TYPE MACHINE NAME/images" not artist/hero and set permissions to 777 as per Content Import Module. And also change File directory path under that field as "CONTENT-TYPE MACHINE NAME/images".


You need to use Hook permission to define the permission within your module


there any field in view that display Display author and date information

Assuming you mean the date posted and making assumptions also on entity types.

For nodes:
Author: Add the "Content: Author" relationship and then the "User: Name" field.
Date: Add the "Content: Post date" field.

For comments:
Author: Add the "Comment: Author" field.
Date: Add the "Comment: Post date" field.


Is it possible to expose custom table data to Views without custom code?

Apparently Views Custom Table does that:

View custom table module provide you functionality to integrate your
custom table data to views, and access all it's column in views. This
module use hook_view_data to add custom tables in views. this module
provides you following functionalities.

Auto integrate custom table data to views
Auto map mysql data types with drual data types
Extend relationship of custom table data to drupal entities


Built in cache system doesn't work in Drupal 6

Drupal generates cache when a node, block, or view is rendered the first time. How much cache is served versus how much is generated on that request can depend on both that visitor's role and specific user account.

If two anonymous users hit the same page, the first anonymous user will trigger the cache to be generated for elements on that page, then the second anonymous user will receive those cached elements and the page will load faster for them.

However, if one authenticated user hits a page, then an anonymous user hits the same page, two different versions of a selection of elements on that page will be cached (for instance, if authenticated users are allowed to see a block, but anonymous users aren't).

Therefore, Drupal's caching mechanism works best when there are lots of visitors with the same permissions hitting the same non-personalized pages. If it's a site with users who sign in, and there are lots of permissions (especially field-level permissions) at play, Drupal's cache will be fairly ineffective for anything but static content nodes and blocks.


How to manage contextual filters for a simple date-based view

Here is the one approach,

First create a custom call back for /events
Remove the date contextual filters from your view
Add only one filter(not contextual filter) to your view for that date field, accept the default values and save the view
Then use the following code in your custom callback to execute the view

function get_events($year = '', $month = '', $day = '')
{
  // Display ID of the view.
  $display_id = 'default';
  // get the view object.
  $view = views_get_view('events_views'); //Replace with your view name
  $filter = $view->get_item($display_id, 'filter', 'field_event_date_value');
  if ($year) {
    $filter['value']['value'] = $year;
    $filter['granularity'] = 'year';
  }
  if ($year && $month) {
    $filter['value']['value'] = $year . '-' . $month;
    $filter['granularity'] = 'month';
  }
  if ($year && $month && $day) {
    $filter['value']['value'] = $year . '-' . $month . '-' . $day;
    $filter['granularity'] = 'day';
  }
  $view->set_item($display_id, 'filter', 'field_event_date_value', $filter);
  // If you have any other arguments read from the URL and pass it here as part of args array
  $result = $view->execute_display($display_id, $args);
}

Hope you are aware of how to pass arguments to the view programatically. This is what we are using for complex date filters in views which lacks lot of support for date functionality, however we haven't tried with granularity. This is un tested and not optimized. Modify it according to your need.


Displaying individual fields in a template

You can not print out content fields directly in the page template. content is available in the node template, not in the page template.

The correct way to print out parts of the node elswhere in the page template is to define a block that does that, for example with the ctools module and a specific view mode that just contains the fields you want.

Alternatively, you can load the node yourself in theme_preprocess_page() and then view/prepare them manually and put it in $variables. But using blocks and regions is the standard and recommended way to put something in the page template.


How can I trigger a rules event by code ?

I managed to invoke the event "calculate sell price" by adding a rule with the event "When existin line item is updated" and then adding a call to rules_invoke_event() in PHP code like this:

rules_invoke_event("commerce_product_calculate_sell_price", $commerce_line_item);

I was previously calling this rule incorrectly, without adding the $commerce_line_item so this problem is resolved, now the shipping remained.
Thanks for your time!


How to access the order total amount in Drupal commerce?

Try this

global $user;
$image = theme('image', array('path' => url('sites/default/files/basketempty.png', array('absolute' => TRUE))));
$order = commerce_cart_order_load($user->uid);

if ($order) {
  $wrapper = entity_metadata_wrapper('commerce_order', $order);
  $line_items = $wrapper->commerce_line_items;
  $total = commerce_line_items_total($line_items);
  if($total['amount']){
    $image = theme('image', array('path' => url('sites/default/files/basketfull.png', array('absolute' => TRUE))));
  }
}

echo l($image, 'twotrees/cart', array('html' => TRUE));


http://test/api/node?parameters[nid]=1&parameters[status]=1&fields=status,bid,title

As always you can look at the tests.

Below you can see whats possible.


Product variations getting same name as product

Okay, I guess I was unfamiliar with the terminology. Here is what I did to find this, in case it helps anyone else. First go to Structure (which because I have the kickstart installed is actually in Site Settings under the Advanced column) then go to content types. Find the product type you want to edit, go to manage fields, edit the product variations and down the page a bit is a checkbox called "Auto generate the product title".