Permission to edit orders, but not delete The title is mostly self-explanatory: I need a user to have permission to edit an order, but not be allowed to delete it. I don't think the currently defined permissions for orders allow this.
Am I wrong? Is there a workaround/extra module/hackneyed solution you can think of?

Here's the proper way to do it with

hook_commerce_entity_access

  Allows modules to deny or provide access for a user to perform a
  non-view operation on an entity before any other access check occurs.

  Modules implementing this hook can return FALSE to provide a blanket
  prevention for the user to perform the requested operation on the
  specified entity. If no modules implementing this hook return FALSE
  but at least one returns TRUE, then the operation will be allowed,
  even for a user without role based permission to perform the
  operation.

  If no modules return FALSE but none return TRUE either, normal
  permission based checking will apply.

Example

/**
 * Implements hook_commerce_entity_access
 */
function MODULE_commerce_entity_access($op, $entity, $account, $entity_type) {
  if ($entity_type == 'commerce_order' && $op == 'delete') {
    // Require administer orders permission to delete orders
    if (!user_access('administer commerce_order entities', $account)) {
      return FALSE;
    }
  }
}


How do I create a redirect after using pathauto_node_update_alias() I am using the Redirect module.  I have a feature, where I have an update hook, that updates (and fixes) the path alias of the nodes on the site (after I made a change to the pathauto pattern).  I need to create a redirect, as updating the path alias does not do this for you when you use pathauto_node_update_alias().  How do I go about this.  Below is the code I have:

function uw_cfg_redirect_update_7010(&$sandbox) {
  $query = "SELECT nid FROM {node} where status = 1";

  // If this is the first pass through this update function then set some variables.
  if (!isset($sandbox['total'])) {
    $result = db_query($query);
    $sandbox['total'] = $result->rowCount();
    $sandbox['current'] = 0;
  }

  // How many nodes should be processed per pass. The higher this number is, the faster your update will
  // complete, but the more likely your server will run out of memory or timeout.
  $nodes_per_pass = 50;

  // Get the nodes to process during this pass.
  $result = db_query_range($query, $sandbox['current'], $nodes_per_pass);
  while ($row = $result->fetchAssoc()) {
    $node = node_load($row['nid']);
    pathauto_node_update_alias($node);

    // TODO: [need to add redirect code here]

    // Increment "current" by 1.
    $sandbox['current']++;
  }

  // Set the value for finished. If current == total then finished will be 1, signifying we are done.
  // If not then this function will be trigger again.  See Drupal Batch API for more details.
  $sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']);

  if ($sandbox['#finished'] === 1) {
    drupal_set_message(t('We processed @nodes nodes. DONE!!!', array('@nodes' => $sandbox['total'])));
    return t('Finish rewrite the path of all the nodes.');
  }

  return $sandbox;
}

Note:  This is not a problem if you use Global Redirect module.   This is not a problem when you resave a node, as redirect gets added.

I'd have a look at redirect_path_update and hook_path_update and maybe consider using node_save() instead of writing the paths directly.

If you're going to write them directly with pathauto_node_update_alias(), you may as well just write paths aliases and redirects directly to the database instead of wasting time node_load()ing all the nodes.


Add custom forms in checkout process in commerce kickstart In Commerce Kickstart checkout process Checkout,Review order,Payment,Checkout complete are sections. I want to add one more section like Availability. How should I add?

Use hook_form_alter to add field(s) or section on any form in drupal.

For more information go through the documentation of this hook.


How do you set up ubercart to filter/sort by price I'm new to Ubercart and just set-up a simple shop (Using Drupal 7 and Ubercart 7.x-3). In the default uc_catalog (table) view you are able to sort by product title.

When going to format -> table settings, there is an option to allow the title field to be sortable, but there is no such option for price. Is there a solution to allow the products in the table to be sorted by price?

I've tried adding a price to the sort criteria but the sort filter doesn't work.

Any help or pointer would be appreciated.

Use Ubercart advanced catalog. Very useful views. Here is a quote about it (from the module's project page):

... add custom filters on Ubercart catalog and provide taxonomy, products attributes (select) and CCK (option widget) support.
Filters are fully configurable. Product display is fully configurable with Display suite and Node display.


How do I show the "Your Cart" link in my Rules message I have a created a rule in drupal commerce.  I want to include a link to the users cart in that message, just like the link that appears when you add a product to the cart.  When I use the url token, the message displays like this: This item has been removed from http://dcomm/user/3/orders/6.

I want it to be --This item has been removed from your cart. and you click on the "your cart" and be taken to your cart view.

How do I do this?

Just add a link to

your cart

It will show the user's shopping cart.


Node reference field display I have a content type with several fields, some of them are node reference fields displaying multiple values. I've configured the display of one node reference field like teaser showing two fields "code, description".
The problem is when the node reference has more than one value, keeps adding lines to the bottom. I want to display this node reference field like "code1/code2 description1/description2" in one line.

How can I achieve this? What template should I override, field.tpl.php or node.tpl.php?

After a lot of research i finally solved my problem. I don't know if this is the best way of doing it but it works for me.

I added a THEME_field() function to my template.php of the desired field.

Inside my template function i removed the even/odd css classes because i want all in a single line.
Probably exists a better way to access field values, this was the solution i found. Digging the $item array i was able to get my code and color description values.

If someone knows a better way of doing this please help me improve it.
There goes the code i hope it helps someone else.
Don't forget to replace THEME by your theme name and the FIELDNAME.

function THEME_field__FIELDNAME($variables) {
$output = '';

// Render the label, if it's not hidden.
if (!$variables['label_hidden']) {
  $output .= '
' . $variables['label'] . ':&nbsp;
';
}

// Render the items.
$output .= '
';
$codes = "";
$colors ="";
foreach ($variables['items'] as $delta => $item) {

    $code = $item['field_color_description']['#object']->title_field['und'][0]['value'];
    $color = $item['field_color_description']['#object']->field_color_description['und'][0]['node']->title;

    $codes .= $code."/";
        //avoid repeated color descriptions
        if (strpos($colors,$color) === false)
        {
        $colors .= $color."/";
        }
     }
     $classes = 'field-item even';

     $codeAndColors = rtrim($codes,"/") . " ". rtrim($colors,"/");
     $output .= '
' . $codeAndColors . '
';
     $output .= '
';

     // Render the top-level DIV.
     $output = '
' . $output . '
';

     return $output;

}


How to limit entity and/or field translation permissions to selected languages only? Is it possible to give some user/role the permission to translate only one language?

I've seen these permissions:

Translate any entity.
Translate field content for any fieldable entity.

But these permissions allow users to translate all languages.

I have one user that has to translate to English and another user who translates to German ...

Interesting (valid!) question. But to my knowledge, and assuming this is for D7 (not D8), this is NOT possible ... yet.

Refer to (active) issue # 1829630 for more details, which also references (fixed) issue # 1807776 related to D8 (and contains a lot of interesting details ...).


problem in website viewing Fatal error: Call to undefined function omega_theme() in /home/itcom/public_html/sites/all/themes/libra/template.php on line 27

Whenever I browse my site, I get this message, and I am not able to login to the site. Clean URLs are not enabled in this site.

I would like to know how I can change the default current theme from code, and any other solution to rectify this problem.

The Libra theme is a sub-theme of the Omega theme, but seemingly the Omega theme is not present (otherwise, omega_theme() would be defined). Make sure that you have placed the Omega theme in /home/itcom/public_html/sites/all/themes/omega and try again.


Help adding multiple blogs / content areas on a page Hi how do I set 4 editable content/blogs block/nodes on a page... i'm trying to do this format http://i.imgur.com/M7Fvc.jpg

main Box 1: width 556 x length 630

right Box 1 : width 210 x length 275

right Box 2 : width 210 x length 185

right Box 3 : width 210 x length 150

also how can I edit the style/css for the blocks/nodes on this page?

You define new block regions in your theme, and structure your page.tpl.php to print the regions in the desired structure.  You should look through the theming tutorials

If that is the layout for a single page only, you might want to look into Panels, though be warned that there is a bit of a learning curve.

For styles of blocks, you can override the default CSS in your theme.  Your theme's CSS files will load after the defaults, so it will take precedence.


node:id token from panel or view I have spent 4 days looking for information on many pages without result, I would like to make a view from which to send an email with the information of a node, with view send and user view I can send emails to those I have select.

But my problem is when to send information from the title of the node, the node apparently not sent. From the panel where the view I can show the node to which I Referencing the URL node /% node / my_view, but apparently not saved when sending mail.

I've found a way to call a certain node with [aet: node: title] and [current-page: url: args: value: 1], but does not work [aet: node:% [current-page: url: args: value: 1]: title].

Any ideas?

finally I managed to send the fields I need from the node through to post in the view send php code, creating a variable to calculate the node id and then use that variable in the token

<?php
$var=token_replace('[current-page:url:args:value:1]', array('node' => $node));
?>

[aet:node:<?php echo $var; ?>:title]

This is the list of modules:

tokens,
token filter,
views send,
token tweks,
Advanced Entity Tokens,
mime mail,
mailsystem,
phpfilter


Rate module: rate icon disappears and no vote is recorded I am having a problem with the rate module. I have implemented it on node 'project' and it appears. When I click on 'thumbs up', the icon disappears. It looks like the AJAX is not working.

I was finally able to resolve this issue by enabling Clean URLs (configuration -> clean URLs).  Note, if you are prompted with a Clean URLs test that inevitably fails, you will likely need to uncomment the "RewriteBase" line in your .htaccess file.


Webform module - Contact form will not send webform emails to users with the same domain, but will send to all other email accounts I set I have a Drupal 6 site. Using the Webform module.

I have it set to send all submissions to the webform to my email address (me@gmail.com) and the clients email (tim@domain.com) - for some reason webform is not sending the email to tim@domain.com only to my email address.

I tried different variations of emails, using other email addresses associated with the clients domain i.e. sales@domain.com but none of them work. But when I use other gmail and yahoo emails, the results come through just fine.

Any ideas?

You using a shared hosting?  Could be that the recipients mail server is thinking your mails are junk if the originating mail is not coming from the resolved hostname.  This problem is common with shared hosting since they use virtual hosts.


Ubercart 3 check the stock before adding to the cart When a user enters in a quantity to add to their cart, I am trying to check that quantity against the stock level of that product, and when the stock is less than their quantity, it returns and error.  This is as far as I have gotten, and I am stuck.  Got any ideas?

function uc_check_stock_form_alter(&$form,&$form_state,$form_id) {
  if ($form_id == 'uc_product_add_to_cart_form_') {
    $form['#validate'][] = 'uc_check_stock_form_validate';
  }
  return $form;
}

function uc_check_stock_form_validate($form, &$form_state) {

  $stock = db_result(db_query("SELECT `stock` FROM `uc_product_stock` WHERE `nid` = '%d'", $form_state['values']['node']->nid));
  if (is_numeric($stock) && $stock < $form_state['values']['qty']) {
  form_set_error('qty', t('Quantity is greater than our available stock. Please adjust your quantity for the this item.'));
  }
}

Someone created a module for that already, needs some fixing IMHO, maybe you can play with that and make something better, I'll definitely be very thankful...


sharing profile2 fields multisite I have a site with 2 multi site like

abc.com
xyz.abc.com
zxy.abc.com

All sites have same drupal 7 code base. and I shared all users successfully across all portals.

my setting file for sub-site looks like this

$main_database_prefix = 'abc.com.';
$current_database = 'xyz';
$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => $current_database,
      'username' => 'xxxx',
      'password' => 'xxxx',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => array(
              'default'   => '',
              'users'     => $main_database_prefix,
              'sessions'  => $main_database_prefix,
              'role'      => $main_database_prefix,
          'role_permission'      => $main_database_prefix,
              'users_roles'   => $main_database_prefix,
              'user_ips'   => $main_database_prefix,
              'user_profile_details' => $main_database_prefix,
              'price' => $main_database_prefix,
              'transaction' => $main_database_prefix,
          'db_roles' => $main_database_prefix,
          'user_modification_history'=>$main_database_prefix,
          'authmap'=> $main_database_prefix,
          'user_industry'=>$main_database_prefix,
          'user_account_request'=>$main_database_prefix,
          'user_account_details'=>$main_database_prefix,
          'country'=>$main_database_prefix,
          'states'=>$main_database_prefix,
          'discount'=>$main_database_prefix,
          'taxname'=>$main_database_prefix,
          'price'=>$main_database_prefix,
          'transaction'=>$main_database_prefix,
          'field_data_field_subscriber_name'=>$main_database_prefix,
          'field_revision_field_subscriber_name'=>$main_database_prefix,
          'profile'=>$main_database_prefix,
          'profile_type'=>$main_database_prefix,

    )
    ),
  ),
);

all tables working properly , except

'field_data_field_subscriber_name'=>$main_database_prefix,
      'field_revision_field_subscriber_name'=>$main_database_prefix,
      'profile'=>$main_database_prefix,
      'profile_type'=>$main_database_prefix,

I can not see these fields on registration page or in backend
The only difference is these table are entity reference table.

I googled things a lot for this but no success.

Thanks in advance.

I resolved the issue by adding 2 more tables

'field_config_instance'=>$main_database_prefix,
'field_config'=>$main_database_prefix,


"Term reference" for two language versions I'm currently working on a Drupal's website for my client. We have a small issue related to new fields in "content types".

I've created a new field with field type "Term reference". We're using terms for isotpe grid, and it should work in both language versions - NL and EN.

That field only displays a single language version (default one), even when we change thhe language.

Here is an example - "field_thema[nl][8]", it supposed to be:

"field_thema[nl][8]"

and

"field_thema[en][8]"

Is there any way we could fix this?

is this a Drupal 7 or Drupal 8 question ?

in Drupal 7 you can use i18n_taxonomy submodule of i18n module.


How to create optgroups from taxonomy terms? I have taxonomy terms with parent/child hierarchies (1 level deep). On a node edit page the terms are shown in a select box where I can select multiple terms.

What I'm trying to do is convert the parent terms into optgroups so they cannot get selected and the children are nicely grouped. This post shows how to structure the form array.

Basically, the array needs to get arranged like this:

$form['field_disc_topic']['und']['#options'] = array (

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

This is the code I started with. A parent term has depth=0, children have depth=1. I can't figure out to how build the array:

$tax = taxonomy_get_tree(2);
for ($i = 0; $i < count($tax); ++$i) {
    debug( $tax[$i]->tid);
    debug($tax[$i]->name);
    debug($tax[$i]->depth);
}

Can anyone solve this? Or is there an easier way to do this?

Is this what you are looking for:
http://drupal.org/node/76500#comment-2193734

I posted the code used in the comment.  All props go to Nate Anderson from drupal.org

<?php
if (isset($form['taxonomy'][$vid])) {
  $tree = taxonomy_get_tree($vid);
  $parent = "";
  $options = array();
  foreach ($tree as $term) {
    if ($term->depth == 0) {
      $parent = $term->name;
    }
    else {
      if ($term->depth > 1) {
        $options[$parent][$term->tid] = _modulename_spaces($term->depth, '-') . ' ' . $term->name;
      }
      else {
        $options[$parent][$term->tid] = $term->name;
      }
    }
  }
  $form['taxonomy'][$vid]['#options'] = $options;
}

function _modulename_spaces($number, $char = ' ') {
  $output = '';
  for ($i = 0; $i < $number; $i++) {
    $output .= $char;
  }

  return $output;
}
?>


How to take a site offline using Drush? How can I take a site offline using Drush?

Drupal 8: drush sset system.maintenance_mode TRUE

Drupal 7: drush vset maintenance_mode 1

Drupal 6: drush vset site_offline 1


SQL Query to display taxonomy terms I am working on a Drupal 6 site and have very limited knowledge of writing sql queries.

I have a content type manage_current_university (which is a content profile) and in that use a taxonomy cck field field_host_university. I am generating a table of users who have signed for a content.

If I write this query in phpMyAdmin, I get the correct tid for that user

SELECT field_host_university_value FROM node n INNER JOIN  content_type_manage_current_university mcu ON n.nid = mcu.nid WHERE n.uid =120;

Replicating the same query inside a module:

$currentuniversity_query = db_query("SELECT field_host_university_value FROM node n INNER JOIN content_type_manage_current_university mcu ON n.nid = mcu.nid
                        WHERE n.uid =".$uid."");
while($currentuniversity_result = db_fetch_object($currentuniversity_query)){
            $currentuniversity = $currentuniversity_result->value;
print $currentuniversity; }

Where $uid fetches $user->uid of signed up users.

But the table column is blank for this one. Using similar query to fetch other profile values of the signed up user works.

Please help!

Try using db_select something like below to build the query for your above condition:

$currentuniversity_query = db_select('field_host_university_value', 'fhuv');

//query of left join with 'content_type_manage_current_university' table.
$currentuniversity_query->leftJoin('content_type_manage_current_university', 'ctmcu',
  '(fhuv.nid = ctmcu.nid)');

//query of conditions and fetching the result
$currentuniversity_query = $currentuniversity_query->condition('fhuv.uid', $uid, '=')
  ->fields('fhuv');
  ->execute();

You may have to modify a query little bit, I just provided what you can try. Also have a look at: https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_select/7

For Drupal 6 try the following:

$currentuniversity_query = db_result(db_query("SELECT mcu.field_host_university_value FROM node n INNER JOIN content_type_manage_current_university mcu ON n.nid = mcu.nid
WHERE n.uid =%d", $uid));


Change the link title of a custom view I created a view via the administration interface. This view lists content (style teaser; title and image).
The default link of titles is /node/'nid'; I want to replace the link with /custompate/'nid'.

I suppose I must "find" the template of my custom view and overwrite it in a custom module.

How can I find the name of the template for this specific view?

Edit : the "advanced" block in my view (theme information is missing :/)

One way to accomplish this would be to change the view from showing content to showing fields. You can then add the fields that you want to show, title and image.

To change the link of the title, you can add the nid as a field, hide it, and then rewrite the output of the title field to include the custom path and nid in the link.

To find the template files of the view, you need to click on the "Advanced" tab and look for "Theme: Information". You'd need a sub-theme to register the template file being overwritten. Drupal Sub-theming

To overwrite it in a module, you could use a pre render hook and modify the rows on the result fields.


hook_form_commerce_checkout_form_checkout_alter() changes are not reflecting on checkout page I am trying to make the changes in commerce_checkout_form but I am facing some issues.  Here is my hook_form_FORMID_alter :

function MYMODULE_form_commerce_checkout_form_checkout_alter($form, $form_state, $form_id){
  drupal_add_js(drupal_get_path('module','MYMODULE').'/js/checkout_validate.js');
  $form['customer_profile_shipping']['#title'] = '
Shipping Information
';
  if(isset($form['account'])){
    $form['account']['#title'] = '';
  }

  if ($form_id == 'commerce_checkout_form_checkout') {
    $form['buttons']['continue']['#validate'][] = 'MYMODULE_form_commerce_checkout_form_checkout_validate';
    dsm($form['buttons']['continue']);
    $form['buttons']['continue']['#attributes']['class'][] = 'classTest';

    if (isset($form['buttons']['continue']['#value'])) {
        $form['buttons']['continue']['#value'] = t('Continue');
    }

    // $form['buttons']['continue']['#validate'] = array_reverse($form['buttons']['continue']['#validate']); // I tried this to give preference to my validate function
    dsm($form['buttons']['continue']);
    dsm($form_state);
  }
}

function MYMODULE_form_commerce_checkout_form_checkout_validate(&$form, &$form_state){
  // This is function is not getting called.
  watchdog('MYMODULE_form_commerce_checkout_form_checkout_validate','partner ID. Response details: @request_details',array('@request_details' =>  print_r($form_state,true)), WATCHDOG_DEBUG);
}

I am getting all the dsm on page, means MYMODULE_form_commerce_checkout_form_checkout_alter is getting called but I can see that, neither 'classTest' is added to continue button nor value of continue button is changed.

This is part of dsm($form_state) :

rebuild :  (Boolean) FALSE
rebuild_info :  (Array, 0 elements)
redirect :  (NULL)
temporary :  (Array, 0 elements)
submitted :  (Boolean) FALSE
executed :  (Boolean) FALSE
programmed :  (Boolean) FALSE
programmed_bypass_access_check :  (Boolean) TRUE

$form_state['rebuild'] value is false. Is this the reason, I am not abel to see the changes?

Should it not be that the arguments are passed by reference?
You are not returning anything, therefore any changes you make within the function will have no affect outside it's scope.

function MYMODULE_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id){
....
}


How to use Docker for a drupal development site and then deploy to online provider? I am operating a Drupal website with two installations:

a development site on my local machine (dev)
a live site at my ISP offering an Apache httpd, with PHP and MySQL (live)

For dev, so far I have just installed software on my local machine (httpd,  php, mysql, drupal) and deployed updates to live by copying changed PHP files and uploading a database backup.

I am considering to use Docker for my dev installation (e.g., docker4drupal). However, due to ISP limitations for the live site I will still have to deploy updates by uploading PHP files from the webserver and database images from MySQL/MariaDB.

What is the best way to extract PHP files and DB snapshots from a docker4drupal installation (or similar Docker based set-ups)?

You're asking 2 questions in the post: a general one (title) & a platform specific one (body), which is off-topic here (we don't write tutorials for Drupal platform integration). I'll answer the general which is useful at-large.

Most of the docker-based Drupal dev tools have decent feature sets. Each tool has one-or-two features that make it uniquely standout for a particular use scenario. You have to judge a dev-tool on who's maintaining, why are doing it, what are its supported features/platforms, how long it's been in development.

Theoretically, everything being Dockerized means you build/test locally and can deploy anywhere that does Docker hosting. In practice, to get from point A to point B, you'll have to figure how what your host platform provides technically (e.g. IaaS vs PaaS, CI tools, etc.) to what you have for your dev setup is (e.g. Dockerized toolchains, source code host, etc.) and match it up to see if all the pieces fit.

You can decide provider or docker-based dev-tools first, but a choice of one is going to impact the other in some way. You basically have to go a through a matrix of:

What the Docker dev-tool provides
What features you want (for platform/dev-tools)
What the platform provides (for integration)

Then the "best" is whatever matches lines up most in your matrix (or tensor since we're talking 3 attributes here). There's a lot of details along the way. You have to do a lot research to fill in the details that work best work for your project.


View nodes in a listing only, not on their own? I have created two node-types: 'match' and 'set'. When a 'match' node is viewed it displays a listing of several 'set' nodes. I've acheived this by calling node_load_multiple in hook_node_view. That's all 'set' nodes do: they are listed by a match node. 'Set' nodes can be created, edited and deleted, but I only want the user to be able to view them in listings.

So, I want to deny access to viewing 'set' nodes on their own page at node/1 or whatever. I've denied access to 'set' nodes using the node access mechanism, but then they don't appear in my listing either.

How can I set these nodes so that they can only be viewed in my listing?

The only thing I can think of is not to call node_load_multiple but to write by own db_select query to retrieve all the necessary 'set' nodes to list in a match 'node': a bit messy.

Hope this makes sense. I open to any suggestions. Thanks.

I believe you could use the node_view hook.  In that hook you can check for the node type (set) and view mode (full) and add your logic.  If you're using a reference field to relate the set to the match then you could probably redirect the user back to the match.

When you're listing sets on the match page you could also not render them as links a user doesn't try to view the set directly.


How do I add a webform to my Event content type View I'm using the Date module to create custom Event content types.  I'm using Webform to create registration forms for each event.  I've created a View that displays events in a table based on start date/end date.  I would like to add a link to the corresponding webform to the event in the View. Is there a way to do that? (Using D7 with all modules updated.) I thought I would need a relationship, but the webform is not available.

Could you use a node reference field on the event?

Example:

Create your registration webform and save it.
Create your Event node, and in the node reference field select the Webform that will book your event.
In your table view you should be able to link to this referenced node.


Why does the Path Breadcrumb module change URLs? I have a multilanguage site. I had a link to node/drupal_get_path_alias('node/15') and works perfectly identifying the language of the site, so it gets the correct path ("products" for english, "productos" for spanish). I have installed Path Breadcrumb, tried to configure, and to my surprise, the link which previously worked is rewritten to the incorrect language, instead of "/productos" is "/products". The link is in the main HTML, in the preprocess_page. Why does Path Breadcrumb rewrites a path instead of just creating the breadcrumb? I uninstall the module and all works as intended again.

It was completely my fault. Path Breadcrumb works perfectly. The problem is that I had a path alias which instead of being English, it was All languages, and so the module didn't know what link to choose. I hadn't noticed the error before installing the module, and somehow the module installation made the error to be detectable.


Unknown directories /pipermail /poll accessible in Drupal 7 My Drupal 7 install, has the Simplenews and Polls modules enabled, but Simplenews is set to subscribe registered members only, and Polls are only open to authenticated users. Yet, the mysite.com/pipermail and mysite.com/poll directories are accessible to anonymous view.

The mysite.com/poll directory returns a page with the Drupal theme only, and the word "Polls" in the page title, and no other data. The mysite.com/pipermail directory returns a blank page, absolutely no data.

These directories are not seen anywhere in the directory tree when I checked using File Manager in cPanel. This is a CentOS 5.10, php 5.4 install. How does one check Drupal's internal directory tree, especially to verify whether the permissions are correctly set on these unknown directories?

How do I remove these problematic directories? Also, is it possible that this flaw can be maliciously attacked, say by ftp upload means, etc.?

Drupal is a Dynamic Content Management system unlike old style files and directories where you find path specific directory.. Various features are available from modules in Drupal... Modules implements menu paths using hook_menu...

For your case, module exposes permissions settings which you can set in "admin/people/permissions" for different roles... Login as admin and access above page to set access permissions..


CCK select list and default values from array without writing custom module For my CCK select list options, I did:

//just making up firstName field to simplify example
$sql = "SELECT uid,firstName FROM users";
db_query($sql);
while($row = db_fetch_object($result)) {
  $uids[$row->uid] = $row->firstName;
}
return $uids;

This returns something like:

'1' => 'joe'
'2' => 'bob'
'3' => 'sarah'

Now in CCK, how do I programmatically set the the logged in user's id to be the default selected from the select list?  Furthermore, CCK's example of a default return value makes no sense to me:

return array(
  0 => array('value' => value for value),
  // You'll usually want to stop here. Provide more values
  // if you want your 'default value' to be multi-valued:
  1 => array('value' => value for value),
  2 => ...
);

I know I can do this with hook_form_alter, but I am trying this WITHOUT writing any custom module so I can learn CCK and make it easy for my future devs.

How about this:

global $user;
return array(
  0 => array( 'value' => $user->uid )
);


What are some design patterns found in prominent contributed modules? Besides Presentation-abstraction-control and other patterns that are used in Drupal core, are there any other design patterns prominently used in the more popular contributed modules such as Views, CCK, and Features?

One place to start is with core itself and the patterns exposed to contrib. - a great write-up by Larry Garfield (Crell) can be found in a Drupal Watchdog article.

  Observers, visitors, and peeping toms

  Drupal is actually built on the twin patterns of Observer and Visitor, although it doesn't call them by name. Instead, it calls them hooks. hook_node_load(), hook_user_login(), and so forth are, in essence, observers on nodes and users. hook_form_alter(), hook_node_view(), and so forth are, in essence, visitors. Because Drupal does not differentiate between the two, some hooks could arguably be considered both patterns but the principle is the same.

  Factories and commands

  There are several variations on the Factory pattern, but they all boil down to the same idea: One object, a client, asks another object, a factory, for an appropriate implementation of a piece of logic, but doesn't care which it is. That's up to the factory to decide. Consider the db_insert() function, the important bits of which are show below:

   function db_insert($table, array $options = array()) {
       // ...
       return Database::getConnection($options['target'])->insert($table, $options);
     }

  The Database::getConnection() method is a factory that returns a connection object appropriate for this site.

  Doctor Drupal's Dependency Injection

  In Drupal 6, the menu system was gutted and rewritten to be a multi-step process. We would now implement the same page callback like this:

   function example_menu() {
       $items['node/%node/example'] = array(
         'page callback' => 'example_page',
         'page arguments' => array(1),
         // ...
       );
       return $items;
     }

     function example_page($node) {
       // Do useful stuff here.
     }

  In this new setup the menu router gets more complex. In return, however, the page callback gets the node on which it depends passed to it, that is, injected into it. That gives us a number of benefits.

  Go for Broke(r)

  One common approach is some variation on the idea of a Broker or Mediator. In this design, an object doesn't request information from another object directly. Instead it asks an intermediary object, which may have been injected into it, to make such a request on its behalf. While it still means the first object has to actively request information, it is only tightly coupled to the mediator object and not to the myriad of other objects it may need to request information from. That means if those other systems change we need only update the mediator, not every system that touches it.


Displaying page execution time using devel How is it possible to use devel module to show Page execution time on a site? I enebled it and it shows numbers only on admin pages.
Thank you for help.

Enabling the 'Display page timer' in the Devel settings should be enough to add it to every page. You could check:

That you are logged in as an administrator when viewing the pages and that you have got all the Devel permissions assigned (People > Permission).
Have a look at the source of your site, Devel appends the time to the very end of the page, after the closing HTML tag. It might be hidden by your browser or theme.

Otherwise have a look at your recent log messages (under reports) or your server error logs to see if something is going wrong.


Query takes nearly 6 secs. Is it ok? I switched on Devel logging on site (shop on Drupal Commerce), went to Shop->Orders and saw that

3818.231 views_plugin_query_default::execute P A E
SELECT commerce_order.order_id AS order_id, commerce_order.order_number AS commerce_order_order_number, commerce_order.uid AS commerce_order_uid, commerce_order.created AS commerce_order_created, users_commerce_order.name AS users_commerce_order_name, users_commerce_order.uid AS users_commerce_order_uid, commerce_order.status AS commerce_order_status, 'commerce_order' AS field_data_commerce_order_total_commerce_order_entity_type FROM commerce_order commerce_order LEFT JOIN users users_commerce_order ON commerce_order.uid = users_commerce_order.uid LEFT JOIN recently_read recently_read_commerce_order ON commerce_order.order_id = recently_read_commerce_order.entity_id LEFT JOIN commerce_payment_transaction commerce_payment_transaction_commerce_order ON commerce_order.order_id = commerce_payment_transaction_commerce_order.order_id WHERE (( (commerce_order.status NOT IN (:db_condition_placeholder_0, :db_condition_placeholder_1, :db_condition_placeholder_2, :db_condition_placeholder_3, :db_condition_placeholder_4, :db_condition_placeholder_5)) )) ORDER BY commerce_order_created DESC LIMIT 100 OFFSET 0
default

2422.621 views_plugin_pager::execute_count_query P A E
SELECT COUNT(*) AS expression FROM (SELECT 1 AS expression FROM commerce_order commerce_order LEFT JOIN users users_commerce_order ON commerce_order.uid = users_commerce_order.uid LEFT JOIN recently_read recently_read_commerce_order ON commerce_order.order_id = recently_read_commerce_order.entity_id LEFT JOIN commerce_payment_transaction commerce_payment_transaction_commerce_order ON commerce_order.order_id = commerce_payment_transaction_commerce_order.order_id WHERE (( (commerce_order.status NOT IN (:db_condition_placeholder_0, :db_condition_placeholder_1, :db_condition_placeholder_2, :db_condition_placeholder_3, :db_condition_placeholder_4, :db_condition_placeholder_5)) ))) subquery

Is it normal that on site with 3000 items and 7000 orders it takes so much time to form orders view in admin interface?

Site is hosted on server, Xeon E5-2609x2 (2.4 Ghz), 16 Gb DDR-3 memory

Just looking at the query, the obvious culprit is the recently_read module. The join that is added to the query is fully unindexed:

LEFT JOIN recently_read recently_read_commerce_order ON commerce_order.order_id = recently_read_commerce_order.entity_id

The query doesn't really make sense, so I assume the Views integration for this module needs work.


Use Regex to insert jQuery querystring before a url anchor On my page I have some content links that start with '/example/'.  I'm using jquery to add a querystring to these links, which is the parent of the currently viewed node.  So, the code looks like this:

//add parent querystring to subpages
$('a[href^="/example/"]').each(function(index, element) {
  var parentAttr = $(this).attr('href') + '?parent=' + Drupal.settings.nodeinfo.nid;
  $(this).attr('href', parentAttr);
});

This works great with one big exception.  Some of the links look like this (note the anchor at the end):

http://mysite.com/example/subpage#anchor-name

So, with my jquery, the resulting link looks like this:

http://mysite.com/example/subpage#anchor-name?parent=123

When the url is structured this way, the anchor part doesn't actually work (it doesn't jump the user to that section of the page).  The querystring actually needs to inject itself between the full url and the anchor.  This format is what's needed:

http://mysite.com/example/subpage?parent=123#anchor-name

How can I modify my code to inject the querystring before the anchor in the url if there is one?  I'm assuming it has to be regexed somehow?

Rather than writing your own solution you could just a solution that's already tried and tested, like the parse_url() function on phpjs.

It works exactly the same way as PHP's parse_url() so you can use it to extract all elements of the url, alter what you need, then build it up again.

For example calling the function like this:

var components = parse_url('http://username:password@hostname/path?arg=value#anchor');

Will yield the following result:

{
  scheme: 'http',
  host: 'hostname',
  user: 'username',
  pass: 'password',
  path: '/path',
  query: 'arg=value',
  fragment: 'anchor'
}

From there it'll be easy to manipulate the values you're interested in and build up a new URL, without having to resort to a another regex.

Basic example:

$('a[href^="/example/"]').each(function(index, element) {
  var components = parse_url($(this).attr('href'));

  var newUrl = components.scheme + '://' + components.hostname + '/' + components.path + '?parent=' + Drupal.settings.nodeinfo.nid + '#' + components.anchor;

  $(this).attr('href', newUrl);
});


Loop trough items in view template and access field values? Drupal 8
name of twig: views-view-grid--places.html

I'm extremely new to Drupal so bare with me and excuse any incorrect lingo.

I created a content type called places and added 2 fields (body and field_location). title is a default for fields.

In my view twig, how do I get those values in my for loop?

{% for item in items %}

{{ item.title }}

{{ item.field_location }}

{{ item.content }}

{% endfor %}

This only outputs the body. What am I missing?

Use {{ dump(item) }} to see the structure.

Once you have the structure you can reference in a faily regular way: if a sub-item is an array or an object, then it's a dot, if an array with a #, reference as an array eg xxx.yyy['#zzz']


How can I prevent a user from logging in from more than one computer or browser? In the Drupal 7 web site I am developing, I have a requirement that will not allow a user to login from multiple computers or different browser (IE and FireFox) on the same computer.  It looks like the Session limit module used to handle this, but I don't see where it is even under development for Drupal 7.  Do you have any idea?

If you look into the modules issue queue, you would see that there is already a very active port underway. You could help to get it to a solid release by testing it out.

See Issue #1047132: Session Limit version for D7


One Drupal site affecting another cloned site I have a weird situation with cloned site, I have copied the entire content from a production server, and made a different directory for testing environment. The steps I did to clone a site is:

Copied all the contents from the main folder /www/d7/ to new folder
/www/test/
Made a separate server config in nginx to browse the content from browser
Original site can be browsed via http://d7.example.com and the copied site can be browsed via http://test.example.com, the nginx have separate logs for both
Dumped the original database after flushing drupal cache, created new database called 'test', with new username 'test' and new password 'test', imported the dumped database to new database 'test'.
Changed the database connection parameter in the file /www/test/sites/default/settings.php to accumulate newly created database.

Now, when I put the production site in offline mode, the test site also goes to offline mode, how come this is possible ? The most weird thing is if I put the site to online mode from test site, the production site also goes to online mode. I even tried creating new database, new database user and changing the settings.php still same issue.

I tried installing different modules to different sites, and the installed modules shows in their respective sites.

Can anyone tell me what's going on here ?

Update with Answer:

As Clive commented below, I changed the memcached_storage settings in settings.php file to $conf['memcache_storage_key_prefix'] = 'test_site'; and I don't have any issues now.

As beth, said in the comment, I am answering this, even after updating the question with answer.

The culprit was Memcached bin, since I am using memcahce_storage module for memcached, the bins of the main site and test site were same, hence, creating this confusion.

I edited the settings.php page of test site and changed the prefix for memcached for test-site as $conf['memcache_storage_key_prefix'] = 'test_site';, now everything is perfect !!!


How do I update a node via a custom form? I have built a custom form (in a module) that creates several related nodes in the database when submitted. Now, I need to create a module so that a user can update his/her submitted form data at a later date. Here's my rough plan:

(1) Determine the nodes that the user wants to update via a wildcard in a requested url;
(2) retrieve the required data from the database;
(3) build a form and insert the retrieved database values via the #value property;
(4) bulid a submit function that uses db_update to update the node

Is this the right approach for updating a node via a custom form? Here's my (not working) module code so far:

// Implements hook_menu().
function update_card_menu() {
    $items['update-card/%update_card'] = array(
        'page callback' => 'update_card_form',
        'page arguments' => array(1),
        'access callback' => TRUE,
    );
    return $items;
}

// Database query function.
function update_card_load($nid) {
    $query = db_select('node', 'n');
    $query -> condition('nid', $nid);
    $query -> join('card_number', 'cn', 'n.nid = cn.entity_id');
    $nodes = $query
    -> fields('n', array('nid', 'title'))
    -> fields('cn', array('field_card_name_nid'))
    // This query will get more complex - I need more nodes and more fields
    -> execute();
    foreach ($nodes as $field) {
        $card['nid'] = $field -> nid;
        $card['card number'] = $field -> field_card_number_nid;
    }
    return $card;
}

$card now contains some values I want to populate my update form:

Array ( [nid] => 123 [card number] => 456 )

But how do I get $card into my form builder function, so that I can populate my #value properties from this array? My code does not work.

/**
 * Renderable form array return function.
 */
function update_card_form() {
    return drupal_render(drupal_get_form('update_card_capture'));
}

/**
 * Form builder function.
 */
function update_card_capture($form, &$form_state, $card) {
    $form['nid'] = array(
        '#title' => t('nid'),
        '#type' => 'textfield',
        '#value' => $card->nid
    );
        $form['card number'] = array(
        '#title' => t('Card number'),
        '#type' => 'textfield',
        '#value' => $card->card_number
    );
}

You need to use hook_menu() to register the path and callback function, like so:

<?php
function hook_menu() {
  $items['some-path/%node'] = array( // %node will use the node_load() function that's already provided by node.module.
    'type' => MENU_CALLBACK // This is just a callback item, it will not appear in any "menus"
    'page callback' => 'drupal_get_form'
    'page arguments' => array('the_form_function_name', 1) // Where 1 = the %node wildcard
    'access callback' => 'node_access',
    'access arguments' => array('update', 1), // The user must be able to update the node
  );
  return $items;
}
?>

Then build a simple form that provides fields to alter on the node, and run node_save() in the submit handler to save any modifications you make to the node.

<?php
function the_form_function_name($form, &$form_state, $node) {
  drupal_set_title('Now editing node ' . check_plain($node->title));

  // Just store the entire $node object in a custom form property. Easy.
  $form['#node'] = $node;

  // An example form field that we'll use to update the node's title.
  $form['new_title'] = array(
    '#title' => 'Title',
    '#type' => 'textfield',
    '#default_value' => $node->title,
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save Node',
  );

  return $form;
}

function the_form_function_name_submit(&$form, &$form_state) {
  $form['#node']->title = $form_state['values']['new_title'];
  // Save the modified node object (http://api.drupal.org/node_save)
  if (node_save($form['#node'])) {
    drupal_set_message('Updated the node.');
  } else {
    drupal_set_message('Could not update the node.', 'error');
  }
}
?>

This is just sample code – I have not tested, but it should work barring any typos.

You would hit this via: http://example.com/some-path/123 where 123 is the node ID of the node you want to edit.


how to modify field of a node? I have a custom text field which I use to display some voucher code to users.
I have it in a custom content type named (machine name) : 'add_deal'.

What I want to do is to style the field when the node is displayed and add a link/button next to that field to copy the text in that field.

I created a field--field-type--cotent-type.tpl.php file, but how do I use it, and I dont think its working for me either. Is there any hook function I need to use to make use of that tpl file?

How could I achieve it?

I think you have to use your field name instead of field type in the name of your .tpl.php file. Assuming the label of your field is 'Voucher code', then the machine name of this field would normally be field_voucher_code and your template file should be named field--field-voucher-code--add-deal.tpl.php See theme_field documentation for more details.

Don't forget to clear the caches (i.e., rebuild the theme registry) after creating this file in your (custom) theme.


How to grant a role permission to edit terms in a specific vocabulary Is there a way/module to grant a role permission to list and edit terms in a specific vocabulary?

The only module I can think of is the Taxonomy access fix module, which has only a version for Drupal 7.

  This module

  adds 1 permission per vocabulary: "add terms in X"
  changes the way vocabulary specific permissions are handled
  changes the Taxonomy admin pages' access checks
  alters the vocabularies overview table to show only what you have access to edit or delete

  The module does what native Taxonomy lacks: more specific Taxonomy permissions (and checking them correctly).


Override field twig template in views I am trying to override the field rendered in a view. The field name is: this_is_field

I copied the /core/modules/views/views-view-field.html.twig and placed it my theme folder.

I renamed with both methods below

views-view-field--this-is-field.html.twig
views-view-field--display-name--block-name--this-is-field.html.twig

I have turned on Twig debugging and still the copied template isn't working.

Am I renaming wrong?

It needs to be:

views-view-field--[field-machine-name].html.twig

If you look in Manage Fields, your field machine name is probably field_this_is_field.

Therefore, in your case:

views-view-field--field-this-is-field.html

Note that this is will override for all views that have this field, if you want to only target a specific view use:

views-view-field--[view-machine-name]--[field-machine-name].html.twig


Edit search form with a module I have made and installed a new module, called searchIcon.
The problem is I want to edit the default value "Search" next to the search form.
I tried the code below, but it does not seem to work.
<?php

/*
 * Implementation of hook_form_alter()
 */

function searchIcon_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'search_block_form') {
        $form['actions']['submit']['#value']= 'TESTSEARCH';
    }
}

?>

How could I change the text "search" to e.g. "TESTSEARCH"?

Okay, I think there must have been a typo somewhere or something, but anyway, this setup works:
info yaml:
name: Search Icon
description: This module replaces search value by an icon.

type: module
core: 8.x
core_version_requirement: ^8 || ^9

module:
<?php

/*
 * Implementation of hook_form_alter()
 */

function searchIcon_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'search_block_form') {
        $form['actions']['submit']['#value']= 'TESTSEARCH';
    }
}

Please note that the module does not work as intended yet, the value should be replaced by an html decimal code for the desired icon.


How to sum two fields I have a content type with the field_watermelons and field_apples fields. I want to record the sum of these fields in the (existing) field_total_fruits field. How can I achieve this?

I do not want to use the Computed field module(because of PHP filter requirement) and the Math Field module is also out because it can't handle Field Collections at the moment (if it could, then I'd have my answer).

I tried hook_form_alter with a callback function attached to the $form['submit']. In that callback, I've tried a number of methods of inserting new values including adding values to $form_state's input, values, completed_form. I've also tried to use entity_metadata_wrapper() approaches in the callback, to no avail. I also tried form_set_value().

How to create a Rules action set to calculate a sum of integers in a Field Collection? looks interesting, but there's no answer.

Surely I'm over-thinking this. Can someone tell me if there's a simple way to sum two field values and insert that sum into the value of another field programmatically?

I suppose I could use the Drupal AJAX system too. I just didn't want that hassle, thinking that there's an easier way, but perhaps it's the best option.

Ok, I've got a solution that will work for me. This d.o forum comment was very helpful.

Instead of changing the $form['submit'] array, prepend the callback to the submit callback stack! Like so:

array_unshift($form['actions']['submit']['#submit'], 'MODULE_my_custom_submit_handler');

Note that the code in the comment from d.o is a bit off, you don't need to assign the unshift'ed array, you just run array_unshift on the array itself.

Once that's added in your hook_form_alter you can do WHATEVER processing magic you want with form_set_value(). Cool! Thanks all.

EDIT: here's what the callback looks like. Also note that for some reason someone took out my fields in my original question. But these field names would make more sense if someone didn't do that.

function MODULE_my_custom_submit_handler($form, &$form_state) {
  $lang = $form['language']['#value'];

  $a = $form_state['values']['field_fruit_collection'][$lang][0]['field_watermelon']['und'][0]['value'];
  $b = $form_state['values']['field_fruit_collection'][$lang][0]['field_apples']['und'][0]['value'];

  $sum = $a + $b;
  form_set_value($form['field_total_fruit'][$lang][0]['value'], $sum, $form_state);
}


Taxonomy Menu: Display Descendants does not work I could not find any good answer to this question online, so I decided to post
  it with the answer I found as it might help some people, I hope so :)

I am using Drupal 7.

In taxonomy menu 1.4 module, if you check option "Display Descendant" , nothing change in your menu.

In taxonomy menu 2.0alpha2 module, if you select the similar option: "Menu path type => Multiple terms" , the items in your menu that have descendants vanish from your menu

How to get this to work ?

With taxonomy menu 2.0alpha2 if you select multiple you'll see the warning : "Multi-terms path is not available in Drupal by default, which means that you will have to register it using a module like Views for example."

Luckily views provide by default a taxonomy term view to emulate drupal default taxonomy term handling, so you need to activate it.
But even with this view activated you wont see your menu items, and this is because the path generated by taxonomy menu(ie: taxonomy/term/tid1+tid2 ) is still not handled.

This is because default taxonomy term view handle multiple terms ids argument but does not validate them (WTF !?).

So what you need to do in a nutshell:

  In taxonomy menu 2.0alpha2 module, select "Menu path type => Multiple terms"
  Activate taxonomy term view
  In [ Contextual filters =>  Content: Has taxonomy term ID (with depth) => Specify validation criteria => Filter value type ] change to "term IDs separated by , or +"

There you go !

ps : I did not try this with taxonomy menu 1.4, anyone ?


Broken URL on node teaser code Fankly this is a silly question.

I want to print node teaser in a block.

As discussed here: How to programmatically render a node's teaser using the theme layer? I've used this code to get the html code of teaser:

 $node = node_load($nid);
 $rendered_teaser = drupal_render(node_view($node, 'teaser'));
 //now print this teaser in block using PHP filter.

But the problem is that this contains a logo whose img src value is

  http: //default/sites/default/files/styles/small-logo-image/public/ddn-job/iitblogo-1395397403j.jpg?itok=ZhTVC9Ee

Also internal URL's are linked as http:// localhost/node/1 which should have been http:// localhost/mysite/node/1

What is the problem? I've also tried running it through check_markup($rendered_teaser,'full_html')

About this problem :

  Also internal URL's are linked as http:// localhost/node/1 which should have been http:// localhost/mysite/node/1

The solution lies in the .htaccess file, at the root of your site : locate the line with RewriteBase, uncomment it if needed, and set it to : RewriteBase /mysite/


How to remove specific meta-tag from header section of page? How to remove specific meta-tag from header section of page ?

I am trying to remove

<link rel="delete-form-edit" href="/node/11/delete" />

tag from header section of the page ,but no luck.

As there is no tag as shown above  found on html.html.twig file header section ,its automatically generating.

I think you need hook_page_attachments_alter, which Alter attachments (typically assets) to a page before it is rendered.

 /**
 * Implements hook_page_attachments_alter().
 * @param array $attachments
 */
function my_module_page_attachments_alter(array &$attachments) {
  if (!isset($attachments['#attached']['html_head_link'])) {
    return;
  }
  $unset_html_head_link = [
    'canonical',
    'shortlink',
    'delete-form',
    'edit-form',
    'version-history',
    'revision',
  ];
  foreach ($attachments['#attached']['html_head_link'] as $key => $value) {
    if (isset($value[0]['rel']) && in_array($value[0]['rel'], $unset_html_head_link)) {
      unset($attachments['#attached']['html_head_link'][$key]);
    }
  }
}

/**
 * Implements hook_module_implements_alter().
 */
function my_module_module_implements_alter(&$implementations, $hook) {
  if ($hook === 'page_attachments_alter') {
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}

excerpt from : How to unset link rel: shortlink, edit-form, version-history and revision from ?


In multisite environment can you have a default site? I am wondering if multisite Drupal allows you to have a default site too. Something like sites/default/settings.php and sites/mysite/settings.php along with the proper sites.php. If yes then what should sites.php look like?

For sure you can have a default site to use i case if the requested site was not available some reason the default site will be open to user. to do that you need to setup the default site setting under sites/default/setting.php

lets assume we have 3 website

mysite1.com
mysite1.com
mysite3.com
defultsite.com

In that case your file structure needs to be :

/sites/mysite1.com folder which will have setting.php file for mysite1
/sites/mysite2.com folder which will have setting.php file for mysite2
/sites/mysite3.com folder which will have setting.php file for mysite3
/sites/default folder which will have setting.php file for default site

You need to setup your .htaccess file in your root of server to point every Domain to the main drupal folder. to learn more about .htaccess please read here.

No to test if your default site is working simply rename mysite1.com folder to xxxxx and now try to access your mysite1.com using any browser it shoud take you to default site because mysite1.come folder cant be found anymore.


Use taxonomy_get_tree() to extract term names? I'm using the handy taxonomy_get_tree() function to, hopefully, just extract the list of term names within a vocabulary. Sounds simple enough, but I'm stumped. Running the following:

$tree = taxonomy_get_tree(2);
print_r($tree);

yields the following:

      Array
(
    [0] => stdClass Object
        (
            [tid] => 1
            [vid] => 2
            [name] => The First Term
            [description] =>
            [weight] => 0
            [guid] =>
            [depth] => 0
            [parents] => Array
                (
                    [0] => 0
                )

        )

    [1] => stdClass Object
        (
            [tid] => 2
            [vid] => 2
            [name] => The Second Term
            [description] =>
            [weight] => 1
            [guid] =>
            [depth] => 0
            [parents] => Array
                (
                    [0] => 0
                )

        )

)

Now all I want to do is pull out each of the name values. So I tried the following:

foreach($tree as $value){
    print($value['name']);
}

I'm returning a server error. I suspect it has something to do with that pesky stdClass Object thing.

So any ideas how I can extract just the names?

Nevermind... this works:

foreach($tree as $value){
    print($value->name);
}

Thankfully, it looks like I'm not the only idiot out there. Sigh...


OAuth token parameter missing when configuring Google Analytics Reports I'm displaying Google Analytics reports at my site using Google Analytics Reports module which uses Oauth.

At the localhost on my computer it works fine.

But on a site my.example.com it is showing "OAuth token parameter missing" when I go to "admin/config/system/google-analytics-reports" and press "Start setup and authorize account".

I see this error in the watchdog:

  Code: 401 - Error: Unauthorized - Message:
  GDataauthErrorAuthorizationInvalid Credentials

If I migrate my site from localhost to this site then also it works fine until I clear my cache.

The Linux server running my.example.com which was giving problem had time lag of 45 minutes. The moment I corrected it .. it worked.


Unset search after leaving page In my drupal admin content page when I search for something it keeps displaying the searched items.

Even when I leave the page and go back it is still displaying items from the search querie

When I press the Clear button the results are normal again. How can I fix this when I leave the content page that it automatically clears the search results?

Thanks in advance!

If you are using Admin Views you can edit the view and change the exposed filters and uncheck "remember the last selection".

A screenshot to illustrate this for the content:title field:


How add a css id selector to a views row I need to add a css id selector to a views row. Of course this is straight forward with a class selector such as .my-class but how do I insert something like #my-class at the individual row level?

I realize that this probably invalid CSS; however, the ID appears to be needed to trigger some JavaScript.

Some background: I want to use a component from the Bourbon Refills CSS  framework for a 'fade in' effect and apply this to all the rows in a views. See http://refills.bourbon.io/components/#fade-in.

In order the make this work I need to add a CSS ID #js-fadeInElement to each row.

Note

After a bit more digging, it seems I may need a custom row.tpl file in my theme. Is this correct?

Solution 1:

No need to add ID for each row, you can achieve it by each row CSS class it self. Instead of document.getElementById("js-fadeInElement"); you can use document.getElementsByClassName("js-fadeInElement");

Solution 2:

You can use Views theme templates to modify the HTML output and add your id attribute.
Under the Advanced section, you will find Theme: information.

  This link will show you possible file name for templates and a sample
  content of that file.

You probably want to copy and modify the "Style output". You can put your custom template in your own theme directory. You probably want a name like views-view-list--your-view--page.tpl.php

Please follow this link to override the template.


Language switcher with country code and title For my responsive site i try to override the language switcher block to get both, the long title of the country and the short code. So I can change the display for smartphone or desktop.

I dont know whats the best solution, print a second block or gives out an array with 2 links in a list element. These code overrides only the title.

   function mytheme_links__locale_block(&$vars) {
      foreach($vars['links'] as $language => $langInfo) {
        $vars['links'][$language]['title'] = $vars['links'][$language]['language']->language;
      }
      $content = theme_links($vars);
      return $content;
}

You have to copy and paste the entire theme_links function and rename it like
you did mytheme_links__locale_block

function theme_links__locale_block($vars) {
  $links = $vars['links'];
  $attributes = $vars['attributes'];
  $heading = $vars['heading'];
  global $language_url;
  $output = '';

  if (count($links) > 0) {
    // Treat the heading first if it is present to prepend it to the
    // list of links.
    if (!empty($heading)) {
      if (is_string($heading)) {
        // Prepare the array that will be used when the passed heading
        // is a string.
        $heading = array(
          'text' => $heading,
          // Set the default level of the heading.
          'level' => 'h2',
        );
      }
      $output .= '<' . $heading['level'];
      if (!empty($heading['class'])) {
        $output .= drupal_attributes(array('class' => $heading['class']));
      }
      $output .= '>' . check_plain($heading['text']) . '</' . $heading['level'] . '>';
    }

    $output .= '
';

    $num_links = count($links);
    $i = 1;

    foreach ($links as $key => $link) {
      $class = array($key);

      // Add first, last and active classes to the list of links to help out themers.
      if ($i == 1) {
        $class[] = 'first';
      }
      if ($i == $num_links) {
        $class[] = 'last';
      }
      if (isset($link['href']) && ($link['href'] == $_GET['q'] || ($link['href'] == '<front>' && drupal_is_front_page()))
         && (empty($link['language']) || $link['language']->language == $language_url->language)) {
        $class[] = 'active';
      }
      $output .= '
 $class)) . '>';

      if (isset($link['href'])) {
        // Pass in $link as $options, they share the same keys.
        $output .= '
';
        // This will give the native name of the lang like 'Français'
        $output .= l($link['language']->native, $link['href'], $link);
        // This will give the name of the lang like 'French' if the website is in English
        // $output .= l($link['language']->name, $link['href'], $link);
        $output .= '
';
        $output .= '
';
        $output .= l($link['title'], $link['href'], $link);
        $output .= '
';
      }
      elseif (!empty($link['title'])) {
        // Some links are actually not links, but we wrap these in  for adding title and class attributes.
        if (empty($link['html'])) {
          $link['title'] = check_plain($link['title']);
        }
        $span_attributes = '';
        if (isset($link['attributes'])) {
          $span_attributes = drupal_attributes($link['attributes']);
        }
        $output .= '
';
        // This will give the native name of the lang like 'Français'
        $output .= '' . $link['language']->native . '';
        // This will give the name of the lang like 'French' if the website is in English
        // $output .= '' . $link['language']->name . '';
        $output .= '
';
        $output .= '
';
        $output .= '' . $link['title'] . '';
        $output .= '
';
      }

      $i++;
      $output .= "
\n";
    }

    $output .= '
';
  }

  return $output;
}

Inside the code you will find the version for mobile and desktop with class added.

    $output .= '
';
    // This will give the native name of the lang like 'Français'
    $output .= l($link['language']->native, $link['href'], $link);
    // This will give the name of the lang like 'French' if the website is in English
    // $output .= l($link['language']->name, $link['href'], $link);
    $output .= '
';
    $output .= '
';
    $output .= l($link['language']->language, $link['href'], $link);
    $output .= '
';

Then you'll have to hide the link (display:none;) in CSS depending on the resolution of you screen (with media queries)


Region not rendering on views page but works perfectly on regular pages! I have a navigation_bar region set up in my .info file which renders perfectly on regular drupal pages but I have two pages which are made from Views, but nothing renders. I am using the superfish module to display my menu block which is in the navigation_bar region. My search bar is in the header region and it displays fine on all pages. When I tried to move the menu into the header region it still doesn't work ! Anyone have an idea what probably might be?

Thanks,
Rita

From the Blocks settings page at admin/structure/block/manage, go to the configuration for the block in question. In the block's "Visibility settings" section, make sure the "Pages" settings are configured in such a way that the block is not hidden from the View page you are having trouble with.


call specific name of views from module Below code changes the all quantity label to none. i am trying to change quantity field label for specific views block for ubercart3. (so in product node, quantity labeled as quantity and in product views block, quantity field is not labeled.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if(strpos($form_id, 'uc_product_add_to_cart') !== FALSE){
    $form['qty']['#title'] = t('');
  }
}

How to call specific views from module? or is this something i should do in views template?
i tried the below code and qty label doesn't change.

if(strpos($form_id, 'uc_product_add_to_cart') !== FALSE){
  $view = $form_state['view'];
  if ($view->name == 'my_view_machine_name') {
    $form['qty']['#title'] = t('');
  }
}

You need to replace 'my_view_machine_name' with your actual view machine name.

To get view machine name, you can edit your view, and in the URL you will see it: admin/structure/views/view/machine_name/edit


Duplicate the value of the price of the products to field in node I have node (Product display) and inside this node is field link to product. The usual option for commerce.

In commerce product is the field  - commerce_price.

In node is field field_node_price.

How can synchronize value from commerce_price to field_node_price?

You need to use Computed Field here.

  Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!

Now, substitute plain link with Entity reference - that way you will be able to access referenced product's fields in code and use them, especially price, in node's computed field


How to resize automatically when users upload images by CCK image field I would like to make the size of images smaller automatically when users upload them using CCK image field.

For example, I would like to let users upload big sized images like 5MB but resize them smaller automatically like 0.5MB before saved on the server.

The reason is that the capacity I can use on the shared server is very limited. Of course I can set "Maximum upload size per file" to a small size but then users who have big sized images but don't know how to resize them before upload will not be able to upload them. I have tried also "image cache" a bit but it doesn't seem to save the files with the name, attributes and in the directory specified by CCK image field.

I don't know if this kind of thing is possible to achieve or not.. Any Idea?

Imagecache is great, but since it keeps the original file around, it won't save space. In fact, if you have multiple presets, it will increase your disk usage as it creates its caches of images of those sizes.

What you may want to investigate is putting some logic into nodeapi() (or, if on Drupal7, its equivalent function) when saving your node that looks at the filepath of whatever image field you are concerned with and does some image manipulation on it if it is over a certain size and then saving it in place.


How to set a rule that assigns a user to a specific Organic Group after the checkout process I´m using rules, organic groups and drupal commerce modules.

I´ve set a rule that creates a new user after the anonymous completes the checkout process.

I want the rule to assign the user to a specific group (OG). I can´t find the way to do it.
I´ve added a screenshot of what are the available options,a nd it seems that there aren´t enough available selectors to do that.

Is there a way to add the user using php? How?
I´ve added the print screen after setting Action: Add entity to group.

For reference, this type of use case (selling access to an organic group) would be best handled now using the Commerce License framework, that has been designed specifically for this type of use cases.

We don't have integration with Organic Groups yet, but it seems straightforward to do in the framework.


Show the site name in a custom block I am working on Drupal 8 custom block. I want to print the site name in this custom block.
MyBlock.php
public function build() {
  return [
    '#markup' => t('This is a simple block!'),
  ];
}

How can I get the site name?

Get the site name from config and add the config as cacheable dependency so that the block gets updated when you change the site name.
public function build() {
  $config = \Drupal::config('system.site');

  $build = [
    '#markup' => $config->get('name'),
  ];

  $renderer = \Drupal::service('renderer');
  $renderer->addCacheableDependency($build, $config);

  return $build;
}


How to call function after submit button clicked $nid = db_insert('tennis_vana')
  ->fields(array(   'firstname' => $first,   'lastname' => $last   ))
  ->execute();

unset($form);
$form_state['rebuild'] = TRUE;

drupal_set_message("you data has been saved");

$details=project_list1();

this is not working. My requirement is, I want to call and display information from after submit.

If you want to call the function after submit of the form.

Add this part in hook_menu:

function MYMODULE_menu(){

    $items['project'] = array(
    'title' => 'Project List' ,
    'page callback' => 'project_list1',
    'access callback' => TRUE,
    'menu_name' => 'devel',
    'type' => MENU_CALLBACK,
    );

 return $items;

}

If you want the menu to appear in main menu you can make these changes:

     'menu_name' => 'main-menu',
     'type' => MENU_NORMAL_ITEM,

Your  function here:

  function project_list1(){
     /////code
    }

And then in your submit function, you can directly add:

  //Add this in the last line of your submit function
   drupal_goto('project');

This will directly go to the path 'project' and call your function

  project_list1()


How to run a Drush command in interactive mode I want Drush to actively output messages instead of putting them into a buffer and then outputting them when it is done running. Now Drush has an interactive mode that I think will do this. However I can't seem to figure out how to get it to work.

I can modify either Drush or my Drupal module (that contains Drush commands) to do this. I just need to know what to do to accomplish this.

I am running Drush 4.4 against Drupal 6.22.

Any thoughts or ideas?

The 'interactive' flag in Drush backend invoke is only used when Drush is going to programatically call another Drush command.  In this instance, the interactive flag tells Drush to call the subcommand in a way that will allow user input.

The issue you reference above (drupal.org/node/1058874) is now standard in Drush 5. If you upgrade, you should find that Drush does a better job at showing incremental progress in some situations. Of course, there are also still some commands where Drush must first compose all of the output, then format it in a table, then output it.  In these cases, the output will always be buffered.


How do I change theme for tables rendered with theme_table()? I'm willing to change look and feel of Drupal tables. I was building my own theme using Zen's STARTERKIT, and the current look and feel is not pretty.

How can I change template for tables? Specifically, I like the table theme being displayed in Administration theme/Admin panel. How do I use that theme for my tables?

I think that what you need is just to change the CSS styles used for the table, as Clive suggested. That would not change the output produced from theme('table'), but it would change how that output is rendered.

If you really want to change the output, because you want to add HTML tags to what normally output for the tables, you need to override the theme function. If THEMENAME is your theme's name, then you need to write the THEMENAME_table() function in the template.php file for your theme. you can look at the code of theme_table() as example of which code to write. Normally you want to add output, or slightly change the output, and in that case you use most of the code already used in theme_table().

In Drupal 7 there is another alternative, which is possible if what you want to do is alter the value of the variables passed to the theme function: Each theme function, even the ones not using a template, have a preprocess function. In this case, the variables used from the theme function are the following ones:

$variables['header']
$variables['rows']
$variables['attributes']
$variables['caption']
$variables['colgroups']
$variables['sticky']
$variables['empty']

Writing code in a function called THEMENAME_preprocess_table() (with $variables as parameter), you can alter the value of those variables before they are passed to the theme function.

  How can I change template for tables?

For the table theme function, there aren't template files involved; it is possible to use a template file in this case too, but you should write more code to gain few. I can report how to do this, but I would not suggest doing it.

  How do I use that theme for my tables?

You just call the theme function with theme('table', $variables), where $variables is an array containing the values required from the theme function, which are:

header: An array containing the table headers. Each element of the array can be either a localized string or an associative array with the following keys:

"data": The localized title of the table column.
"field": The database field represented in the table column (required if user is to be able to sort on this column).
"sort": A default sort order for this column ("asc" or "desc").
Any HTML attributes, such as "colspan", to apply to the column header cell.

rows: An array of table rows. Every row is an array of cells, or an associative array with the following keys:

"data": an array of cells
Any HTML attributes, such as "class", to apply to the table row.
"no_striping": a boolean indicating that the row should receive no 'even / odd' styling. Defaults to FALSE.

Each cell can be either a string or an associative array with the following keys:

"data": The string to display in the table cell.
"header": Indicates this cell is a header.
Any HTML attributes, such as "colspan", to apply to the table cell.


Media Module Bulk Upload for Image Field Using Media 7.x-2.x-version I am trying to use the integrated Bulk Upload Module. I have activated Media Bulk Upload sub module as part of Media. Now if I use a image field with media selector I can still upload only one image at a time. Only if I go to "file/add" I have the multiple file upload option. Is this by design or is there a possibilty to use multiple file upload directly when adding content via Image field.

I'm also faced the same issue. But after applying this patch (check your media module version) it works great.


Reasons for using a webform node rather than just linking directly to the webform Other than reuse, is there any reason why I should not link directly to a form in Drupal 8? I mean linking directly to the webform rather than to a node that incorporates the webform?

The main reason being you can't use any functionality that comes with a node being the page. E.g. add custom fields/paragraphs and allow users to edit them to customise the page. All of that would need to be done as blocks which isn't as efficent/easy for content loaders to manage
If you need to add metatags and other things like that also become more difficult.
And from the webform perspective it allows you to reuse the same form on multiple pages and the results are segmented to the webform node. Meaning if you need multiple copies of a form on your site you can have 1 form and reuse it on multiple pages rather than duplicating the actual webform itself


Intermittent silent login failure A knowledgeable user had a strange login problem today. Our site is using LoginToboggan.

User went to directly to a URL requiring login (clicked on a link a in an email), but was not logged in.
User got 403 page, Access Denied, as expected. I have 403 pages set to go to /toboggan/denied.
User typed in name and password (or browser had it memorized) and clicked "Log in"
User went to a 403 page again. This happened repeatedly.

The user tried two other browsers, cleared cookies, etc. Eventually he tried our usual login page, which has a regular login block. That worked fine.

I tried this myself several times, and was able to reproduce it exactly once. I noticed at some point during multiple failures that the URL on the 403 page was not the original URL, but was /user/logout. It was as if I was sort of half-logged-in or half-logged-out.

Since then I've tried numerous variations on this and haven't been able to duplicate it. For the user, it happens consistently. I went over the user's browser settings and they don't seem to be unusual (he accepts third-party cookies, etc.).

Suggestions welcome as to what else to check for.

I believe this was due to the user logging in as http://example.com and then trying to access a link (from an email) to http://www.example.com/page-that-requires-a-login. In addition the user had a bad browser-memorized password for http://www.example.com, though his password for http://example.com was good. This apparently caused an odd loop of login failures.

I have uncommented the Drupal-supplied redirects in .htaccess that force all http://www.example.com URL's to redirect to http://example.com versions, and have told all my users they may need to re-memorize their passwords in the browser.


Why do I get a redirect loop (302) when using path-auto patterns on taxonomy terms? I am using pathauto to set up my URL's at the moment and they are working fine for nodes.
However when I set up a rule for taxonomy terms using [term:name] as the pattern I end up with redirect loops.

Can anyone explain why this is and how to remedy.

Thanks for any help.

It seems to have been due to caching and the rebuilding of the alias table.

Once I left it for a while and cleared caches it was working as expected.


How do I display a summary page after finishing a multistep form? I have a multi step form in Drupal 6, and I want to show a summary page based on entered information in the steps after finishing the steps and user click finish button.

I am using the ctools wizard for create the multistep form.

How can I achieve it?

Multistep forms are pretty well documented in Examples for Developers module. Basically if you need a summary before posting, add one more step, as steps have access to values from previous ones. If you need a "thank you" page, use usual redirect. That's the answer for question in title, at least.

If you are using some modules than stops you from doing it the traditional way described above, you need answer from someone familiar with that particular modules. Sorry, cannot help you specifically with ctools wizard.


How do you improve Drupal performance? Drupal is fast at develop, but the performance is so poor.
It is hard to reach 50 request per second.

And there are so many SQL queries in a simple web page.
If you test the request time of a form submit in Drupal.org it will always take seconds to finish.

How do you improve the speed of your web site?

Caching, caching, and caching.

Some suggestions I have previously given to a similar question on d.o.

Putting Varnish or another reverse-proxy in front of your http-deamon is probably the single best thing you can do.
During DrupalCon Copehagen, Rasmus stated that using a php opcode cache, such as APC, is one of the best things you can do to speed up PHP in general. Performance improves with newer versions of PHP. There is also additional benefits to upgrading PHP when you upgrade Drupal. From 6 to 8, Drupal will go through a major shift towards object orientation, which is also were most performance improvements happens in the newer PHP versions.
Memcache is a popular choice for speeding up cache, by putting the cache into memory instead of disc.
Panels + Caching combined with Cache actions can increase performance significantly, even for logged in users, as it supports quite complex logic.
The Entity Cache is a nice and zero-conf speed boost for anyone using Drupal 7.
Write-heavy sites have fewer "well established" solutions. Some options include.

Moving frequent writes entirely, for example statistics, somewhere else, such as google analytics.
Caching frequent write operations with a custom solution in something like NodeJS that will write to DB once every Xth second.
Sacrifice the sacred ACID, and use a database like MongoDB. (See Berdir's comment below)
Cluster your SQL-database. Do reads from one database, writes to another. This is native to D7 and Pressflow can help with that in D6.


How to login into Drupal 8 using the REST API? Ok i've spent my whole afternoon trying to get this running:

Setup a freshly installed Drupal 8
Activate the WebServices (HAL, HTTP Basic Auth, Restful Webservices, Serialization)
Install REST UI Module
Activate the REST Module for e.g. /user/{user} under Configuration -> Web-Services -> REST (i'm activating GET/POST with json and basic_auth)
Fix the permissions so all "authenticated user" can access the Restful Webservices for User content

I basically followed this tutorial to get there: https://drupalize.me/blog/201401/introduction-restful-web-services-drupal-8

Then i go forward and create a POST call looking like this:

GET http://{my-host}/user/testing

// with following headers obj
{
  'Authorization': 'Basic dGVzdGluZzptYXN0ZXI=',
  'Content-Type': 'application/json'
}

Well, the user "testing" really exists, i've checked this like 100 times. The Basic Authorization user i'm giving him (i obfuscated the data here since it is still plain text base64) - believe me, it is a correct credential too, even from the admin user.

The path is correct too with /user/{user} - but he is always returning a 404 Not Found ...? Why?

Well what i try to achieve is a login trough a REST API call - so i can login with an existing drupal user from an external system (auth0). As far is i understood from the docs this should all be possible with the /user/{user} endpoint - but i'm totally unsure because i couldn't find any working examples for it.

'Content-Type': 'application/json' needs to be 'Content-Type': 'application/hal+json' in order for it to work.

I recommend you watch these video tutorials

Learn Drupal 8 - REST API Part1

Learn Drupal 8 - REST API Part2

The login is covered in part 2, but part 1 is very informative and part 2 will make more sense if you watch part 1.

Although, the video tutorial uses the Google Chrome Postman add-on, your code needs to do the same.

Have a header with the Content Type and Authorization values

  GET http://{my-host}/user/testing

Your URL to POST, GET, or PATCH shouldn't be your user page, unless you want to work with the user fields. The URL needs to have the entity you are working with.

For example: See the url's used in the video tuts.

You can even use Postman to generate your code

HTTP Generation

PATCH /node/1 HTTP/1.1
Host: forexample.com
Content-Type: application/hal+json
Authorization: Basic Q2FtaWxvOmNvY29saXNa
Cache-Control: no-cache // delete
Postman-Token: 3803eeac-0dc2-5c09-05e1-40d15d5b9820 // delete

{
"title": [
{
"value": "The title changed, WOOOHOOO!!!"
}
],
"type": [
{
"target_id": "article"
}
],
"_links": {
"type": {
"href": "http://forexample.com/rest/type/node/article"
}
}
}

PHPV1 generation

<?php

HttpRequest::methodRegister('PATCH');
$request = new HttpRequest();
$request->setUrl('http://forexample.com/node/1');
$request->setMethod(HttpRequest::HTTP_METH_PATCH);

$request->setHeaders(array(
  'postman-token' => '9656f5e8-13a5-0e2b-23cb-5ac03af59b5b', // remove this line
  'cache-control' => 'no-cache', // remove this line
  'authorization' => 'Basic Q2FtaWxvOmNvY29saXNa',
  'content-type' => 'application/hal+json'
));

$request->setBody('{
"title": [
{
"value": "The title changed, WOOOHOOO!!!"
}
],
"type": [
{
"target_id": "article"
}
],
"_links": {
"type": {
"href": "http://forexample.com/rest/type/node/article"
}
}
}');

try {
  $response = $request->send();

  echo $response->getBody();
} catch (HttpException $ex) {
  echo $ex;
}

You can also generate for other languages like Python, jQuery, PHP Curl to name a few.


Trigger AJAX from a Google Maps Marker I have a Google map loaded through the Google Maps API with markers generated from node locations.

How can I cause content to be loaded via AJAX when one of the markers is clicked.

For example, if the marker is clicked, it would replace another div on the page with information from that node gathered via a db query.

Currently I have the following js which will fire the alert when the marker is clicked

google.maps.event.addListener(marker, 'click', function() {
    //alert(marker.nid);
    $.post('search-map/ajax/marker.nid',{
        nid:marker.nid
    });
});

The "search-map/ajax/marker.nid" URL corresponds to a URL added through hook_menu

$items['search-map/%/%'] = array(
    'page callback' => 'mymodule_map_marker_click',
    'page arguments' => array(1,2),
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM
);

And then I'm trying to get this callback function to run, which as a test, just should replace the contents of a div with some test output:

    function mymodule_map_marker_click($ajax, $building_nid) {
        if ($ajax == 'ajax') {
            $commands = array();
            $output = 'test';

            $commands[] = ajax_command_invoke('.search-listings__listings', 'html', array($output));

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

        } else {
            // if ajax disabled
            return array(
            );
        }
    }

I get this response visible in Firebug, but no action happens on the page:

    [{"command":"settings","settings":{"basePath":"\/","pathPrefix":"","ajaxPageState":{"theme":"mytheme","theme_token":"-CJtCsEvk1Nlzi_mfwSlDTCUoeOv7yyIBHLItpFSIC4"}},"merge":true},{"command":"settings","merge":false},{"command":"invoke","selector":".search-listings__listings","method":"html","arguments":["test"]}]

In my case, I was able to solve this by taking the response from Drupal.ajax and just parsing it myself into the command I needed to run:

                google.maps.event.addListener(marker, 'click', function() {
                    console.log(this.nid + this.title); //#DEBUG
                    $.ajax({
                        url: 'search-map/ajax/' + this.nid,
                        success: function(data,status){
                            for (var key in data) {
                                if (data[key].command == 'invoke') {
                                    console.log(data[key].arguments[0]); //#DEBUG
                                    $(data[key].selector).html(data[key].arguments[0]);
                                }
                            }
                        },
                    });
                });


How to get a custom block form in another custom block? I have a custom block
/**
 * Provides block A.
 *
 * @Block(
 *   id = "block A",
 *   admin_label = @Translation("Block A"),
 * )
 */
class Block A extends BlockBase implements ContainerFactoryPluginInterface {

  public function defaultConfiguration() {
    return [some_value]
  }

  public function blockForm($form, FormStateInterface $form_state) {
    // Configuration form
  }
}

Now I have another block
/**
     * Provides block B.
     *
     * @Block(
     *   id = "block B",
     *   admin_label = @Translation("Block B"),
     * )
     */
    class Block B extends AnotherClass {

      public function defaultConfiguration() {
        return [some_value]
      }

      public function blockForm($form, FormStateInterface $form_state) {
        $form = BlockA->buildForm()
        return $form;
      }
    }

The AnotherClass extends BlockBase.
Is it possible to display the Block A configuration form in Block B?
Like $form = BlockA->buildForm()?
The problem with @Clive comment is that Block A is from the contrib module. So I can't change its base class.

The answer is to use the plugin.manager.block service
Example:
In the Block B BlockForm method.
public function blockForm($form, FormStateInterface $form_state) {
  $block_manager = \Drupal::service('plugin.manager.block');
  $block_a = $block_manager->createInstance('block_a');
  $form = block_a->blockForm($form, $form_state)
  return $form;
}


Can I create an aggregate view that only shows totals without details? I have a view that totals columns but displays each row as well as the totals. Is there a way to hide the detail rows?

You can individually set any field to not display in a View.


Set Permissions in Custom Module I am writing a custom module for my Drupal 7 site. I have added the code to enable a configure form.

I want to restrict the config to admin users only, and some of the functions to another group of users. How do I go about doing this?

Any and all help greatly appreciated.

You can use hook_permission() in your module. This allows you to add a custom permission. For example:

return array(
  'your permission name' => array(
    'title' => t('your permission title'),
    'description' => t('Description.'),
  ),
);

Afterwards, go to the permission page and set the ticks where you need them.


Can't get AJAX on file upload working I have a managed_file form element. I want to trigger an AJAX callback when a user clicks the upload button. But I can't seem to get anything working by attaching the #ajax element to the managed_file element. I know the managed_file element creates an upload button automatically, so I tried to hook into that using hook_form_alter but the button doesn't seem to have been created yet, so I can't attach the AJAX handler.

Any ideas?

No, unfortunately, you can't use #ajax because managed_file uses it internally for its own purposes.


How can I get the node ID inside my implementation of hook_tokens()? I am trying to implement a custom token using the following code.

/**
 * Implements hook_token_info().
 */
function hook_token_info() {
  $type = array(
    'name' => `enter code here`t('xyz'),
    'description' => t('module.'),
    'needs-data' => 'xyz',
  );
  $tokens['full_html_form'] =array(
    'name' => t('Full HTML Form'),
    'description' => t('Returns full HTML Form based on the node'),
  );
  return array(
    'types' => array('abc' => $type),
    'tokens' => array('mno' => $tokens),
  );
}

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

  if ($type == 'abc') {
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'full_html_form':
        $output = core_module_get_node($node->nid);
          $replacements[$original] = $output;
          break;
      }
    }
  }

  return $replacements;
}

I don't understand how to pass node ID to core_module_get_node(). How can I do it?

Since you are defining your own token type, you need to pass the node object to token_replace() in the $data array, for example as $data['node'] or $data['abc']->node, as you are telling Drupal the token requires the 'abc' data.

Your hook_token_info() implementation is wrong, anyway. The correct one would be the following one.

function mymodule_token_info() {
  $type = array(
    'name' => t('xyz'),
    'description' => t('The tokens for the xyz data.'),
    'needs-data' => 'xyz',
  );
  $tokens['full_html_form'] =array(
    'name' => t('Full HTML Form'),
    'description' => t('Returns full HTML Form based on the node'),
  );

  return array(
    'types' => array('abc' => $type),
    'tokens' => array('abc' => $tokens),  /* << */
  );
}

From your code is not clear, but if the token is generated for a node, then you should implement code similar to the following one. (See token_token_info() as guideline.)

function mymodule_token_info() {
  $info['tokens']['node']['full_html_form'] = array(
    'name' => t('Full HTML Form'),
    'description' => t('Returns full HTML Form based on the node'),
  );

  return $info;
}

Modules can define new tokens for token types defined from other modules. The Token module is an example of such a module.


Adding different containers to different parts of content from a node How would I go about restructuring certain elements from a node so they are within different containers. E.g.
If I had a node with 8 different fields and I wanted 4 of them to be rendered within a list, 2 of them within a certain div and the last two in a table. How would I do this?

Should I do it in hook_node_view_alter() and restructure the build array with nested containers, and if so, wouldn't this be quite expensive for large nodes compared to telling the rendering array to nest, according to some conditions, as it is structured? If so where would I do this?

Should I do in a post_render function or?

The Field Group module will allow you to group fields into containers you may then be able to alter some of the mark up with the Fences module.

It does sound like you need more control so if those modules don't work you'll have to get your hands dirty in some code. The template files node.tpl.php and field.tpl.php should give you all the control you need over the mark up.