Update Symfony components There are many posts and articles that make vague references to upgrading Symfony 3 to Symfony 4 in Drupal 8. But nothing specific.

For example this one by Ryan Weaver "Symfony 4 and Drupal"

I've installed a fresh copy of Drupal 8.8.1 and updated with

 composer update drupal/core --with-dependencies

Then, I ran

composer outdated "symfony/*"

Clearly, there are symfony components that are outdated.

Is it possible to update these "outdated" components? Or, are we stuck till Drupal 9?

As Ryan Weaver mentions,

  The current version of Drupal - 8.4 - requires Symfony 3.2.8 or
  higher, but less than 4.0. In practice, this probably means that your
  Drupal 8.4 project is using the latest Symfony 3.2.* version. But, you
  could technically upgrade your Symfony dependencies to version 3.4.

  Source: Symfony 4 and Drupal

Thus, you can, but only for minor versions.

To quote Dries Buytaert,

  Our biggest dependency in Drupal 8 is Symfony 3, and according to
  Symfony's roadmap, Symfony 3 has an end-of-life date in November 2021.
  This means that after November 2021, security bugs in Symfony 3 will
  not get fixed. To keep your Drupal sites secure, Drupal must adopt
  Symfony 4 or Symfony 5 before Symfony 3 goes end-of-life. A major
  Symfony upgrade will require us to release Drupal 9 (we don't want to
  fork Symfony 3 and have to backport Symfony 4 or Symfony 5 bug fixes).
  This means we have to end-of-life Drupal 8 no later than November
  2021.

  Source: Drupal 7, 8 and 9

He says here that Drupal 8 will reach end of life of Nov 2021 because that's Symfonys 3's end of life. Thus, from this, one can conclude that you can't just upgrade D8 to Symfony 4 (another major Symfony version).


Correct way to change the active Drupal theme programmatically? What is the correct way to change the active Drupal theme programmatically?

Drupal 6 solution:

You want to make sure you change the global $custom_theme variable fairly early in page execution.

global $custom_theme;
$custom_theme = 'garland';


Override taxonomy term path with Views I need to override by views my hierarchical taxonomy term paths:

www.example.com/[vocabulary name]
www.example.com/[vocabulary name]/term1
www.example.com/[vocabulary name]/term1/term2
www.example.com/[vocabulary name]/term1/term2/term3

Where

term1 has depth = 0
term2 has depth = 1
term3 has depth = 2

Vocabulary terms:

+ term1
-- + term2
---- + term3
---- + term3.a
---- + term3.b
-- + term2.a
-- + term2.b

+ term1.a
-- + term2.c
-- + term2.d
-- + term2.e

Paths have been configured by Pathauto

If the path leads to term with depth = 0 I'm using view display "Page".

If the path leads to term with depth = 1 I'm using view display "Page - category".

If the path leads to term with depth = 2 I'm using view display "Page - subcategory".

I tried to use Taxonomy Views Integrator to override the paths by Views, and it's working, but there is one disadvantage in this solution:

If I add a new content and create a new term (with the help of the Simple hierarchical select module ) then I'll be forced to edit this term and select the appropriate view  to override this term path. It might be very time consuming with many terms, so I'm looking for another solution.

How to set a view display for a specific term depth?

I think you are making a little mistake that confuses you.

TVI does not allow to define a view for the vocabulary itself so the path www.example.com/[vocabulary name] cannot be handled by the module. The vocabulary settings are the default ones for all terms within the vocabulary. These settings can be overriden for each term and can be inherited with the latest version. If you want a specific view for your entire vocabulary, you will have to create it by yourself because no vocabulary page exists by default in Drupal.

If I get your problem described in this post and on drupal.org (https://drupal.org/node/2066015) I can suggest you the following :

Define view1 as a page display and give it the path related to your vocabulary's name
Define view2, view3 dans view4 using any path of your choice, it does not matter as TVI will call them directly
Define view2 as the vocabulary's default view
Define view3 and view4 as term's specific settings if needed

When trying to show a term page, TVI will do the following :

If the term has TVI settings, use it
Else find its first parent having a TVI setting with the "override" option and use it
If no parent is found, use the vocabulary's TVI settings

If I take your drupal.org sample you will have :

Terms

Vocabulary (view2)
T 1 (no settings)
    T 1.1 (view 3, not inheritable)
        T 1.1.1 (no settings)
    T 1.2 (view 4, inheritable)
        T 1.2.1 (no settings)
    T 1.3 (no settings)
T 2 (no settings)

Results

T 1 (view 2 from vocabulary)
    T 1.1 (view 3 from itself)
        T 1.1.1 (view 2 from vocabulary)
    T 1.2 (view 4 from itself)
        T 1.2.1 (view 4 from T 1.2)
    T 1.3 (view 2 from vocabulary)
T 2 (view 2 from vocabulary)

I hope this will help you to achieve what you want to do.


How can I override the Calendar module's theme functions? I'm trying to override Calendar module's theme functions. Specifically, I'm trying to override template_preprocess_calendar_month() and template_preprocess_calendar_mini().

The override seems to work, but the problem is that the variables are processed/modified by template_preprocess_calendar_month() and template_preprocess_calendar_mini() before they reach the functions I implemented.

I need access to some of the theme variables before they are processed. Is there a way to do so?

You can create your own custom module and define your own copies of these preprocess functions.

For this example we'll call your module mysite.

In your mysite.module file you would define:

mysite_preprocess_calendar_mini(&$variables)
mysite_preprocess_calendar_month(&$variables)

And then modify the contents of the variables in these functions as needed. Copying the existing preprocess functions might be a good place to start if you're not sure what you want to modify.

Check out the preprocess documentation for some more information about how this system works.


Force Language Path Prefix For Default Language I have a multilingual site configured to use path prefix for URL language detection.

When no prefix is used in the URL, the default language is assumed. How can I change this behavior?

I want the site to return content only when a language prefix is set in the URL, otherwise return a "page not found" error.

Reasoning behind this functionality:

Preventing duplicate content in search engines
Keeping everything well organized (under language prefixes)
Avoiding users to be able to view content without a language prefix and thus potentially link to it (loosing link juice)

Edit: added reasoning.

You can configure it from (admin/config/regional/language/edit/en) if English language is the default and change (Path prefix language code) field from empty to en for example


How to programmatically duplicate a node? I'm looking to create a copy of a webform I've made, with a new email address as the recipient.

After I load the node with node_load, can I just save it with node_save?  Will that create a new node with new timestamps and ids?

How can I get the nid of the new node that has been created?

Just unset the node ID with unset($node->nid), and node_save() will create a new node.

The code executed from node_save() is the following one:

// Insert a new node.
$node->is_new = empty($node->nid);
// ...
if ($node->is_new) {
  _node_save_revision($node, $user->uid);
  drupal_write_record('node', $node);
  db_query('UPDATE {node_revisions} SET nid = %d WHERE vid = %d', $node->nid, $node->vid);
  $op = 'insert';
}

The last argument of drupal_write_record() is not passed; this means the function will not update an existing database row.

Once the node object has been saved with node_save(), $node->nid contains the node ID for the newly created database row.


How to call function by reference? I want to call uc_stock module by reference in my custom module. Actually I want to add and delete stocks. I have done this first using node_presave and it works successfully, here is the code:

function my_module_node_presave($node){
  if($node->type == 'add_stock') {
    //drupal_set_message('stock_save :'.print_r($node,true));
    //drupal_set_message($node->field_reference['und'][0]['nid']);
    //$nid=16;
    //$p_node = node_load($nid);
    //drupal_set_message($p_node->field_product_stock['und'][0]['value']);
    $product = $node->field_stock_value['und'][0]['value'];
    drupal_set_message('product :'.$product);
    $nid = $node->field_reference['und'][0]['nid'];
    drupal_set_message('nid :'.$nid);
    $p_node = node_load($nid);
    $stock = $p_node->field_product_stock['und'][0]['value'];
    drupal_set_message('stock :'.$stock);

    $stock = $product + $stock;
    drupal_set_message('Stock :'.$stock);
    $p_node->field_product_stock['und'][0]['value'] = $stock;
    //$p_node = node_load($nid);

    //drupal_set_message($p_node);
   // drupal_set_message('node_load :'.print_r($p_node,true));

    node_save($p_node);
    //drupal_set_message('after saving product');
  }
 elseif($node->type == 'sold_stock') {
   $new_product = $node->field_sold_stock['und'][0]['value'];
   drupal_set_message('new product :'.$new_product);
  $new_nid = $node->field_stock_reference['und'][0]['nid'];
   drupal_set_message('new nid :'.$new_nid);
   $new_node = node_load($new_nid);
  $sold_product = $new_node->field_product_stock['und'][0]['value'];
   drupal_set_message('sold product :'.$sold_product);
   $product_sold = $sold_product - $new_product;
   drupal_set_message('product sold :'.$product_sold);
   $new_node->field_product_stock['und'][0]['value'] = $product_sold;
   node_save($new_node);
 }
}

Now I want to do the same thing as done in uc_stock module of Ubercart.

I'm not sure if I understood your question correctly, but if you want to change the stock for a product you can simply call the uc_stock_set() function (where the product is in the $node variable, and the new stock is in the $stock variable)

$stock = 5;
uc_stock_set($node->model, $stock); // sets stock to 5

Or use uc_stock_adjust() to increase or decrease the stock by a certain amount

uc_stock_adjust($node->model, 1); // adds 1 to current stock, stock is now 6

I am assuming that you have

Installed ubercart
Activated the uc_stock module
Created a product, and set its SKU (model) to a certain value, say MODEL_1
Gone to the 'stock' tab on the edit node page of this product and activated the stock for MODEL_1

At this point we have a product, represented by a node. This product has one (or many) associated SKUs. Each SKU has an associated stock stored in the database by uc_stock.

Only once all of this is in place can we can go ahead and use the uc_stock_set and uc_stock_adjust functions.


Run lazy-builders of sub-keys in the render array Our page and region templates need to access fields from the custom blocks inside that region.

Unfortunately, {{ region.block_id.field_x }} doesn't work, because region.block_id only contains a #lazy_builder, and therefore the actual variables inside that render array aren't available until we're in the block template itself (at which point it's not possible to inject variables back into the parent template).

Basically, it looks like what we need is a theme_preprocess(&$variables) that iterates over all child elements and recursively evaluates their lazy builders / pre-render hooks, so that all nested elements are available to parent templates. Is there an easy way to do this, or are we stuck with re-implementing parts of the render API here?

This seems like an anti-pattern. Normally you would configure and theme separate instances of the block for the fields you want to display in each region.

If you need block fields in the page template, get the fields directly from the custom block content and put them in variables in page preprocess, see Programmatically accessing block content, or use the module Twig Tweak:

{{ drupal_field('field_example', 'block_content', 1) }}


Taxonomy Terms based on already created content Ok I have a client that builds homes in subdivision.  I have created a subdivision and homes content type.  What I want to be able to do is attach homes to subdivisions.

What i want to be able to do is when a subdivision is created, it will automatically be available as either a taxonomy term, or as part of a drop down available when the client is creating a new home.

Is there a way that I can achieve this using the taxonomy module?

Thanks in advanced.

Instead of using taxonomy term use the following options:

Option 1: References module

  This project provides D7 versions of the 'node_reference' and 'user_reference' field types.

Option 2: Entity reference module

  Provides a field type that can reference arbitrary entities.


How to add registry key verification step with the key being stored in another database I am currently learning how to use Drupal through Udemy classes; I am a complete newbie.

I am building a Drupal Website, for my personal development, and when someone wants to register to the website I want the to fill in the typical form: full name, organization, etc (stuff like what Facebook for example asks). However, I want to add one extra identifier: registry number. What I really need to know is how to make this secure; so that when you type in a number; if it is not correct or it is random, then it would not allow you to register (sounds like the CD keys old PC games had).

Typically, those registry numbers are within the government ministries (say for businesses registries). For example to make taxes you have a registry key, i think that is how it is called; then when you do your taxes online you add that key to verify it is you. But how does the system know that key you entered is correct? It must be connected to a database that has all this information stored.

How do can I make this happen for my drupal website? But is it also feasible? (it must be right?)

What you want is quite doable on Drupal, however if you just started learning Drupal then I am afraid you need to find an experienced developer, who could write up a custom module using the hook_field_validate().


Drupal views contextual filter: use last argument as filter value I would like a views contextual filter to only use the last argument in the url.    Given the following taxonomy structure, I would want /term-a to return Term A1 and Term A2 only (which works fine).  However, if the url is /term-a/term-a1 I would want only Term A1a to be returned, which isn't working, it's still returning Term A1 and Term A2

Within views, I don't see a way to use the last part of the path for the filter.  I tried to remove the argument from the path and then use the following as a default argument:

$path = arg();
return array_pop($path);

Here is the sample term hierarchy:

- Term A
  - Term A1
    - Term A1a
  - Term A2
- Term B
  - Term B1
  - Term B2

Just to reiterate what is returned:

The path /term-a returns:

Term A1
Term A2

The path term-a/term-a1 returns:

Term A1
Term A2

The path /term-a1 returns:

Term A1a

One solution would be hook_views_pre_view()

function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
    if ($view->name == 'view_machine_name' && $display_id == 'my_display_id') {
        $args = array(end($args));
    }
}

For a view with one contextual filter this would always set the argument to the last argument from the URL.


Taxonomy Term Permissions i tried to use Taxonomy Term Permissions
module to set permissions on terms, but this module does not work.
After selecting the roles that i want to allow them selecting the specific term and saving the changes, nothing get saved, i tried also to search for a solution i found a version that worked in drupal 7, i replaced it with the first module.
this version has corrected to allow us to select the roles with saving the changes, but when i requested to create a node(go to create node page) the page did not open and show up a message that tell me an error happen in my site,
There is another module like that one above? or is there another way to set  permission on a terms?
thanks.

There are some other modules you can try:

Taxonomy Access Control

Taxonomy Access Control Lite

A short but good tutorial for Taxonomy Access Control is available at Control Who Can View Drupal Nodes: Taxonomy Access Control


String translations not working after setting language in page preprocess function I am using the domains module (D6) with multiple domains on a 1 site, and we have multiple languages on 1 domain. (We have to have this set up with no other option). Internationalization string translations is enabled and the translated strings in the t() function are in the database.

The domian language setting overrides the node language setting which causes the string translations not to work when having multiple languages on 1 domain.

I have overridden the domain language setting with the node language setting in the theme template_preprocess_page() function and works well but I think it happens too late in the process as the string translations still don't work.

What do I need to do to get the string translations to work?

function phptemplate_preprocess_page(&$vars, $hook) {
  global $language;

  // Reset Language to Page Node Level
  // Get the list of languages
  $languages = language_list();

  // Set up the new language code
  $new_lang_code = $vars['node']->language;

  // Make sure the required language object is actually set
  if (isset($languages[$new_lang_code])) {

    // Overwrite the global language object
    $language = $languages[$new_lang_code];
  }
  var_dump($language) // $language = node language setting
}

I have got this working now by moving the code into the preprocess_node() function instead.

function phptemplate_preprocess_node(&$vars, $hook) {
  global $language;
  $languages = language_list();
  $new_lang_code = $vars['node']->language;

 if (isset($languages[$new_lang_code])) {
  $language = $languages[$new_lang_code];
 }
}


Get Entity ID when is saved I need to capture the entity_id when the entity is saved. The ID will process and insert in a custom field. I use hook_entity_presave(), but when is a new entity the ID is void.
Is there any way to capture the ID?

/**
 * Implements hook_entity_presave().
 */
function MY_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $entity_type = $entity->getEntityType()->id();
  if(($entity_type === 'node' || $entity_type === 'taxonomy_term')) {
    $entity->field_custom_token->value = _process_token($entity->id()); // if entity is new, the ID is Null :(
  }
}

Try changing your code to use hook_entity_insert which is run after the saving to the database:
 https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_insert/8.2.x

As the reason you can't get the entity ID in presave is because if its a new entity then the ID hasn't been generated by the autoincrement ID field in the database yet so an ID doesn't exist for it until it's saved for the first time


How can i change the form default value but not via hook_form_alter I have a question about add a node which have a specific field!

I create two buttons on different page called A,B.

When User touched the A button,i redirect the user to the node_form page.

The specific field default value will be set as ValueA.

When the user touched the B buttons,the value of the specific field will become ValueB.

So i cant user hook_node_form_alter.

I want to write the code at the myform_submit() because of touching the button.

How can i do that?

Are there any method which can change the form value not via the form_alter()?

Please Help Me fix this problem! Thank you!

Let assume you want to create a page. Then create button A which redirect user to /node/add/page?button=a and button B redirect to /node/add/page?button=b

Then in your module create hook_form_alter for node form

function MODULE_node_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node']->type == 'page') {
    if ($_GET['button'] == 'a') {
      $form['FIELD_NAME']['und'][0]['#default_value'] = 'aaa';
    }
    elseif ($_GET['button'] == 'b') {
      $form['FIELD_NAME']['und'][0]['#default_value'] = 'bbb';
    }
    else {
      $form['FIELD_NAME']['und'][0]['#default_value'] = 'ccc';
    }
  }
}


How to set up a view containing a list of events ordered by date I want to have a list of Events on the front-end like this:

Upcoming (Newest on top)
<Event1 title> @ <Event 1 Date>
<Event2 title> @ <Event 2 Date>
.
.
Past (in reversed order)
<Event3 title> @ <Event 3 Date>
<Event4 title> @ <Event 4 Date>

So I created a content type: event:

Title
Description
Start_Date

And a view: events with the filter criteria Type = event.

This gives me a list of all events created. But where to go from here? I created a new views-view--events.html.twig but I don’t know how to retrieve the Start_Date value. Also I think this should/can be done somewhere else?

Thanks!

In the view, you may configure the fields you want to show (assuming you want a list of unformatted fields, for easier theming).

You just pick fields as title or date start/date end, so you have them available when the view is processed.

Having them available, the rest is up to you, your project requirements, and twig :)


How to exclude Views results for custom entities for which a user has no permission to view them? I have a custom entity which I list in views. I set access control for them, but when I list in views these entities, all entities shows up, those one too, which  the user does not have permission to access.

What do I need to implement to filter out those entities, which the user does not have right to view?

After reviewing the list of Views hooks, I think hook_views_pre_render() is the one you can use to filter results before they are rendered.

/**
 * Implements hook_views_pre_render().
 */
function MODULE_views_pre_render(ViewExecutable $view) {
  if (!empty($view->result)) {
    $entities = [
      'your_custom_entity_id',
      'another_entity_id',
    ];

    foreach ($view->result as $key => $result) {
      if (empty($result->_entity)) {
        continue;
      }

      if (!in_array($result->_entity->getEntityTypeId(), $entities)) {
        continue;
      }

      $access = \Drupal::entityTypeManager()
        ->getAccessControlHandler($result->_entity->getEntityTypeId())
        ->access($result->_entity, 'view', NULL, TRUE);

      if (!$access->isAllowed()) {
        unset($view->result[$key]);
      }
    }
  }
}


How to access Machine name fields in PHP? If I go to admin/config/people/accounts/fields I can see a lot of fields being mapped for LDAP on my server.

For example - for first name there is a machine name "field_fname".

How can I access this on my webform using PHP?

Like I want to display something like this on my webform through PHP:

  "Hello first_name last_name, how are you ?"

Here is a little code snippet that should load the value of field_fname into a variable called $first_name.

global $user;
// Load the user object
$user = user_load($user->uid);

$first_name = $user->field_fname[LANGUAGE_NONE][0]['value'];


Temporary add role by token for a particular page to anonymous user I have a specific task: I need to give a temporary access to particular unpublished nodes for anonymous users using access token. Anonymous is a key feature, so I can't create a limited user account by some reasons.

I found a rough temporary solution by adding a field "access token" to my node type, creating a role with access to unpublished nodes (using view unpublished module) and by changing user_access function. I added the following strings:

 if ($_GET['access_token'] && arg(0) == 'node' && is_numeric(arg(1)) && !arg(2)) {

        $node = node_load(arg(1));

        if (isset($node->field_access_token['und'][0]['value']) && $node->field_access_token['und'][0]['value'] == $_GET['access_token']) {

            $account->roles[6] = 'unpublishedaccess';
        }
    }

How can I do similar but without changing Drupal core files?

Assuming that this question is about D7, you could use the Rules module for this, combined with enforcing the usage of an URL argument which must include the correct token.

Here is an example of a relative path you could use/enforce: /node/123?SomeUrlArg=456, which would be for the node with node id = 123 and which uses an URL argument named SomeUrlArg and with the value of that URL argument 456 (obviously, each node can have its own argument value).

To implement this, you would create a custom rule that looks like so:

Rules Event: Drupal is initializing (you must use this event, otherwise you're too late).
Rules Condition: NOT (Check if the URL argument (=SomeUrlArg) is present and that its value matches the value of your field_access_token).

Note the NOT in this Rules Condition: you only want to perform the Rules Action below if either the argument is absent OR if its value doesn't match with the field_access_token value.

To be able to specify these Rules Conditions, you can use the Rules URL argument module. For more details about this module, refer to my answer to "How to use Rules to redirect a user based on URL argument?".
Rules Action: perform a redirect to whatever relative path that fits your needs (but not to /node/123 of course).


Block expands more than the height of content when using collapsiblock module? I have applied the collapsible property to one of the block using Collapsiblock in Drupal 7. everything working fine, but the issue is that, after clicking for slide, it slides more than the content height and then after again in back slides and then fits to the content. I want that it just slide till its content and stops on first instance. Please see attached Image.

This is a wild guess (no time to test this) but you could try some of the following and see if this will make a difference:

Try using a different version of jQuery (download and install jQuery Update and then go to Configuration>Development>jQuery update and test different versions. Don't forget to clear the cache every time before the test).
Try tinkering with your CSS classes for the block and its contents to include a max-height: 100% property. For example, try this for the ID of the block (e.g. #block-block-2) and/or for the .content class inside that block (#block-block-2 .content)


How do I alter the Price Component Title in Commerce Userpoints Discount without altering the module? It seems that when a user adds a Userpoints Discount line item to their shopping cart it appears in the footer as 'Royalty', which will be totally confusing to users.

On line #382 of commerce_userpoints_discount.module there is this code:

function commerce_userpoints_discount_commerce_price_component_type_info() {
  return array(
    'userpoints' => array(
      'title' => t('Royalties'),
      'display_title' => t('Royalties'),
      'weight' => 1000,
    ),
  );
}

Without hacking this module, is there a way I can change this description? In my case, we will be using -two- Userpoints currencies (depending on the type of product the user orders) and we would like the description in the footer to be that userpoints description.

What I've already tried is to create my own hook with a higher weight. My hope was that my hook would take precedence over the default, but apparently not. Perhaps I don't understand 'hooks' well enough yet. If so, could someone tell me how to make -my- hook take precedence?

function my_module_commerce_price_component_type_info() {
  return array(
    'userpoints' => array(
      'title' => t('My Userpoints Currency'),
      'display_title' => t('My Userpoints Currency'),
      'weight' => 2000,
    ),
  );
}

In short, we want the Price Component title to match the currency type of Userpoints on the line item.

The implementations of hook_commerce_price_component_type_info() are invoked from commerce_price_component_types(), which uses the following code.

  // If it did not exist, fetch the types now.
  if (!isset($component_types)) {
    // Find components defined by hook_commerce_price_component_type_info().
    $component_types = module_invoke_all('commerce_price_component_type_info');

    // Add default values to the component type definitions.
    foreach ($component_types as $name => &$component_type) {
      $component_type += array(
        'name' => $name,
        'display_title' => $component_type['title'],
        'weight' => 0,
      );
    }

    // Allow the info to be altered by other modules.
    drupal_alter('commerce_price_component_type_info', $component_types);
  }

As with other hooks, if you want to alter what an hook implemented from another module returns, you need to implement an alter hook.

In your case, the code should be similar to the following one.

function my_module_commerce_price_component_type_info_alter(&$component_types) {
  if (isset($component_types['userpoints'])) {
    $component_types['userpoints']['title'] = t('My Userpoints Currency');
    $component_types['userpoints']['display_title'] = t('My Userpoints Currency');
    $component_types['userpoints']['weight'] = 2000;
  }
}

Generally speaking, this is only possible when the module using the hook is also calling drupal_alter(), such as in this case.


When enabling Clean URLs, test passes, but ticking & updating fails I have mod rewrite running fine and the test passed ont he CLean URLs page, however when I tick the box to 'Enable clean URLs' and click 'Save configuration', I get a message saying 'The configuration options have been saved.' however the box remains unticked and I get the same page below!

Any ideas why it is not enabling here?

This has taken me a long time to resolve also. You need to set the relevant line in /sites/default/settings.php to

$GLOBALS['conf']['clean_url'] = 1;

Mine was set to zero. When I updated this, I realized that my server account didn't have permissions to change the settings.php file, and I suspect this is why it was not able to be updated by Drupal.

Hope this helps


Strange PDOException Error With Computed Field I have a computed field which is calculating values based on an entity reference field. It works fine when calculating an AVG, but I realized today that what I actually would like is for it to find the most popular result in a column. So I altered the code as suggested here. However, now it's throwing me a PDOException error that (I think, I'm not exactly an expert) is related to the WHERE portion of the query. I'm not sure why it would be doing this. The code and error are included below. Any suggestions?

Old, working code:

$entity_field[0]['value'] = "";

$nids = db_query('
    SELECT entity_id
    FROM {field_data_field_review_venue_reference}
    WHERE field_review_venue_reference_target_id = :nid',
    array(':nid' => $entity->nid)
   )->fetchCol();

if (empty($nids)) {
    $entity_field[0]['value'] = "-10";
}

else {
    $entity_field[0]['value'] = db_query('
    SELECT AVG(field_review_payment_value)
    FROM {field_data_field_review_payment}
    WHERE entity_id IN (:nids)',
    array(':nids' => $nids)
   )->fetchField();
}

New, error-throwing code:

$entity_field[0]['value'] = "";

$nids = db_query('
    SELECT entity_id
    FROM {field_data_field_review_venue_reference}
    WHERE field_review_venue_reference_target_id = :nid',
    array(':nid' => $entity->nid)
   )->fetchCol();

if (empty($nids)) {
    $entity_field[0]['value'] = "-10";
}

else {
    $entity_field[0]['value'] = db_query('
    SELECT COUNT(field_review_payment_value) AS `Rows`
    FROM (field_data_field_review_payment)
    GROUP BY (field_review_payment_value)
    ORDER BY `Rows` DESC
    LIMIT 1
    WHERE entity_id IN (:nids)',
    array(':nids' => $nids)
   )->fetchField();
}

Error:

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE entity_id IN ('16', '17', '21', '22', '30', '31', '32', '33', '34', '35', ' at line 6: SELECT COUNT(field_review_payment_value) ASRowsFROM (field_data_field_review_payment) GROUP BY (field_review_payment_value) ORDER BYRowsDESC LIMIT 1 WHERE entity_id IN (:nids_0, :nids_1, :nids_2, :nids_3, :nids_4, :nids_5, :nids_6, :nids_7, :nids_8, :nids_9, :nids_10, :nids_11, :nids_12, :nids_13, :nids_14, :nids_15, :nids_16, :nids_17, :nids_18, :nids_19, :nids_20, :nids_21, :nids_22); Array ( [:nids_0] => 16 [:nids_1] => 17 [:nids_2] => 21 [:nids_3] => 22 [:nids_4] => 30 [:nids_5] => 31 [:nids_6] => 32 [:nids_7] => 33 [:nids_8] => 34 [:nids_9] => 35 [:nids_10] => 36 [:nids_11] => 38 [:nids_12] => 40 [:nids_13] => 45 [:nids_14] => 46 [:nids_15] => 47 [:nids_16] => 50 [:nids_17] => 51 [:nids_18] => 52 [:nids_19] => 57 [:nids_20] => 75 [:nids_21] => 79 [:nids_22] => 85 ) in eval() (line 26 of /Applications/MAMP/htdocs/sites/all/modules/computed_field/computed_field.module(466) : eval()'d code).

Try moving the WHERE clause to before the GROUP BY statement:

$entity_field[0]['value'] = db_query('
  SELECT COUNT(field_review_payment_value) AS `Rows`
  FROM (field_data_field_review_payment)
  WHERE entity_id IN (:nids)
  GROUP BY (field_review_payment_value)
  ORDER BY `Rows` DESC
  LIMIT 1',
  array(':nids' => $nids)
)->fetchField();

MySQL queries have to follow a certain format and the WHERE clause needs to be before GROUP BY, ORDER BY, LIMIT, etc.


Webform Conditional fields showing by default I am using the Webform Conditional module to control visibility of some webform components until a checkbox has been ticked.

I found recently that the conditional fields were showing by default (they were not doing so previously).

To add to my confusion, the same set of related fields worked just fine on some nodes but not on others.

Then just as suddenly as the problem appeared, it vanished and my conditional fields began working as expected again.

The site is soon to be LIVE and it be really bad if this problem unexpectedly returns.

Can anyone offer some opinion as to why that happened, especially if it has happened to you before, and how I can make it more stable, please?

@kine456: My problems with webform conditional were very occasional. I mean sometimes they were there and other times they just disappeared.

I am also using webform template. On the templates, the conditional fields always worked but not so on the webforms inheriting from the template.

Thankfully, conditional fields have been built into webforms. I downloaded and currently use version#7.x-4.0-alpha6. No problems to report so far


Drupal.attachBehaviors only working for some fields when using Ajax .load The following code works for some things that I do in terms of .load() such as adding Chosen to fields.
But it won't do anything to date fields, conditional fields or field groups. They get left with no JS.

I've added other similar forms on the page as a test so the scripts are available and I've also added the scripts to the theme's .info file.

Is there any way to fully .load() a form? It has to added using Ajax as it's a really slow form and kills website performance.

EDIT: As Jimmy Ko pointed out, this isn't a good method. Instead, this link shows how to change the target of a form submit in an iFrame to the parent so I'll try loading the form that way with a custom tpl so only the form is shown in the iFrame.

   (function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    // Check so it doesn't repeat load
    if ($('#page-content-st-node-form').length == 0) {
    // Load
     $('.page-bar').load('/node/add/page-content-st #page-content-st-node-form', {}, function() {
     Drupal.attachBehaviors($('#page-content-st-node-form'));
     });

    }

  }
};
}

)(jQuery);

$.load() will not update the Drupal.settings object, which contains the references to which fields need to be ajaxified. This is why you are seeing the issue you have. In order to load a form through AJAX, you need to return the form as well as the settings for the form alonng with the form, after the form has been rendered. This will update the Drupal.settings object, which then will ajaxify your form.

First you need to declare a callback path in hook_menu()

function hook_menu()
{
  $menu['my/ajax/callback'] = array
  (
    'title' => 'AJAX callback',
    'page callback' => 'my_ajax_callback',
    'access callback' => TRUE,
  );

  return $menu;
}

Then you need to generate your form, and ajax settings, in the callback path

function my_ajax_callback()
{
  $form = drupal_get_form('some_form');
  $rendered_form = render($form);
  $javascript = drupal_add_js(NULL, NULL);
  $settings = FALSE;
  if(isset($javascript['settings']))
  {
    $settings = '<script type="text/javascript">jQuery.extend(Drupal.settings, ' .
      drupal_json_encode(call_user_func_array('array_merge_recursive', $javascript['settings']['data'])) .
    ');</script>';
  }

  $response['form'] = $rendered_form . $settings;
  drupal_json_output($response);
}

Finally, you need to make an ajax call to get your form, and append it to the page somewhere, finally calling Drupal.attachBehaviors()

$.ajax(
{
  url:'/my/ajax/callback',
  success:function(data)
  {
    // Create a div and set the returned data as the contents,
    // so as to turn them into HTML
    var formElement = $("<div/>").html(data.form).contents();

    // Append the form somewhere on the page
    $("#some_container").append(formElement);

    // Finally call Drupal.attachBehaviors
    Drupal.attachBehaviors(formElement);
  }
});

For more of an understanding on what I'm doing with Drupal behaviors, read my tutorial on working with JavaScript in Drupal 7, in particular the section on attaching behaviors: http://www.jaypan.com/tutorial/high-performance-javascript-using-drupal-7s-javascript-api


Hundred of Thousands of database records and how to safely delete them? Hi
I've been asked to work on a Drupal commerce site and I'm not very familiar with this module.

The idea is to use an existing database and export it to 'quickstart' a new site.
I'm to keep all the products but delete all the customers and transactions data.
But when I look at the DB of the existing site it's packed with hundreds of thousands of stuff that I don't understand.

The product catalog only includes 50 or 80 products or so but in the database I see an incredible number of rows in some of the table and I don't know how I can safely remove all this data without breaking the database. Here is what I see in php/myadmin:

field_revision_commerce_unit_price   ~210,219 InnoDB    utf8_general_ci 129.7 MiB   -
field_revision_commerce_total    ~211,353    InnoDB utf8_general_ci 128.7 MiB   -
field_data_commerce_unit_price   ~210,696    InnoDB utf8_general_ci 128.6 MiB   -
field_data_commerce_total    ~209,449    InnoDB utf8_general_ci 127.6 MiB   -
field_revision_commerce_order_total ~210,849 InnoDB utf8_general_ci 125.5 MiB   -
field_data_commerce_order_total  ~210,129    InnoDB utf8_general_ci 119.5 MiB   -
field_revision_commerce_product  ~210,384    InnoDB utf8_general_ci 82.5 MiB    -
field_data_commerce_product  ~210,384    InnoDB utf8_general_ci 81.4 MiB    -
field_revision_commerce_line_items ~211,257  InnoDB utf8_general_ci 81.4 MiB    -
field_revision_commerce_display_path ~210,521 InnoDB    utf8_general_ci 77.5 MiB    -
field_data_commerce_display_path ~210,521    InnoDB utf8_general_ci 76.4 MiB    -
field_data_commerce_line_items   ~210,393 InnoDB    utf8_general_ci 75.4 MiB    -
field_revision_field_dept_date   ~210,384    InnoDB utf8_general_ci 69 MiB  -
field_data_field_dept_date ~210,384 InnoDB  utf8_general_ci 68.9 MiB    -
commerce_line_item   ~211,134 InnoDB    utf8_general_ci 34.6 MiB    -
commerce_order   ~210,442 InnoDB    utf8_general_ci 34.1 MiB    -
commerce_order_revision ~212,036 InnoDB utf8_general_ci 26.1 MiB    -

I'm really lost here isn't there a quicker way to delete all the unnecessary data while keeping the product catalog intact?
Thanks

Forget about accessing the database manually, you will just break things.

For mass-deletion create a VBO-based view.

Same thing for export, you will want to export whole entities, not tables.


How to get EMI Calculator module I am developing a Real Estate website for that i need EMI calculator Module.
From where i can get this.

Is there any module is developed for EMI Calculator

A quick google search gives me the impression  that there is no such module available just yet.

Feel free to provide it to the community if you want ;-)

You can take a look here if you want:

http://emicalculator.net/emi-calculator-widget

That might  give you a good starting point.


Display an image through page.tpl.php only on front page I want to display an image only on front page through page.tpl.php... However i am not sure about the syntax or where i am going wrong as the code that i type in leads me to en error (syntax error)...here's the code:

<?php  if (drupal_is_front_page())
    {

    }
?>

Rather than editing in page.tpl.php which applies on all pages, you should create a template file called page--front.tpl.php and add image there if you want to display the image only in front page.

EDIT

For more theme hook suggestions refer this page


How to add multistep registration form in default user registration I need to create a user registration form in Drupal 7. My requirement is as follows:-

I want to use the default Drupal 7 User Registration Form i.e admin/config/people/accounts
Form must appear in popup/modal when user click on "Create new account" in User Login Form
Form should be Multistep i.e there will be 3/4 steps of filling the form.
Customize the form in such a way that UserName, Password and Email
appears on last step of the form.

Please let me know if it is possible in Drupal 7 default user registration form and how?

You can try Field group

  Fieldgroup will, as the name implies, group fields together. All
  fieldable entities will have the possibility to add groups to wrap
  their fields together. Fieldgroup comes with default HTML wrappers
  like vertical tabs, horizontal tabs, accordions, fieldsets or div
  wrappers.

Available group types

Fieldsets
Horizontal tabs
Vertical tabs
Accordions
Divs
Multipage steps: Note: This is only client side.

The idea is to use Multipage steps to make the form steps.


Refer a Node in Forum Post Is there a way to refer to a node in a forum post?

Like I want to put a hyperlink to the node with the node title as the display name. Is there any short handed variable that allows me to do that?

Thanks

Have a look at Freelinking Casetracker.

Drupal.org itself also automatically converts [#nid] found in issue comments to Node links, but I'm not sure if they're using this module or another similar input filter.

Writing your own input filter is pretty straightforward if those don't exactly match your needs.


Display Views Result Summary in Twig Template I have views with exposed filter and display exposed filter as a block. I need something like views result summary on my twig template. How am I supposed to achieve this in Drupal way.

I hope you mean views results count. If that is what you are looking for then you get it by  {{ view.total_rows }}


Why am I unable to send an email order using the Ubercart and Smtp Authentification module? After Ubercart checkout submitting order, I get this error:

  Unable to send email. Contact the site administrator if the problem
  persists.

I am using the SMTP Authentication Support module, I configured it correctly. Test mails work. So the error lies probably within Ubercart.

On Drupal /admin/reports/dblog, I get this interesting error log:

  Error on sending e-mail (from admin@xxxxx.com to
  admin@xxxxx.com.com).

it tries to send the mail to the sender mail? Very weird!

How to get this resolved?

Okay I found the solution using the instructions at "Drupal – Ubercart and SMTP Authentication Support".

I installed Mail System module.
In the Mail System configuration, I updated the Cart module class, Order module class and Store module class so that they all use the SmtpMailSystem rather than UbercartMailSystem, as shown in the screenprint below:


Prepopulating a multi-select on a webform I have a webform with a multiselect box.  I want to use the prepopulate module to allow people to set the default value in the URL.  The following works, but it only supports selecting one value:

/mywebform?edit[submitted][multiselect_name]=Value

Other places have suggested using URLs like the following, but that doesn't work for either one URL or multiple:

/mywebform?edit[submitted][multiselect_name][]=Value

When I pass multiple URL parameters, it just takes the last one, so Value2 is selected in the following example rather than Value and Value2:

/mywebform?edit[submitted][multiselect_name]=Value&edit[submitted][multiselect_name]=Value2

As a workaround, I could define custom GET parameters for each item in the webform using the webform module, but I was hoping to make everything consistent, and as far as I can tell, webform doesn't support GET parameters that use array notation (as per http://drupal.org/node/824606), so neither of the following works as the default in the webform module:

%get[edit][submitted][multiselect_name]
%get[edit[submitted][multiselect_name]]

Thanks for the help!

I have just read through the code of Prepopulate module, and it seems that as for now it doesn't support the feature you're after. The prepopulate module just assigns whatever is passed as a parameter to #value of the corresponding form element. To have multiple items selected you need to assign to #value something like this: array('Value 1', 'Value 2'); but there is no way you can pass this via parameters.

THe possible workaround is to hack the module code. Add the following code on the line #78 of the file - prepopulate.module

  if($form['#type'] == 'select' && $form['#multiple'] == TRUE) {
    $requestslice = explode(',', $requestslice);
  }

just before this line:

  $form['#value'] = $requestslice;

This change will allow you to pass multiple values as a comma separated list, for example:

  mywebform?edit[submitted][multiselect_name]=Value1,Value2

I have just created a patch for for the prepopulate module that implements this thing, you can find it here:

http://drupal.org/node/1468024


The block isn't shown on the front page I have a view block that shows a sub-set of nodes. In the configuration page, the autopreview section shows content, so I know the filters for the view are set up correctly. I configured the block to show on only the listed pages and entered <front> for the page.  Unfortunately, the front page shows only the following content and a static block.

  No front page content has been created yet.
  •Add new content

The weird part is that this static block is configured the same way the view is configured  to show only on the front page.

Why doesn't the view block appear on the front page?

There is something else you should check. If this is a new site, and you have newly named regions, make sure that the regions have underscores (instead of dashes.) If you need to convert any dashes to underscores, you'll have to reassign and re-enable the blocks on the Structure > Block Layout page.


How to add a field to Views table output with hook_views_pre_render? I have a view displaying node titles formatted as a table. In a custom module I'm using hook_views_pre_execute to do do a table join and add a field to the views query. (I cannot use a regular relationship in Views to accomplish the join, because it has to be a RIGHT JOIN).

When I inspect the resulting view object with dpm($view) in hook_views_pre_render, I can see that the objects in $view->result contain the string values of the node_title, nid, and field_myfield_value (where field_myfield_value is added via the custom module).

But how do I actually display field_myfield_value in the view? And more specifically, how do I make it a column of the table?

To take a different approach: you could add the field through the UI as normal, and use hook_views_query_alter() to change the join type:

function MYMODULE views_query_alter(&$view, &$query) {
  if ($view->name == 'my_view' && $view->current_display == 'foo') {
    $query->table_queue['field_data_field_myfield']['join']->type = 'RIGHT';
  }
}

That should get you the same effect with a bit less effort.


Redirect to a content page after login only from that page On one certain page of my site, users have to log in before going any further. They don't have to be logged in to see most of the rest of the site content, but on this one specific page, they do have to be logged in. I figured out how to put a barrier up that forces users to log in before seeing that page's content (i.e., if users aren't logged in, the only thing on the entire page is a line that says "To create content, you must first log in" and there's a link to the login page), but how do I redirect newly logged-in users directly back to that same page (which now will have content on it) so they can now see its content?

At the moment, after they log in, it just takes them to their profile page.

In other words, if users log in on any other page, it's fine if they're redirected to their profile page, but on this one specific page, they need to stay put. I've seen lots of variation of the following code:

function hook_user_login(&$edit, $account) {
drupal_goto('node/1');
}

But I don't think this is what I'm trying to accomplish. The current code I have in there looks like this:

$sample1 = 'log in.';
$sample2 = 'To create a classified ad, you must' . " " . $sample1;

global $user;
if ($user->uid == false){
return $sample2;

}

I've seen some code like this that looks promising:

#action' => url($_GET['q'], array('query' => drupal_get_destination()))

But I can't figure out how to make it work. Anyone got any ideas?

Hope this will give you,

In Drupal 7, you can achieve it by using destination parameter.

Just add the destination parameter in the URL where you want to redirect it.

For example if you are in login page and after login if he want to redirect to some node say about page then

YOUR_DOMAIN/user/login?destination=about

Just add the destination parameter in "To create content, you must first log in" link. On click of this link it will redirect to User login page with the destination parameter. After login it will redirect to the path you have specified in the destination value.


Adding script conditionally In the module I am developing I need to add script which require jQuery.The will be added depending on configuration settings. Hence I am using template_preprocess_module(&$variables) where I am trying to add script by doing something like this:

function template_preprocess_module(&$variables) {
  if (TRUE) {
    $variables['jquery'] = ?;
    $variables['script'] = 'path to script in module';
  }
}

Then in the template I will simply be rendering these variable in the head section. But I am facing trouble in adding jQuery, because I don't know its source (obviously I know its source in core but I need something over here which automates path). Can the source be known by using something like drupal_get_path() ? I am also not sure if this is the best way to add script conditionally, any suggestion regarding this? Thanks.

To attach a script in Drupal 8 you need to define a library first in your modules *.libraries.yml (replace * with your modules machine name).
The file should look as follows:

libraryname:
  version: 1.x
  js:
    js/script.js: {}
  dependencies:
    - core/jquery

After that you have the possibilities to attach a script through a preprocess function or directly in the template with a twig function.
I believe you are trying to achieve the first. In that case you need to modify the render array, like in this example:

<?php
function modulename_element_info_alter(array &$types) {
  if (isset($types['table'])) {
    $types['table']['#attached']['library'][] = 'modulename/libraryname';
  }
}
?>

If you want to append a script to every page depending if a custom setting is activated in your module, you should do as follows:

function modulename_page_attachments_alter(array &$page) {
  if ($settingIsTrue) {
    $page['#attached']['library'][] = 'modulename/libraryname';
  }
}

You can read more about it in the manual.


Programmatically get the continent from ISO2 I am using the Countries module to assign countries and associated data to nodes. I am currently writing a custom token and only can access the ISO2 data for the value, not the associated data (full name, language, ISO3).

How can programmatically get the other data with only the ISO2?

Continuing the answer from the initial question, I think you have to load the Country entity to replace the token with what values you are after.

Based on looking at the Countries module, it stores countries as a custom entity:

/**
 * Implements hook_entity_info().
 */
function countries_entity_info() {
  $return = array(
    'country' => array(
      'label' => t('Country'),
      'plural label' => t('Countries'),
      'entity class' => 'Entity',
      'controller class' => 'EntityAPIControllerExportable',
      'base table' => 'countries_country',
      'token type' => 'country',
      'fieldable' => TRUE,
      'module' => 'countries',
      'entity keys' => array(
        'id' => 'cid',
        'name' => 'iso2',
        'label' => 'name',
      ),
      'bundles' => array(
        'country' => array(
          'label' => t('Country'),
          'admin' => array(
            'path' => 'admin/config/regional/countries',
            'access arguments' => array('administer site configuration'),
          ),
        ),
      ),
      'view modes' => array(
        'full' => array(
          'label' => t('Country'),
          'custom settings' => FALSE,
        ),
      ),
    ),
  );
  return $return;
}

/**
 * Loads a country entity by ISO alpha-2 code.
 *
 * This is also a menu wildcard loader.
 *
 * @param string $iso2
 *   An ISO alpha-2 string. This is case-insensitive.
 *
 * @return object
 *   A country object loaded by the entity controller.
 */
function country_load($iso2) {
  // The URL's should be case insensitive.
  $iso2 = $iso2 ? drupal_strtoupper($iso2) : $iso2;
  return entity_load_single('country', $iso2);
}

It looks like the iso2 value is the entity id, based on this code and the helper load function here, so, you can access the full entity when a token is replaced by:

/**
 * Implements hook_tokens().
 */
function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = [];

  if ($type == 'node' && !empty($data['node']) && array_key_exists('MYTOKEN', $tokens)) {
    $country = country_load($data['node']->field_prgm_country[LANGUAGE_NONE][0]['iso2']);
    // $country should be a fully loaded Country entity with all its fields and properties
    // check out $country here with ksm($country);exit;
    $replacements['[node:MYTOKEN]'] = // data you want to show;
  }

  return $replacements;
}

It looks like the Country module provides its own country: scope of tokens, but I do not know how (or if) they work in the context of fields on a node. This should get you closer at least.


Where to set the DOCTYPE? My zen subtheme doctype is currently !DOCTYPE html and I would like to change this. What is the correct place to add the doctype I want to use?

I copied the html.tpl.php file and pasted it into the templates directory of my subtheme thinking that's where it's set, but it's not being picked up...

You're in the correct place (html.tpl.php) to modify the doctype assuming you're using Drupal 7, thats the default theme implementation for altering the basic page structure (documentation). In Drupal 6, you're looking for the page.tpl.php file.


How to send node as body content in email using Rules? I wonder if there is a way of inserting the contents of a node into the body of the email when using the Rules module?

It depends on the Rules Event that your rules is using ... e.g.:

If Rules Event is something like "After updating existing content", then you'll be able to use token [node:body] within (eg) the message body of Rules action "send eMail".
If Rules Event is (eg) "After updating an existing user account" then token [node:body] is not available for using it within (eg) the message body of Rules action "send eMail".


Getting rid of strongarm in features export I exported a feature and it came wiht a bunch of strongarm configureation that I didn't want. I was able to delete most of it, but I wasn't sure about this part:

/**
 * Implements hook_ctools_plugin_api().
 */
function mymodule_ctools_plugin_api() {
  list($module, $api) = func_get_args();
  if ($module == "strongarm" && $api == "strongarm") {
    return array("version" => "1");
  }
}

Can I get rid of it altogether, or should I just have it return the version, for ctools?

the short answer is yes you can delete it since you don't have any strongarm stored in this feature.

usually features add 3 pieces of code to any exported type:

the configuration it self in a file feature_name.features.config_group.inc or feature_name.config_group.inc
the include part in features feature_name.features.inc
what are the content of the export in feature_name.info

you can delete those manually and the feature will act as if they where never there, though removing a complete set of config group (e.g: remove all strongarm config) form the features UI will usually leave you with config file .config_group.inc (1), and rarely with include settings in .features.inc, which you can delete them manually.


Passing parameters from Panel to View (contextual filter) I ran into a little problem today, I have a specific panel for all my products.
This panel contains out of a 3 column layout.

One of those columns contains a list of all other products in the same category. (which is a view).

When I created the view, I added a contextual filter to only display products out of the category that was send. (Categories are nodes and linked by a node reference) (This is just to allow the client to easily add and remove categories so he doesn't have to use the build in taxonomy)

I noticed however that I can only use the node id of the category to filter.

The problem is that the Panel only sends the string to the View, so the filter doesn't work.
Is there a way to get the node id of the linked category?

General solution:

Your View should have a "Content pane" display
Your pane should be configured to require an argument that matches the one your contextual filter wants.
Add the pane to your page.

For your specific question, I don't understand how you pass a string at all to Views, so I need more info about your setup to be more specific.


Libraries Not Loaded After Cache Clear / Reload I'm experiencing a problem with drupal 8

whenever I clear the cache, my custom theme's libraries(ex: the css and js) will not be loaded

and I must reinstall the whole drupal to make it works again

is there anything I can do to trace the source of the problem ?
Nothing strange is being logged in nginx and php's error log

Solved

this issue occurred because I've another custom module with the same name as the theme.


What changed in the way to implement a block? The documentation for Drupal 8 lists the following hooks as the ones necessary to implement a block.

hook_block_access() controls which users have access to a block
hook_block_view_alter() is used to alter how a block implemented by other modules is rendered
hook_block_view_BASE_BLOCK_ID_alter() is a specialization of the previous hook, similarly to what hook_form_FORM_ID_alter() is for hook_form_alter()

What I don't find is hook_block_info(), which in Drupal 7 allowed to expose the blocks defined from modules, and hook_block_view(), which was invoked when a block defined from a module was rendered in a page.

How do modules expose blocks, in Drupal 8? How are the blocks rendered?

Using the "Powered by Drupal" block as an example:

Drupal 7

modules/system/system.module

/**
 * Implements hook_block_info().
 */
function system_block_info() {
  $blocks['powered-by'] = array(
    'info' => t('Powered by Drupal'),
    'weight' => '10',
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function system_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'powered-by':
      $block['subject'] = NULL;
      $block['content'] = theme('system_powered_by');
      return $block;
  }
}

Drupal 8

core/modules/system/src/Plugin/Block/SystemPoweredByBlock.php

<?php

/**
 * @file
 * Contains \Drupal\system\Plugin\Block\SystemPoweredByBlock.
 */

namespace Drupal\system\Plugin\Block;

use Drupal\block\BlockBase;
use Drupal\Component\Annotation\Plugin;
use Drupal\Core\Annotation\Translation;

/**
 * Provides a 'Powered by Drupal' block.
 *
 * @Plugin(
 *   id = "system_powered_by_block",
 *   admin_label = @Translation("Powered by Drupal"),
 *   module = "system"
 * )
 */
class SystemPoweredByBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#children' => theme('system_powered_by'),
    );
  }
}

The hook_block_info() is replaced by an annotation, containing all of the necessary metadata within the @Plugin portion of the docblock. hook_block_view() is replaced by the BlockPluginInterface::build() method.

The directory structure is the key here. All blocks must be placed into a specific directory within their module folder (src/Plugin/Block).


Rules react on event for file_managed table? Im looking for a solution to be able to create a "react on event" in rules for when a file is added to the file_managed table. Is it possible and if so, how?

I have looked and it is not an easy thing to accomplish with rules/drupal strictly. So instead I took a different approach that works great :)

I have a separate database that I use for various things which is added through my settings.php so available to drupal. I have added a newfiles table to this db. I then use on the file_managed table a trigger:

CREATE TRIGGER `newfile_trigger` AFTER INSERT ON `file_managed` FOR EACH ROW INSERT INTO otherdb.newfiles (fid,uid,filename,uri,filemime) VALUES(NEW.fid,NEW.uid,NEW.filename,NEW.uri,NEW.filemime);

In my custom module I then have a hook_cron that looks up the entries on the newfiles table every minute, performs the necessary functions and then deletes the row.


Strange problem with enabling/disabling modules I just moved my Drupal 7 site over from one host to another. At first, everything seemed to be working just fine, but I keep getting this strange problem when dealing with modules.

The installation appears to go without a hitch, and it shows up in the modules list. It also shows up under the correct path in /sites/all/modules/$modulename. However, the problem I get is two-fold:

Attempting to go to the configuration page for the module does virtually nothing. It just takes me to the related menu for whatever admin category that particular module falls into. (For example, Disqus would take you to Web Services rather than a Disqus configuration panel).
Disabling the module doesn't remove it from the configuration menus, either. I've tried running cron, flushing my caches, and even using the registry_rebuild scripts.

This also affects my themes now. I can't seem to get any of my new themes to appear in the directory when I upload them into my /sites/all/themes/ directory. I can remove themes manually, and they disappear at least. But, as you can imagine this is all a very frustrating problem. I think it may possibly be a permissions error, but frankly I really have no idea.

My first thought was permissions, but I don't think that incorrect file permissions would result in the kind of problems you're seeing.

Have you checked that the server has all the same extensions installed for PHP? If you've still got access to the old server, put a phpinfo() page on both server and compare the extensions that are available to see if any are missing.


How should I create a main page with a mix of dynamic and static content? I apologize for the terribly basic question but I'm not even a particularly adept web dev.  I've read that Drupal is great if you know exactly what you want to do (then the API is handy) but I don't even know what I need yet. That is what I am hoping to gain from this discussion.

I want a main content page which has a fancy content slider (using jQuery or something) which will be a selector for showing some basic information on these 2 or 3 subjects.  I'm stuck on where I should be writing this mix of markup. In the template? Create "content" through a content type?  Since there's a fair share of CSS and markup required to do this, I don't know if I can do that through the "basic page" content type that was there.

I'm looking for pointers that can teach me how I would become aware of what Drupal can and can not do.

There are a number of options available to customise the front page -

have a look at
http://www.devdaily.com/blog/post/php/how-customize-content-front-page-drupal

I usually go the route of creating a custom page-front.tpl.php (as explained in the link above) and then use a combination of views and blocks to get in the content I need.

hope this points you in the right direction...


Using a View as a filter criteria to another view How can I a view as is one of filter criteria for another view, So that it provides a list of possible options?

You can try the Views filter view sandbox module, which does exactly what you are asking for.

  This module will allow to filter results by another view.
  This other view is either not active on the current site at all, then the view is executed and the result is taken.

  If the view on the site was runned already, the result is reused


Validate a comment from a custom module I want to validate comments using a custom module; I am using hook_comment(), and "validate" as value for $op, but I cannot get the value of the comment field. How do I get the comment value from a custom module?

Assuming you're working in Drupal 6:

/**
 * Implementation of hook_comment().
 */
function mymodule_comment(&$a1, $op) {
  switch ($op) {
    case 'validate':
      $subject = $a1['subject'];
      $comment = $a1['comment'];
      // validate here
      break;
  }
}

In Drupal 7 hook_comment() is gone, being replaced by a set of hooks hook_comment_view(), hook_comment_load(), etc. Unfortunately there is no hook_comment_validate() but see this answer for a solution.


Where is the Image Field Settings Form http://drupal.org/node/1558548

That page says I can fix this bug by visiting the image field setting form - where is this located exactly? I can't find it.

Didn't read the linked site, but:

Image styles are managed here "admin/config/media/image-styles"
Image Field settings are managed here: Visit "Structure" -> Content types -> Edit %your-content-type% -> Manage fields tab -> Click edit link in the row of %your-img-field%


url alias not working on https I am using Drupal 7.40. I just found a redirect issue on my website.

When I enter "http://www.website.com/node/439432" in the browser, it will 301 redirect to "https://www.website.com/myalias.html" correct.

However, I enter "https://www.website.com/node/439432" in the browser, the webpage will not redirect to my URL alias page.
When I check the network, I got 200 status for the node page.

Use the Global Redirect module to achieve this: https://www.drupal.org/project/globalredirect


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

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

Create a view with a page display.

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

Set a path for the first feed display.

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

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

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

I hope this helps!


How can I add a custom currency to commerce? I'm trying to add a custom currency (like points) but I can only choose the "real world" currency. Can I change the currency in commerce or I have to do it with a module? If so, which module should I use? Thank you !
PS: I have to do it in commerce, is for a school project

Have a look at the Commerce Userpoints module. Some details from its project page:

It allows users to create commerce_line items with negative points value, behaving like a discount system in the order process.
The user can choose how many points he wants to use, they will be automatically taken from his userpoints account.


How to count the number of posts by a author? D8 I see how to do this in D7. I tried to do something similar in D8.

I tried using Entity instead of Content because there is no content:nid option in D8 my view looked like this

(author) COUNT(File Usage: Entity ID) (Count by User) | Aggregation settings

but my results where all 0

There is no difference between Drupal 7 and Drupal 8 on how to accomplish this.

From a default Content view:

Add the "Content: Authored By" field to the view.
Click "Use Aggregation" and change to yes.
Click "Aggregation Settings" to the right of "Content: Title".
Change to COUNT and Entity ID respectively.

View export:

langcode: en
status: true
dependencies:
  module:
    - node
    - user
id: content_with_author_count
label: 'Content with author count'
module: views
description: ''
tag: ''
base_table: node_field_data
base_field: nid
core: 8.x
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: perm
        options:
          perm: 'access content'
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: none
        options:
          offset: 0
      style:
        type: default
        options:
          grouping: {  }
          row_class: ''
          default_row_class: true
          uses_fields: false
      row:
        type: fields
        options:
          inline: {  }
          separator: ''
          hide_empty: false
          default_field_elements: true
      fields:
        title:
          id: title
          table: node_field_data
          field: title
          relationship: none
          group_type: count
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: false
            ellipsis: false
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: string
          settings:
            link_to_entity: false
          group_column: entity_id
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: node
          entity_field: title
          plugin_id: field
        uid:
          id: uid
          table: node_field_data
          field: uid
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: target_id
          type: author
          settings:
            link: 0
          group_column: target_id
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          set_precision: false
          precision: 0
          decimal: .
          format_plural: 0
          format_plural_string: "1\x03@count"
          prefix: ''
          suffix: ''
          entity_type: node
          entity_field: uid
          plugin_id: field
      filters:
        status:
          value: true
          table: node_field_data
          field: status
          plugin_id: boolean
          entity_type: node
          entity_field: status
          id: status
          expose:
            operator: ''
          group: 1
      sorts: {  }
      header: {  }
      footer: {  }
      empty: {  }
      relationships:
        uid:
          id: uid
          table: node_field_data
          field: uid
          relationship: none
          group_type: group
          admin_label: author
          required: true
          entity_type: node
          entity_field: uid
          plugin_id: standard
      arguments: {  }
      display_extenders: {  }
      group_by: true
    cache_metadata:
      max-age: -1
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - 'user.node_grants:view'
        - user.permissions
      tags: {  }


Create a PDF with one result from a view I have a view with information from a specific database table and I want users to be able to generate a PDF with the results from one row, which would contain all the information from the row. So far, I've only been able to generate a PDF of an entire view instead of one result. I'm not sure how to "tell" the PDF which view result to generate as a PDF.

Note: This is a different way of asking a question I previously posted, which I think was too confusing at this point.

It is just an idea. You need to create a one more view with same field. But you use views contextual filters and also use view pdf in this view . create a link for print with where you pass argument for this view . Print this link in your first view using view php.

You can also do this custom . create a custom menu item .Pass argument (id,nid) load content programmatically and add pdf download option.

Thank you


Create a Views Block to show all Node 'Attached Files' as a File list. In creating the CMS structure, I've been trying to do this today, but seem to be getting no where.

I simply want to show all the files as link (PDF, Doc, Docx etc) that have been uploaded by a user to a node type listing which has a Field already created in the Content type structure (by me, the Admin/web) using Views. I've got as far as creating the View with the relevant fields and set it in the Panel Page as a block, but in testing nothing seems to show.

All I require is any relevant 'attached' files related to that Node Content (ie XYZ rock Band, attached mp3 files at bottom of page) so that future readers can click to download to local.

Can someone refresh my memory as how to do it so I can compare where I may be going wrong? I have set the author ID in Relationship, but still the files I have set do not show. Maybe I'm missing something here.

Based on the discussion above, create a new view, and configure and filter it however you need. the main part is to have the file display as link for download. For this, when you add the relevant field to views, in the settings form, there will be a drop down option for "Link this field to". Choose "File" from there and the field value will be linked to it. Clicking on it will allow the user to download the file. Hope this helps.


Entityreference not saved correctly inside ContentEntityForm I was having a weird bug with my views. Some entity-references from my main-entity didn't show up in my view.

I investigated further with entityQuery and came across some weird action.
I can get the missing referenced entities by querying for nulls in main_entity and loading the referenced entities manually using the magic entity getter:

// Returns 90 main-entities. These correspond to the entities with missing data in my view.
$main_entity_ids = \Drupal::entityQuery('main_entity')
  ->notExists('field_referenced_entity')
  ->sort('created')
  ->execute();
$main_entities = \Drupal\my_module\Entity\MainEntity::loadMultiple($main_entity_ids);

// Load referenced entities for each main entity using the magic entity getter
$referenced_entities = [];
foreach($main_entities as $main_id => $main_entity){
  // Skip nulls
  if($referenced_entity = $main_entity->get('field_referenced_entity')->entity){
    $referenced_entities[$referenced_entity->id()] = $referenced_entity;

    // // Re-saving the entity here doesn't help
    // $main_entity->set('field_referenced_entity', $referenced_entity->id())
    // $main_entity->save();
  }
}

// At this point $referenced_entities -array contains 90 fully loaded refenced entities.

Also, the table main_entity__field_referenced_entity is missing rows for the missing references. I wonder how am I able to get the reference with the magic getter.

I tried to re-save all the entities in my loop but with no success.

The main-entity is first created and saved without the reference which is added afterwards inside ContentEntityForm::save()-method.

...
// Entity is saved and re-loaded
$main_entity->save();
$main_entity = \Drupal\my_module\Entity\MainEntity::load($id);
...
// Set the reference and save
$main_entity->set('field_referenced_entity', 123);
$main_entity->save();
...

Creating the MainEntity programmatically seems to work, inserting the required rows to the main_entity__field_referenced_entity -table:

$main_entity = \Drupal\my_module\Entity\MainEntity::create([
  'type' => 'main_entity',
  'status' => 1,
  'name' => 'Programmatically created MainEntity',
]);
$main_entity->save(); // No rows
$main_entity = \Drupal\my_module\Entity\MainEntity::load($main_entity->id());
$main_entity->set('field_referenced_entity', 123);
$main_entity->save(); // Row added

The problem seems to have started after updating to Drupal 8.5 from 8.4.4. I was running Drupal 8.5.3 when I noticed the problem. Updating to Drupal 8.5.5 doesn't help.

Does anyone have any idea what could be going on?

Found the cause!

Someone had added the line

$this->getReferencedEntity();

to the MainEntity::__construct()-method.

getReferencedEntity()-method uses some database-magic to find the reference and then set it to the MainEntity.

This worked fine before Drupal 8.5 but it seems that after that the system thought it already had the reference and didn't bother to insert it to the database.


Views filter of date - complicated relative format Looking for some suggestions on how to best accomplish this. We want to set up a filter on a date field to display just content with a date within the current (or next or previous) academic year, defined as May 1-April 30.

Using the great Views between dates filter (https://www.drupal.org/project/views_between_dates_filter) we can do the filter, but the exact relative format string elludes us, and quite likely can't be achieved without writing some code.

What we have so far is a start set to "first day of may" and end set to "last day of april +1 year", but of course as soon as we hit January 1st that blows up.

Can anyone recommend a different approach or even better module that makes this happen?

There's no need for views_between_dates_filter for this use-case.  You might consider turning on the date_views module because it provides some niceties, but if you're using core date properties (like Post Date or Updated Date) then you don't even need that.  Just add 2 filters to your view:

One set to only show content where the date field is greater than or
equal to your specific desired start date (2015-05-01 00:00:00 for
instance)
One set to only show content where the date field is less
than or equal to your specific desired end date (2016-04-30 23:59:59 for
instance).

You don't need relative dates at all since you're setting up distinct views for each year.


Add class to page content output I have the following snippet in a theme's page.tpl.php:

          <?php print render($title_prefix); ?>
          <?php if ($title): ?>
<?php print $title; ?>
<?php endif; ?>
          <?php print render($title_suffix); ?>
          <?php if (!empty($tabs['#primary'])): ?>
<?php print render($tabs); ?>
<?php endif; ?>
          <?php print render($page['help']); ?>
          <?php if ($action_links): ?>
<?php print render($action_links); ?>
<?php endif; ?>
          <?php print "**59**". render($page['content'])."**88**"; ?>

The starred numbers in the last line for debugging. The output of render($page['content']) is something like the follwoing:

.....

What I need to perform is programmatically change or add class name to

You can do that in a module/theme by adding a region preprocess hook:

function MYTHEME_preprocess_region(&$vars) {
  if ($vars['region'] == 'content') {
    $vars['classes_array'][] = 'foo';
  }
}


I'm getting errors from trying to upload images from 2 different fields, server or module issue? Using Drupal 7 and Siteground hosting, when I try to upload images at registration I get this error, but randomly.

  An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (128 MB) that this server supports.

The form has 2 image fields, a multiple upload and the standard user image field. Sometimes it works, sometimes doesn't work with both fields.

What could be wrong, hosting issue or module issue?

Most of the time this is hosting issues. Review drupal and php error log to pin point exactly where the issue happens.

Sometimes the upload is successful to the temp folder but it can't move it to the files directory due to permissions ect..


Combining AND and OR in Rules I'm trying to set up a rule (using the Rules module) with AND and OR conditions.
I have a content type with a field A (date) and field B (time slot).

The rule needs to check if field A is either e.g. a Monday or a Wednesday AND if the time slot in field B is either 16:00 or 17:00 or 18:00 or 19:00 (on a Monday) OR 13:00 or 14:00 or 15:00 or 16:00 (on a Wednesday).

If it meets those criteria it has to perform an action.

I've set up my rule as shown in the screenshot, but alas whatever combination or indentation I use, it won't work ...

Who can shed some light on this? Much appreciated.

You need 2 extra ANDs, right below the highest level (1st) OR.

And EACH of the 2 ORs you already have, and the Data comparison that preceeds those ORs, you need to move them below the extra AND. So that in the end it looks like so:

OR

AND

Data Comparison (A=Maandag)

OR

Text Comparison (B=16:00)

Text Comparison (B=17:00)

Text Comparison (B=18:00)

Text Comparison (B=19:00)

AND

Data Comparison (A=Woensdag)

OR

Text Comparison (B=13:00)

Text Comparison (B=14:00)

Text Comparison (B=15:00)

Text Comparison (B=16:00)

Here is how "I" would translate the above logic:

We accept a date that is either on Monday (line 2 to 8) OR (line 1) Wednesday  (line 9 to 15).
If you want a date that is a Monday (= line 3), we insist (via the AND in line 2) that you pick a timeslot that fits for us on Monday.
To pick a timeslot for Monday, you have a choice (OR in line 4) of 4 options (ie those in line 5, 6, 7 or 8).
Similar Rules, oeps rules, apply for Wednesday, as expressed in line 9 to 15.

If after these changes your Rules Action(s) still don't get executed (because something else is wrong in any of these Rules Conditions, and/or you're not using an appropriate Rules Event), then move on to Rules debugging, as explained in "How can I display the value of a variable inside a condition?".

PS: just to make sure your "Text Comparison" condition behaves as you expect/hope it to do, create a temporary clone of your rule with only 1 Rules Condition (= 1 such text comparison), with same Rules Event and same Rules Action. That way you can either narrow down your problem, or exclude that as a possible reason why it still doesn't work.


bullet points in view I created a block-view which shows me the titles of the newest content. By default drupal simply lists the titles. I would like that the list appears with bullet points. Is this only possible to do in CSS? Is there no way to format it in the view module?

Thanks for any feedback

In the settings of your view, change the format from "Unformatted list" to "HTML list".


Alternative themed forms for a single custom content type On a site I would like a "quick entry" form for a custom content type on the front page, while also keeping the "normal" non-customized "node/add/mycontenttype" form. I'm able to customize the "normal" form by using the theme_hook function returning the proper array which points to my function that renders the form ('template' => 'some-node-form').

But ideally I would like to keep both versions of the form, rendering my customized form on the frontpage in a block, and with the normal form at the normal place "node/add/mycontenttype". I figured I could try to detect at runtime in the 'some-node-form' function if for instance it was invoked through a special path "node/add/mycontenttype/frontpage", by passing a variable or similar. I haven't quite managed to do this yet, but at least in theory it should be doable.

But do any experienced Drupal developers have better ways of accomplishing what I'm doing, things like having multiple paths pointing to different template rendering functions or similar?

My first thought (in Drupal 6) would be to use hook_form_alter to set a different #theme value in the form depending on the path.

eg

mymodule_form_alter(&$form, &$form_state, $form_id) {
 if ($form_id = 'my_form_id') {
  if ($_GET['q'] == 'somepath') {
   $form['#theme'] = 'function_one';
  } elseif ($_GET['q'] == 'someotherpath') {
    $form['#theme'] = 'function_two';
  }
 }
}


Counting the number of rows returned from db_query() with the "SELECT" statement How do I find the total number of rows returned in db_query() for the SELECT statement, or the equivalent of mysql_num_rows()?

I'm using MySQL.

If you look at the db_result() documentation for Drupal 6:

function db_result($result) {
   if ($result && mysql_num_rows($result) > 0) {
    // The mysql_fetch_row function has an optional second parameter $row
    // but that can't be used for compatibility with Oracle, DB2, etc.
    $array = mysql_fetch_row($result);
    return $array[0];
   }
   return FALSE;
}

I also saw that you could do this in Drupal 6:

$num_rows = db_result(
  db_query("SELECT COUNT(*) FROM {node} WHERE type = '%s'", $type->type)
);

It looks like you could simply do:

// Execute your query.
$result = db_query($your_query);
// Use mysql_num_rows() on the result set.
$num_rows = mysql_num_rows($result);


Safe change of field type from text to email or link I have some field types that are in text and have data and I need them to be a link or email type (ie. email module.) I realize there are several approaches:
change in D7 database.
Use the migration module.
Export as Feature and re-import.

Does someone have experience addressing this and a suggested approach?

A different approach  could be - Why try to change field type ? Why not copy old to new ?

You could possibly use something like views data export or other similar module to create a dump of your nodes as node ID and text field to csv file.

Then create your new field.

Then use feeds to import your csv and assign the old text field column to your new field. Make sure you tick the box to update nodes !

Then delete your old field.


How can I print out large variables in hook_entity_presave for debugging? I'm trying to print out the $entity variable im hook_entity_presave because I want to see all of the properties and their values at the time of saving.

The problem is that every way I have tried to print out the information, I get out of memory limit PHP errors.  My PHP settings are set to 1024M max memory.

I have tried print_r(), var_dump() and debug(), all with the same result.  I also tried dpm(), which allows the page to continue without running out of memory, but nothing gets output.

function my_module_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  debug($entity, NULL, TRUE);
}

You don't want to see all properties. That's internal data that doesn't help you much anyway. What you want to see is the field values. And the easiest way to do that is this:

debug($entity->toArray());

That gives you a simple structure of all fields and their values. You can access them in a similar way as that array looks like, e.g. $entity->field[$delta]->property, [$delta] is optional and defaults to 0. See http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet for more details.

The other way is to use an IDE with a debugger, then you can set break points, inspect anything at runtime and even execute code.


Retrieve deleted Heartbeat activity I am using D7 + Hearbeat module

Previously my heartbeat setting was when cron runs delete activities older than a month. So a cron run removed the activities.

Is there any way of retrieving the deleted heartbeat activities?

I don't think so because data was deleted from database. If u have old copy of database, then here you can do something,
Create an other database and import that old database into it.
and Fetch the required tables(means required rows and column) and dump into your current database.


Load module in a drush script I have a Drush script that I am running from my Drupal environment which loads a particular module that I want to get access to.  Particularly, I want to use one of the functions it has defined in one of it's included files.

I tried just calling the function in my script, but PHP fails with an error citing an undefined function.

I am running the script as follow:

drush php-script ~/path/to/script.php

And this is my script in its entirety right now:

<?php
    $val = biblio_get_contributor(1);

    print_r($val);
?>

biblio_get_contributor($aid) is most definitely defined in the module.

So to sum up, I need to get this module's functions loaded somehow.  Thoughts?

The biblio_get_contributor() function is located in the includes/biblio.contributes.inc file. The file isn't automatically included by the module unless it needs it, which is probably why you're getting that error.

You can include it into a page build explicitly with the following:

module_load_include('inc', 'biblio', 'includes/biblio.contributors');


add/change div wrapper around specific radio button? By default, the HTML markup for radio buttons looks like (Drupal 7):

  <input id="edit-SOME_ID" class="form-radio" type="radio" value="SOME_VALUE" name="SOME_NAME" />
  MY LABEL

I need to change/add some css classes in the outer
 OR add a wrapper
. How do I do that?

If you're defining the form yourself you can wrap an element with HTML using the #prefix and #suffix properties:

$form['radios'] = array(
  '#type' => 'radios',
  '#title' => 'Options',
  '#options' => drupal_map_assoc(1, 2, 3),
  '#prefix' => '
',
  '#suffix' => '
'
);

If you want to add a class to the existing wrapper you can do so using the #attributes property:

$form['radios'] = array(
  '#type' => 'radios',
  '#title' => 'Options',
  '#options' => drupal_map_assoc(1, 2, 3),
  '#attributes' => array(
    'class' => array('some-class')
  )
);

If you're not defining the form yourself then you can still use the same logic and implement a hook_form_alter() to change the existing form:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'some_form_id') {
    $form['some_element']['#attributes']['class'][] = 'some-class';
  }
}

Note that when using the hook_form_alter() method you should append to the existing classes array so as not to override any classes that have been set previously.


How to set up a train schedule content type in Drupal 7? I'm trying to set up a site in Drupal 7 to list train schedules.

My concept is this: create a content type to manage each train.  I'm setting up each train like an airplane flight.  Each train leaves station A at a certain time, stops at a few other stations and ends at station X.

The content type needs to be able to handle which stations it will stop at (Taxonomy terms since values will be re-used) &  what time it will stop at each station.

As I said, the station names can be Taxonomy terms but I'm having trouble with the times.  While station names can be re-used, times each train stops at each station will vary.

Is there a module that will allow me to select a taxonomy term (individual station) and then allow an additional field to be edited on-the-fly to input a time?

I'm also open to alternative suggestions for setting this up.  Thanks!

This post is pretty old at this point, so it may no longer be an issue for you, but I'll try to answer it anyway.

The type of solution I'm imagining for this is what the Double Field module sounds like it does (though I cannot be certain since I have never used it). If this module would be able to do it, you'd want a field with taxonomy with a Date field to select the stop and time of that stop (and then be able to have multiple values for this field so you can select multiple stops and their times).

Otherwise, you could use Taxonomy if the trains have set times that they arrive (like they always arrive on the hour, quarter after, etc.). Otherwise, yeah, it wouldn't be realistic to use that if they can arrive at 12:53, 3:38 - if any time is possible.


How to create an Atom RSS feed with site's content type? I have a content type named "blog" of drupal 7 website. How to create Atom RSS feed with site's blog?

You can use Views + Views Atom to create XML feeds.


$node object not populating with data I'm using the Rules module to execute custom PHP script whenever a new node is saved after importing via Feeds module.

<?php

$lid = db_insert('location')->fields(array(
    'additional' => $node->field-address, //saves as '0'
    'city' => $node->field-locality, // saves '0'
    'province' => $prov, // //saves correctly
    'country' => 'xx', //saves 'xx' correctly
    'latitude' => $node->field-latitude-temp, //saves as 0.00000
    'longitude' => $node->field-longitude-temp, //same
    'source' => 1,
    'is_primary' => 0
))->execute();

This is the location table (from the Location module) and I'm importing data from a csv file.

All the other constant values are saved properly except for when it is coming from the $node object. Lat and Lon goes 0.00000 while all the other string values such as city and address also goes 0.

Been dealing with this for hours.

EDIT: I'm using Feeds module. But I need to import also location data. While a row is getting committed to db, the values are all 0!

node:field-latitude-temp shows the actual imported value correctly when viewing the node. But it is not getting absorbed in within the PHP Execute custom code page in Rules.

I am not sure this can help you, but I don't think $node->field-address or $node->field-longitude-temp are valid syntax by $node object, you should use $node->field_address['und'][0]['value'] or with entity_metadata_wrapper function, eg:

$nodeWrapper = entity_metadata_wrapper('node', $node);
$nodeWrapper->field_address->value()