Why doesn't the pagination work for a comment type, but it works for the other one? I have a custom content type with multiple comment types.

Query comments
Discussion comments

I set the pagination limit for the both the comments as 10. The node detail page, when the number of comments exceeds 10, shows the pagination. For the discussion comments, only 10 comments are shown, even if they are more; no pagination is shown.

Why does this happen?

If you have more than one listing on a page, the pager ID for each needs to be different. This applies to views, but also comment lists.

The way to change this is under your content type's display settings (admin/structure/types/manage/MYTYPE/display). For the comment fields, click on the gear icon and you should see this configuration option:

So long as each comment type uses a different ID, the pagers should work independently of each other.


Article content special characters This problem is node titles and content text.

' character shows like this  mark.

Poland characters there is only ? characters. Example: ŁOŚĆ shows ????

But breadcrumbs shows ' character like this: '

I have trying this:

in article page but not working. Other pages doesn't work either. There I trying this method:

description, ENT_QUOTES, 'UTF-8');?>

But nothing work. So how I can do my page working with all special characters?

There are several possible reasons for that behavior. The most likely one is that your database encoding does not support these characters.

You should use a UTF8 encoding as standard character set (collation).


Is there any module that can automatically convert a module to be used on a different version of Drupal? I don't find many of the Drupal 6 module yet on Drupal 7 and there are many Drupal 7 module that are not available in Drupal 6. I work in High level synthesis and am sure these can be done using high level compilation techniques, but wondering if there has been already any work in this direction. My question is, is there any module /framework already developed that can automatically convert a Drupal 6 module to Drupal 7 and vice versa?

I will not say that it is fully automatic, but Coder Upgrade, which is a sub-module of Coder, will do a lot of the grunt work for you.  However, it is not a 100 % solution, there are always some loose ends to tie up.  It is a good idea to use Coder Review afterwards to highlight the areas that need special attention. After that, it should be a simple case of installing the Drupal 7 version of the module, test it, and fix the remaining nits "by hand".

You can download and install it as part of your staging site or use the web-based version: http://dupgrade.com/

It is one way: Drupal 6 to Drupal 7.  I know of no tool that goes in the other direction.

See also: https://drupal.org/node/224333 for an overview of the changes from Drupal 6 to Drupal 7.


How do I programmatically update pathauto paths for an entity? If an entity has opted into auto generated paths, you could simply re-save the entity. However saving an entity is particularly inefficient, and the path/routing system runs outside of the entity system.

How do I update a path for an entity without saving the entity?

You could use the pathauto.generator service provided by Pathauto:

\Drupal::service('pathauto.generator')->updateEntityAlias($entity, 'update');


Ajax Search Field with labels for node types I'd like to have a search field with ajax and some kind of label for the node type. Similar to http://www.finanzen100.de . Is there any module or other ways of getting this for drupal 7 (or 6)?

Can Inline Ajax Search cover your needs?


Trying to display/printing latitude and longitude from Geolocation Field to node template I've been trying to figure how I can fetch the latitude and longitude values using geolocation field and display it on my node.html.twig template.

I've been using to kint() to see how I would be able to fetch but I can't seem to figure out the right syntax. It seems to be inside an array

Tried node.field_geolocation.latitude.value or node.field_geolocation.longitude.value

I did this by printing, {{ node.field_geolocation.lat }} and {{ node.field_geolocation.lng }}.

That should print the values.


Installing Drupal 7 on VPS CentOS I am using a Green Geeks VPS (CentOS) at the moment and I am new to it. I have found a tutorial on installing Drupal/Apache/Webadmin etc. http://drupal.org/node/743610

What I am wondering is why not just use something like XAMPP instead of all the separate installs? Is there something more I have to take into account here?

I think it's more a taste/customization vs convenience here.
Using XAMPP can install way more stuff than needed and SysAdmins doesn't like this ;) installing each piece individually allows you to select exactly the pieces you need and also there's less risk to be bothered by some strange library or configuration that XAMPP may set up.

So to sum-up:

you're tech-savvy, you want to manage and configure your VPS and aspire to become a SysA, go for the separate install.
you don't want the hassle of configuring (and eventually debugging) each parts, go for XAMPP.
if you want even less troubles, go for a fully managed/optimized hosting platform like Acquia Dev Cloud.


How to convert hook_xmlsitemap_links to xmlsitemap 6.x-2.x API? While writing a test harness for a module I wrote, I discovered my implementation of hook_xmlsitemap_links wasn't actually called anymore.

The module doesn't work with nodes but gets data from sources other than Drupal and themes that. It implemented hook_xmlsitemap_links to add its urls to the sitemap.

Is there some documentation on how to replace a hook implementation with its equivalent(s) in the new 6.x-2.x API, that breaks my search-fu style?

I found it is "kinda hard to explain" and was reading the code like suggested.

There doesn't seem to be hook anymore to return links for further processing, but
 adding and deleting links is done with calls to xmlsitemap_link_save and xmlsitemap_link_delete(_multiple)

I implemented a hook_xmlsitemap_index_links, which normally is only called when the command drush xmlsitemap-index is issued:

function my_xmlsitemap_index_links($limit) {
  $sql = "SELECT x.id FROM {xmlsitemap} x WHERE x.type = 'my'";
  $query = db_query($sql);
  $indexed = xmlsitemap_db_fetch_col($query);
  //there isn't a lot of stuff, it fits in memory, but fetching it is costly.
  $indexed = array_flip($indexed);
  $mystuff = __my_get_stuff();
  $i = 0;
  foreach ( $mystuff as $thing ) {
    if ( !isset($indexed[$thing->id]) ) {
      # new thing
      xmlsitemap_link_save(__my_make_xmlsitemap_link($thing), $thing->id);
      $i++;
    }
    unset($indexed[$thing->id]);
    if ( $i == $limit )
      return;
  }
  #Done indexing new stuff;
  if ( $indexed ) {
    $deleted = array_flip($indexed);
    xmlsitemap_link_delete_multiple(array('type'=>'my', 'id'=>$deleted));
  }
}

I'm still puzzling on what to return from my hook_xmlsitemap_link_info. It's not at all clear when those callbacks are called.

The process callback is useless for this usecase; xmlsitemap has no way of knowing any foreign IDs.
The rebuild callback is afaik only called by drush and manual action, not a means of keeping the links up to date, but it remains unclear if such a callback is required or optional (although xmlsitemap_custom seems to manage without one)
The settings callback is still a mistery to me, but it's used for the admin.

This hook_xmlsitemap_link_info with my_xmlsitemap_index_links as rebuild callback, makes my module reindex when I issue a rebuild command from the admin.

function my_xmlsitemap_link_info() {
  return array(
    'my' => array(
      'label' => t('My Stuff'),
      'xmlsitemap' => array(
        'rebuild callback' => 'my_xmlsitemap_index_links',
        ),
      )
    );
}

I ended up implementing a hook_cron that periodically calls my_xmlsitemap_index_links, to keep it in sync.

I might update my hook_load, to issue a xmlsitemap_link_delete on failed loads (404's).


Cannot figure out role-based pricing rule for custom Product Display/Variation in Commerce Kickstart After working thru the Commerce tutorial and understanding roles, I thought it would be straightforward to set up a pricing rule based on user role, but I cannot seem to build the correct "Action" in Rules.

I want to reference a "Dealer Price" field in a Product Variation is the User Role = "dealer"

Error: Data selector commerce-line-item:commerce-product:field-dealer-price:amount for parameter amount is invalid.

Here are the steps I took to get to my current spot:

In a custom Product Variation "Bikes", I created a new field "Dealer Price" that mirrors the "Price" field that is already part of Commerce Kickstart
Dealer price
Field Type: Price
Widget: Price with Currency
2, Created role "Dealer"
Initiated creation of pricing rule
Store Settings >> Pricing Rules
Add Pricing Rule
Add Event: Calculating the sell price of a product
Add Conditions: 1. User has role(s): Parameter: User: [site:current-user], Roles: dealer; 2. Entity has field: Parameter: Entity: [commerce-line-item], Field: commerce_product; 3. Entity has field: Parameter: Entity: [commerce-line-item], Field: field_dealer_price
Then, I get stuck with Add Actions:
Select action to add: Commerce Line Item: Set item to specific amount
Line Item: Data Selector: commerce_line_item (Already inserted)
Amount: [Click on Switch to Data Selector]: commerce-line-item:commerce-product:field-dealer-price:amount
or commerce-line-item:commerce-product:field_dealer_price:amount or commerce-line-item:commerce-product:field-dealer_price:amount

I get an error msg when trying to reference the new price field "Dealer Price".

I feel like I am missing a connection within Commerce that ties the Product Variation to the commerce_line_item, but I haven't been able to identify the missing link. My products show up correctly in the shopping cart, so that hasn't been an issue.

Any help in tying the concepts of "Roles", "Rules", and "Commerce Kickstart" together is appreciated.

Thanks,

Entity has field: Parameter: Entity: [commerce-line-item], Field: field_dealer_price

Your price field won't be on commerce-line-item. It will be on commerce-line-item:commerce-product. You need to check for it there.

  Amount: [Click on Switch to Data Selector]: commerce-line-item:commerce-product:field-dealer-price:amount or commerce-line-item:commerce-product:field_dealer_price:amount or commerce-line-item:commerce-product:field-dealer_price:amount

So since the field_dealer_price is on the product instance, you'd be looking at this: commerce-line-item:commerce-product:field-dealer-price:amount

An example, without the role condition, would look like this:

{ "pricing_from_another_field_example" : {
    "LABEL" : "Role based pricing example",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_line_item", "commerce_product_reference" ],
    "ON" : { "commerce_product_calculate_sell_price" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "commerce-line-item" ], "field" : "commerce_product" } },
      { "entity_has_field" : {
          "entity" : [ "commerce-line-item:commerce-product" ],
          "field" : "field_dealer_price"
        }
      }
    ],
    "DO" : [
      { "commerce_line_item_unit_price_amount" : {
          "commerce_line_item" : [ "commerce_line_item" ],
          "amount" : [ "commerce-line-item:commerce-product:field-dealer-price:amount" ],
          "component_name" : "base_price",
          "round_mode" : "1"
        }
      }
    ]
  }
}


Specify the reason for the refusal of publication node Please tell me whether it is possible to realize the functional moderation node using the Rules and Rules Link modules.

When you click the "Decline", moderation offers fill in the "Cause"?

3 day looking for a solution, shoveled a lot of information already.
Now implemented regular rulesov link "Decline" for no reason.

Looks like you were looking for the editablefields module (and some scripts to attache a link). Here is an excerpt from its project page:

  ... allows CCK fields to be edited on a node's display (e.g. at node/123), not just on the node edit pages (e.g. node/123/edit). It also works within views etc. Anywhere a 'formatter' can be selected, you can select editable (or click to edit).


The module does not dissapear after disable, uninstall, clear cache and cron job I want to completely remove the File entitymodule from my Drupal site.

I've disabled the module via Modules in admin panal. Then I also uninstalled it though the panel. After that, I've deleted the files from ftp located under /sites/all/modules/file_entity.

I've cleared the cache. I've run the cron. I even tried /update.php but it says there's nothing to update Review updates step.

When I log into administration panel, I still see that ghost:

I don't have any module that is dependent on File entity.

How to remove that module? I want to do so I can install the new fresh version of it which I need.

This module might live in a profile or in a directory that is not sites/all/modules. It is possible to have the same module in multiple places in Drupal at the same time.

You should open up the database, go to the system table and look for the entry for file_entity and see what the path is. That will tell you. You could also grep your codebase for "File entity" or "file_entity" which should also produce results.

If not, perhaps you are on a dev/stage environment? Did your FTP program actually delete the files? Check that there wasn't a permission issue regarding deleting that.

edit: if this is an older release of the media module, it used to ship with file_entity under media/modules/file_entity if I recall. Also check there. If that is the case, what you should do is completely upgrade the media module to the latest version, which looks like rc2 right now.


add role to existing user on hook_entity_presave I'm trying to add a role to a user but I can't save the change.
function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity){
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  $user->addRole('foobar');
}

I would like to save the change, but $user->save() causes a fatal error.
What would be the correct way?
Note: The error is a whitescreen of death. I guess $user->save() is for creating new users. I would need to update an existing one.

Code should look like this, as an example:

use Drupal\Core\Entity\EntityInterface;
use Drupal\user\Entity\User;

function mymodule_entity_presave(EntityInterface $entity) {
  if ($entity instanceof AccountInterface && $entity->isTranslatable()) {
    $user = User::load($entity->id());
    $user->addRole('foobar');
  }
}

Or better yet, hook_ENTITY_TYPE_presave():

use Drupal\Core\Entity\EntityInterface;
use Drupal\user\Entity\User;

function mymodule_user_presave(EntityInterface $entity) {
  $user = User::load($entity->id());
  $user->addRole('foobar');
}

Simply using hook_entity_presave will fire for any entity about to be saved. So you either need to check the incoming entity, or use the second hook to isolate it.


Automatically fill title attribute of image I defined a content type that consists of a field photo for which I can add up to 20 photos. I'm using the Multiupload Imagefield Widget module to be able to upload several images to one node. Since I'm using descriptive filenames, I would like the title attribute of each image to be automatically filled (instead of filling them all by myself). Does anybody know how to do this?

I looked at the File entity module, but this creates individual pieces of content for each Image I upload. That is not the direction I want to go in.

UPDATE: I'm using D7

If you use D6 try image_fupload module.

  Automatic node title creation and predefining of imagefield fields (customisable / themeable / editable by user / token support [imagefield])


Can I use multiple if statement in with with same validation? Multiple if statement with similar validation will crash(WSOD) my website and I'm not sure if this an expected behavior, meaning what I'm doing is wrong. Or this is a bug, which I should fill into Drupal.org as bug.

Here is my code.

  {%  if page.footer_second and page.footer_third %}
       {% set col_class = 'six' %}

   {# If we have 3 columns#}
   {%  if page.footer_first and page.footer_second and page.footer_third %}
       {% set col_class = 'four' %}

   {# If we have 2 columns#}
   {%  elseif page.footer_first or page.footer_first or footer_third %}
        {% set col_class = 'eight' %}
   {% else %}
        {% set col_class = 'ten' %}
   {% endif %}

     {{ page.footer_first }}

     {{ page.footer_second }}

         {{ page.footer_third }}

    {% endif %}

If I remove one of my if statement my website will not crash (WSOD).

What I'm doing wrong ?

What's jumping out at me is this line:

elseif page.footer_first or page.footer_first or footer_third

It's checking page.footer_first twice, and footer_third, which based on the code you've shown is not a valid variable, it should be page.footer_third. I'm guessing this should be more like:

elseif page.footer_first or page.footer_second or page.footer_third


Which variable to set for programmatically making a field required? I am trying to do something like :

/**
 * Implements hook_update_N().
 */
function module_name_update_7002() {
 // Change field to required
}

To alter a field to make it required in production (where i can't access the backoffice).

Which variable do I have to set for doing so?

Get the form_id of that form and write an alter function for it in your custom module.

function hook_form_form_id_alter() {
 $form['that_field_name'] = array(
   '#required' => TRUE,
    // add other features you want to add
 );
}

Follow the below link for more details:
https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_FORM_ID_alter/7


Drupal Forms API how to get degree sign onto submit button I'd like to have a submit button with "°C" value on it. But when I just copy paste the degree sign, I get an empty value. When I try HTML code for degree sign (&deg;) it is escaped so I get &deg;C.

This is my submit button element in my hook_form function:

$form['wrapper']['F'] = array(
    '#type' => 'submit',
    '#name' => 'F',
    '#value' => '°F',
    //'#value' => '&#176; F',
    //'#value' => '&#x00B0; F',
    '#attributes' => array('id' => 'fahrenheit-button'),
    '#weight' => 20,
  );

Any ideas? Thanks, Tomas

Buttons in Drupal by default are being generated by the theme_button() theme function which uses drupal_attributes() to handle all of the button's attributes which always escapes an attribute's value using check_plain().

Visit api.drupal.org/api/drupal/includes%21form.inc/function/theme_button/7 for the theme_button() function and click under the Code section on a function name to see what it does.

I think there are two possibilities:

You write your own implementation of theme_button(): copy the original function, paste it into your template.php file and rename it to something like YOUR_THEME_button();
Or just use the bare unicode character as you did in your question. I read at stackoverflow.com/q/3627720/328272 that this does not work on Windows XP, but I successfully tested it on IE7 and IE8 on XP using browserstack.com.


How to send an email from user email templates programmatically? There are some email templates on the admin interface of the user account settings.

I want to load that email template and change the token value dynamically in my custom module and then send that email?

Any one who have some idea?

I have found the solution. Below is the method I followed.

I added the new email template to the user account settings form using the following code.

$form['custom_email_template'] = array(
    '#type' => 'fieldset',
    '#title' => t('Contributor Email on Miles recieved'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#tree' => TRUE,
    '#group' => 'email',
  );
  $form['custom_email_template']['user_mail_custom_email_template_subject'] = Array(
    '#type' => 'textfield',
    '#title' => 'Subject',
    '#default_value' => variable_get('user_mail_custom_email_template_subject'),
    '#maxlength' => 180,
  );
  $form['custom_email_template']['user_mail_custom_email_template_body'] = Array(
    '#type' => 'textarea',
    '#title' => 'Body',
    '#default_value' => variable_get('user_mail_custom_email_template_body'),
    '#rows' => 15,
  );

And then on the 2nd submit handler of the user account settings form I used the following code to save the email content in a drupal variable.

variable_set('user_mail_custom_email_template_subject', $form_state['values']['custom_email_template']['user_mail_custom_email_template_subject']);
variable_set('user_mail_custom_email_template_body', $form_state['values']['custom_email_template']['user_mail_custom_email_template_body']);

and then use the following code to get the content of the email template.

$body = variable_get('user_mail_custom_email_template_body');
$subject = variable_get('user_mail_custom_email_template_subject');

and used the str_replace() function to replace the tokens with the dynamic values.

Hope it will help someone.


How to display View contents in a drop down select list? I have a View which display the title field of content of the type Partners. However, I want to format the results in a drop-down select list, so when a user selects one of the titles, it will automatically redirect the user to the content page. How can I achieve this?

Sure this is all possible:

If you just want a select list assure you have the Ctools module installed on your site and use the Jump Menu views style output for your Partners content type. Alternatively use the Jump Menu module which you may find more helpful.
Want this embedded into a block you say? Use the Views Field View module to place your output of (1) into a second view that is a block. If you go this route you likely want to enable caching in your Views.

Be sure to see the project page(s) for these modules.


How to save custom fields when using hook_form_FORM_ID_alter? I am implementing hook_form_FORM_ID_alter(). I have managed to setup for, and be able to collect custom values from the fields. When I submit the form, the node is created without my custom fields (i.e field_1 an field_2).

function mymodule_form_AYG_node_form_alter(&$form, &$form_state, $form_id){
  $options_first = _mymodule_get_first_dropdown_options();

  $selected = isset($form_state['values']['field_1']) ? $form_state['values']['field_1'] : key($options_first);

  $form['field_1'] = array(
    '#weight'=> -15,
    '#type' => 'select',
    '#title' => 'field 1',
    '#options' => $options_first,
    '#default_value' => $selected,
    '#ajax' => array(
      'callback' => 'mymodule_dependent_dropdown_callback',
      // 'wrapper' => 'dropdown-second-replace',
    ),
  );

   $form['field_2'] = array(
    '#weight'=> -14,
    '#type' => 'select',
    '#title' => 'field:',

    '#prefix' => '
',
    '#suffix' => '
',

    '#options' => _mymodule_get_second_dropdown_options($selected),
    '#default_value' => isset($form_state['values']['field_2']) ? $form_state['values']['field_2'] : '',
  );

  $form['#validate'][] = 'mymodule_form_validate';
  $form['#submit'][] = 'mymodule_form_submit';

  return $form;
}

function mymodule_form_submit(&$form, $form_state) {
  // I can see values for the custom fields here.
  // How do I store them in the node?
  dpm($form_state);
}

I have installed the Entity API module, and tried the proposed solution. It gives me an error.

function mymodule_form_submit(&$form, $form_state) {
  $node = $form_state['node'];
  $node = node_load(arg(1));

  krumo($node);  // Getting FALSE here

  $obj = entity_metadata_wrapper('node', $node);
  $obj->field_1 = $form_state['values']['field_1'];
  $obj->field_2 = $form_state['values']['field_2'];
  $obj->save();
}

This is the error:

  EntityMetadataWrapperException: Invalid data value given. Be sure it matches the required data type and format. in EntityDrupalWrapper->set() (line 735 of E:\wamp\www\Classified\sites\all\modules\entity\includes\entity.wrapper.inc).
  The website encountered an unexpected error. Please try again later.

The only thing your form alter has done it added fields to a form. But you need somewhere to store the values of those fields.

When you add a field to an entity (node) using the Field UI module Drupal creates 2 database tables. One to store the field values and one to store older revisions of that fields value. Without these tables you don't have anywhere to store the values.

Here are steps to add that field your node bundle:

Make sure the Field UI module is enabled.
From the admin toolbar visit Structure > Content types > AYG (the name of your node type) > Manage fields.
On this page add your new fields and configure as required.

Now your new fields will show on your node creation / edit forms and you will have tables to store the values of those fields.


How to send an email to a specific user on new account creation using Rules? I have an alumni association portal. When a new user creates profile on the portal, that account stays blocked until a specific user from that batch/department approves it.

I am trying to make use of Rules, but not able to.

You can do setting "admin/config/people/accounts" to sent notification email on account activation.


Content Strategy: Similar but unique content I am building a Drupal 7 site and need some help with my content strategy.  One type of content I regularly work with are workshop/conference pages.  Each workshop/conference may have one or more of the following (proposed content type in parens)

The workshop/conference (book page)

About (basic page)
Registration (webform)
Schedule (basic page)
Lodging information (basic page)
Transportation information (basic page)

The main benefit of this approach: we'll use a Book Navigation Block to have a menu for each workshop/conference sub-page.

However, I see several disadvantages:

Two different workshops/conferences may require unique "Lodging Information" pages.  Drupal won't let me title two different pages "Lodging Information" even though each belongs to a separate book.  I could name each specifically, like

"Lodging Information Conference FOO 2013"
"Lodging Information Conference BAR 2013"
"Lodging information Conference BAZ 2013"

Thinking long-term. . . Let's say in the future our site documents dozens/hundreds of workshops/conferences.  The drop-down to select Book parent pages could get excessively long.  If we don't stick with a good naming convention, this could be a bit overwhelming for content contributors.
I don't like the Book navigation helpers near the footer of every parent/child page (table of contents on parent, previous/up/next buttons on all children pages).  Editing the core Book module seems like overkill to remove this functionality.  Perhaps there's a better way?

Using the Book Module brings up more questions than answers.  Is a the Book Module the best approach to implementing a workshop/conference page?

I would agree with beth's post earlier, use a taxonomy to group all the different content types you are working with.  For example, create a taxonomy vocabulary named "Conference".  For EACH of the content types used to store information about the conference, add a field:
Label: Conference
Type: Term reference
Form element to edit the data: Autocomplete term widget (tagging)

Now, when you are filling in the details using your different content types, tag your content with the conference name.  Later you can filter display of that information by filtering on the taxonomy term.


How do I know the discount rate? Hi I wont to know about how can I use discount rate ?

$report_query = db_select('commerce_order','co');
$report_query->fields('co');
$report_query->orderBy('co.created','ASC');
$report_res = $report_query->execute();
while ($re = $report_res->fetchObject()) {
    $o_id = $re->order_id;
    $o_load = commerce_order_load($o_id);
    echo "<pre>";print_r($o_load);
}

Output:

[1] => Array(
[name] => tax|vat_cst
[price] => Array(
        [amount] => 27556
        [currency_code] => INR
        [data] => Array(
                [tax_rate] => Array(
                        [name] => vat_cst
                        [display_title] => VAT/CST
                        [description] => VAT
                        [rate] => 0.125 // here display tax rate
                        [type] => vat
                        [rules_component] => commerce_tax_rate_vat_cst
                        [default_rules_component] => 1
                        [price_component] => tax|vat_cst
                        [calculation_callback] => commerce_tax_rate_calculate
                        [module] => commerce_tax_ui
                        [title] => VAT/CST
                        [admin_list] => 1
                    )
            )
    )
[included] => 1
)

[2] => Array(
   [name] => discount-20% Off
   [price] => Array(
        [amount] => -49600
        [currency_code] => INR
        [data] => Array(
          [discount_name] => discount_full_discount_20_
          [discount_component_title] => 20% Off
        )
   )
   [included] => 1
)

In vat_cst the rate is 0.125 but,how can I know which rate is used on total order?

The discount rate isn't always available as a percentage (like, for instance, taxes are) because discounts can be whole numbers as well. Regardless, you can ultimately get information about how a price is calculated by looking at the commerce_order_total field on an order or the commerce_total field on a line_item.

Here's an example:

In this screen shot, we'll take a look at 4 items. For the comments assume $price = $order->commerce_order_total[LANGUAGE_NONE][0].

$price['data']['components'][0]['price']['amount'] is the original amount. You know this because $price['data']['components'][0]['price']['amount'] is "base_price".
A discount price component will a name of "discount|DISCOUNT_ID" where DISCOUNT_ID is the machine name of the discount that is being referenced.
$price['data']['components'][1]['price']['amount'] in this instance is the discount that is applied.
$price['amount'] is the combination of all of the components under $price['data']['components'].

There is a data array under the price information on the discount. It contains the label and the machine name of the discount, but it doesn't have any other information. Custom discounts might put more information on there, but you can't necessarily depend on anything else being there.


How to let a user choose a role after their very first login? I want to let users to select their role. There are 4 available roles (created by me as an admin) and the selection should be done after first login, so not on the registration form.

Can anyone help me to resolve this problem?

Note: the question let the user choose role upon registration is not exactly the same as my question here: that one contains "... with their chosen role ...", which is clearly something they entered on the registration form.

I am not sure, but you can try somthing lke this: create form with Form API, on submission change value of Role array in user object.
Example:

function MENUCALLBACKNAME($form, &$form_state, $user) {
 $form = array();
 $form['role'] = array(
  '#title' => t('select role'),
  '#type' => 'select',
  '#options' => //Array of your roles like array(id_of_role => t('Name of Role'), ...)
 );

 $form['uid'] = array(
  '#type' => 'value',
  '#value' => $user->uid,
 );

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

 return $form;
}

function MENUCALLBACKNAME_submit($form, &$form_state) {
 $uid = $form_state['values']['uid'];
 $role = $form_state['values']['role'];

 $account = user_load($uid);

 $account->roles = $role;
 user_save($account);
 $form_state['redirect'] = 'SOME PATH';
}


removing menu block title causing problems I know how to remove the menu title from the block by going into the block setting and putting

<none>

in the title space.

But when i do this a smaller version of my menu appears in place of where the title was.

any clues on how to fix?

Please try to put in the block title

<none>

instead of space


Linking taxonomy terms in views I am using Drupal 8 and I am creating an internship placement system where students sign up and have a skills field (using taxonomy terms).

Employers can create job postings, which have same skills field.

How do I link matching fields (skills) in a view so that when a student logs in they only see jobs related to their skills?

You need to use views as described below

1. Create a user view (not content view)

2. Add contextual filter user id with default value current logged in user

3. Add relationship on terms referenced from field skills (of user)

4. Add relationship with term from skills

The previous relationship should be autoselected

5. Now you can add content fields to view and the field skills relationship should be autoselected

when a user visits the view page the jobs will be contextually filtered based on their profile selections


Change submit button to be ajax using jQuery on forget password does not work I want to change submit button on forget password to be ajax to display the form as a pop up
I use this validation

jQuery('#user-pass').validate({
        rules:{
            "name":{
                required:true,
                email: true
                }
            },
            submitHandler: function(form){
                jQuery.ajax({
                      type: "POST",
                      url: jQuery("#basPath").val() +"ajax/check-login",
                      data:  jQuery("#user-pass").serialize(),
                      dataType:"html",
                      success: function(msg)
                      {
                        if(msg == "Invalid Email")
                        {
                            return false;
                        }

                        else
                        {
                            jQuery("#user-pass").submit(function() {
                              alert('Handler for .submit() called.');
                              return false;
                            });
                        }
                      }
                 });
            }
        });

but no email is sending
Is this right or I have to make something else (I am using Drupal 7.12)

I found a solution I want to share with you
I use

jQuery(form).ajaxSubmit();

an remove this

jQuery("#user-pass").submit(function() {
                              alert('Handler for .submit() called.');
                              return false;
                            });

and it solve the problem I hope it can help you


Upload file and fill in fields in one step; or trigger a rule when a file is uploaded I want to make use of the Media module and the File entity module to upload files, in particular images, to my site without having to attach them to a node. Solely uploading images works like a charm, as the Media module automatically places an "add file" link within the navigation menu.

I also added a couple of fields to my image file type. Unfortunately, the Media module doesn't allow me to choose the image file and fill in the fields at the same time, and then submit. Instead, I have to upload the file, go back to the file, click on edit and fill in the fields afterwards, which in my opinion is pretty annoying.

I am not sure if this issue can be resolved somehow. If it can not be, this could be a workaround:

When I upload a file, a rule is triggered that sends me to the edit page. This way uploading the image and filling in the fields somewhat forms a unit.

However, the Rules module does not offer to react on file uploads.

Does anyone have an idea how to get around this issue?

So I believe that uploading and editing files works correctly with the latest dev release of the media module when using a file field or image field.

Like you said when you go to file/add it is using the file_entity module which I believe they are discussing adding upload and editing here http://drupal.org/node/1553114.


PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'fmotors_fms.block_node_type' doesn't exist: This was working fine last night but when i login to my computer again I got this error now. What is this table {block_node_type} I cant find it in the database but it is in the drupal code in node.module. PLease help

If it was working last night, and now it doesn't and the table is missing, then the table has been deleted/renamed, or the database is partially corrupted. There isn't any other logical explanation.

As you rightly say that table is installed, unconditionally, by the node module upon installation of Drupal (see node_schema()).

If the table is really gone then your only option is to restore the DB from a backup; or if there was no data in that table, just manually create it (or copy from another Drupal install).


Remove website field from comment forms I made it mandatory for anonymous users to leave contact information while commenting along with comment notify so as to improve the user engagement. There are two problems that crept in because of this:

A homepage field also got added with the email field. I want to remove only the homepage field, leaving the email field in place. I could not figure out how to do this.
People comment with fake email addresses.

Can anybody tell me a workaround for these problems?

If you wish to allow anonymous comments but remove the Homepage field, you can do so in either a custom module or theme function that implements hook_form_FORM_alter().

Via a theme function (source, mengi on drupal.org):

function THEME_form_comment_form_alter(&$form) {
  $form['author']['homepage']['#access'] = FALSE;
}

Or via a custom module:

function MYMODULE_form_comment_form_alter(&$form) {
  $form['author']['homepage']['#access'] = FALSE;
}

Note: Anonymous comments may be reasonable if you use other anti-spam measures such as honeypot fields and javascript-filled anti-spam fields.


Any way to customize default nomask used in file_scan_directory() to allow Node.js modules? I would like to use Node.js modules (such as grunt-contrib-imagemin) in my Drupal theme, but that adds *.info files which confuses Drupal.  If there were some way to change the default value of nomask used in file_scan_directory() to include 'node_modules' or some way to tell Node.js to use a local folder other than node_modules then the problem would be solved.

There is a post here that suggests patching Drupal core, but I'm hoping there's a more elegant solution.

As far as Drupal/PHP are concerned, no, there's no option other than either changing the default arguments to the function, or finding all calls to that function that don't include the 2nd arg, and updating things there. Either way you're likely to have to patch a core method or two.

NPM's convention is to use a folder called node_modules. They don't want to change that (https://github.com/npm/npm/issues/2734, https://github.com/npm/npm/issues/775), but there is a prefix config option which may be suitable for your needs.


How to remove panel-separator CSS in mini-panels? I have an issue with a mini-panel which prevents me from aligning social buttons:

I tried to set:

.panel-separator { height: 0px; width: 0px; }

in my CSS, but the Google +1 button is still under the ShareThis buttons, rather than next to it. The only difference is that FireBug displays the div line as shaded. There is enough space on the right of the ShareThis buttons for the Google +1 button.

How can I solve this? Thanks. If it matters, I am using Panels Everywhere with the Versatile theme.

UPDATE

I tried .panel-separator { display: none; }. It improved the situation, but did not solve it:

I am including more requested information:

UPDATE II

I asked another question and the issue is now solved.

All you need is to override the panels_default_style_render_region function.

Open your template.php file that can be found here:
/sites/all/themes/YOURTHEME/
Create a  new function in end of the file

function YOURTHEME_panels_default_style_render_region($vars) {
    $output = '';
    $output .= implode('', $vars['panes']);
    return $output;
}


update only a part of url path in database I am migrating website and I changed my mind about url path where my images are stored. Before the path looked like: files/name-of-article/image.jpg now I would like to change it to files/img/name-of-article/image/jpg. How it is possible to replace "files" with "files/img" string? I found following sql code but it works only for replacing whole urll path.

UPDATE field_data_body  SET body_value = REPLACE(body_value,'src="/olddirectory','src="/newdirectory');

Thank you.

Try the scanner module instead:

http://drupal.org/project/scanner

  Search and Replace Scanner can do plain text search-and-replace, or regular expression search-and-replace, against the title, body and text content fields on all nodes in your system. This is useful for finding html strings that Drupal's normal search will ignore. The module is very handy if you are fixing typos in a lot of content, changing the name of your company, or are changing the URL of a link included multiple times in multiple nodes, among other things.

Your sql query might work but this is a little more robust and has a rollback option.


New sub-theme not showing in appearance I am working with Drupal's Open social framework where in I copy socialblue theme so that i can do my modifications in the new theme. I followed the below steps, cleared cache, yet I am not able to see my new theme in admin/appearance section.

Steps I followed:

1) I duplicated the theme socialblue (html/profiles/contrib/social/themes/socialblue) to newtheme (html/profiles/contrib/social/themes/newtheme)

2) I did a search (socialblue) and replace (newtheme) inside of “newtheme” directory

3) I changed the names of the following files from “socialblue” to “newtheme"

newtheme.info.yml
newtheme.libraries.yml
newtheme.theme
config/install/newtheme.settings.yml

4) I created a /html/sites/default/services.yml file from default.services.yml and made the following changes

twig.config -> debug: true
twig.config -> auto_reload: true
twig.config -> cache: false

5) html/profiles/contrib/social/themes/newtheme$ yarn install

6) html/profiles/contrib/social/themes/newtheme$ sudo npm install -g gulp-cli

7) html/profiles/contrib/social/themes/newtheme$ gulp

I do not get any error. I made sure that my newtheme.info file has name newtheme. I also copied this new theme in html/themes/custom/newtheme still no luck. Am I missing something?

I solved it. Turns out it was because my base theme was mentioned as 'socialblue'. I changed it to 'socialbase' and it worked out. I don't know if a parent theme can have more than one child themes in drupal 8.


Run my JS after views slideshow has finished loading? My javascript executes on window load, resize and orientation change.

jQuery(window).bind("load resize orientationchange",function (e) {
//do something
});

This worked fine until I started using the views slideshow. My code runs before the slideshow. As it measures elements on the screen it doenst work properly. If I resize the browser (so the code re-fires) then it works as expected.

How can I make my code run after views slidehow has finished loading? I also need to re-execute the code every time a slide changes.

I faced the same issue many times (especially when I used lightbox2 module), you can use the theme_preprocess_views_view hook or one of Views template files and add the JS using drupal_add_js.

With your code

drupal_add_js('jQuery(window).bind("load resize orientationchange",function (e) {
//do something
});', 'inline');

Thanks :)


How to implement quotation replies on Commerce orders by multiple users? Commerce order will have 0 price when being placed, Once the order is placed all the users of specific role will get notification(this is working) and should be able to reply to that order(I am making a custom module and view for this) with their own price for that order. There will be multiple fields data to reply like price, qty, destination, etc.

I don't want to create a new order or order revision.I want to be able to somehow add all quotation data to that order for each user.I have seen some quotation like modules but they do not do what I need.

My question is where to save all those fields and data?How to relate it with that order?

How do I achieve that?

Use the Flag module to allow those users of a specific role to flag orders.

When configuring the (non-global) flag(s), attach appropriate fields to them, as described in Attaching fields to flags. These fields could perfectly match with the "multiple fields data to reply like price, qty, destination, etc." (as in your question).

If needed, use the Rules module to add all sorts of additional (custom) logic to the mix, eg:

only allow such flagging to happen within selected timeframes.
send (eMail) notifications to appropriate users.
perform field level validations (whatever may seem to be needed).
...


I installed the Civicrm module on drupal but it s not showing in the navigation bar I just installed the CiviCRM module on my Drupal website. But nothing new about the CiviCRM module is listed on the navigation except in configurations. And of course i have already set all the permissions for CiviCRM accessible for the administrator of the site.

How i can have access to the CiviCRM module?

Installing the CiviCRM module on Drupal requires a few more steps than just enabling the module itself. Check out how to do this in the Drupal Installation Guide for CiviCRM for the version you're using.


I can't access a provided variable in rule action In a rule I have 2 actions, the first one provides a variable (my_var_name). But in the second action this var is not shown as available.

I can't figure out what the problem is.

I was having this problem with a different module with Rules.  I believe the data types are conflicting.  node:author:name is a string, while the value have calculated is an integer, a decimal or a float.

My Problem:

User Field - Voting Currency (set as integer)

Event:

Vote was cast on entity

Action:

Query database for the value of the vote cast
Calculate the value to add/subtract from the Voting Currency field
Set the new value of Voting Currency field.

I discovered the vote was a decimal data type.
I removed the Voting Currency integer field with a Voting Currency decimal field and everything worked!


I cannot clone my site Whenever I try to clone one of my sites, I get this error:

  Drush command terminated abnormally due to an unrecoverable error.
  Error: Cannot redeclare entity_features_get_controller() (previously declared in /data/disk/dd/distro/005/drupal-7.41.1-prod/sites/www.firstsite.com/modules/entity/entity.features.inc:11) in /data/disk/dd/distro/005/drupal-7.41.1-prod/sites/www.clonesite.com/modules/entity/entity.features.inc, line 19

Could you tell me what the reason could be?

I would recommend that you avoid multisite, and clone the code into a separate codebase -- then copy the database. This is much easier to manage for simple use cases, and would entirely avoid your problem above, as you would only have one copy of each module present in your code base, so Drupal would not be able to load any of them twice.

I am not sure exactly how your situation above came to be, but the database from the original site contains references to all of the paths of all of the enabled modules; somehow, Drupal is trying to bootstrap both the old cached paths, and also the new paths for the same module in its new location.  If you want to continue with a multisite setup, it is likely that a registry rebuild would clear this up.


Should I change multiple text fields values via MySQL or is there any other preferable way? The site has a content type and this content type has two fields:

Text Field
Term Reference Field

There are thousands of nodes on this content type and I want to change some values (find/replace).

For example, I want to change all the "ABCD" strings with the "WXYZ" strings on the text fields in all the nodes.

Is it a good way to do this change via MySQL or is there any other preferable way? (Both text field change and taxonomy term replacement).

Note: I saw the Search and Replace Scanner module but it gives some errors I couldn't understand why. And it gives timeout error for a large amount of nodes.

The Drupal way is to iterate over the nodes of interest and modify the fields. Here is a simple example that shows how you could make modifications in the Body field of the Article content type:

  $nodes = node_load_multiple(array(), array('type' => 'article'));
  foreach($nodes as $node) {
    // Only modify nodes that have something in the body field
    if (isset($node->body[$node->language][0]['value'])) {

      $text = $node->body[$node->language][0]['value'];
      $find = 'ABCD';
      $replace = 'WXYZ';
      $text = str_replace($find, $replace, $text);
      $node->body[$node->language][0]['value'] = $text;
      node_save($node);
    }
  }

One thing to note about doing it this way is the last-modified time of all your nodes will be updated. You may or may not want this. If you want to update the nodes without changing the timestamp, use this instead:

  $nodes = node_load_multiple(array(), array('type' => 'article'));
  foreach($nodes as $node) {
    // Only modify nodes that have something in the body field
    if (isset($node->body[$node->language][0]['value'])) {

      $text = $node->body[$node->language][0]['value'];
      $find = 'ABCD';
      $replace = 'WXYZ';
      $text = str_replace($find, $replace, $text);
      $node->body[$node->language][0]['value'] = $text;
      unset($node->created);
      unset($node->updated);
      field_attach_update('node', $node);
    }
  }

Edit: How to modify taxonomy terms

You could use the same approach to modify taxonomy terms, i.e. load the terms, iterate over them, and do a find/replace on each.

  $vocab = taxonomy_vocabulary_machine_name_load('my_vocabulary');
  $terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocab->vid));

  foreach ($terms as $term) {
    $text = $term->name;
    $find = 'ABCD';
    $replace = 'WXYZ';
    $text = str_replace($find, $replace, $text);
    $term->name = $text;
    taxonomy_term_save($term);
  }

Depending on how expert you are with MySQL, you could try updating the database field directly and you might have success, but it's prone to error especially if your fields have revisions.


When to use a preprocess function instead of changing the template I am using drupal 7.

I have one query that when to use a preprocess function instead of changing the template files?

From the docs

  The main role of the preprocessors is to set up variables to be placed within the template (.tpl.php) files.

And building on that:

  There can be numerous preprocessors for each theming hook. Every layer from core, modules, engines and themes can have one, each progressively building upon the variables before being rendered through template files. This keeps the markup clean and easy to work with inside templates by placing most of the logic inside these preprocessors.

So if you're setting up a variable that you want to be rendered in a template, your code will go in a preprocess function.

When it's time to render the variables that have been set up, wrap them in specific markup and so on, you'll be editing template files.


Conference Organizing Distribution (COD) Is COD shipped as a module or an entire Drupal CMS modified to handle conferencing. I can't find any straight forward documentation installing this to an existing project.

COD is a distribution that you can start a Drupal project with, but you can also take the COD features and implement them into an existing site. It's just easier to start off with COD.


How can I grey out/disable certain fields? I am using a Webform module for my multi page form. I would like certain form elements to be greyed out/disabled if an answer to one of the questions is "Yes" (dropdown list).

How would I go about doing this?

If you're using Webform 3.x, you're probably looking for the Webform Conditional module.  If you're using 4.x, conditionals support is built in.

Adding conditionals to your webform will allow you to show or hide webform fields based on answers to other fields.  Using the above module or built-in support in 4.x, you could completely hide a certain field if the answer to another field was "Yes."


problems with contextual filter backtracking node references Drupal 7.19

I have two content types defined:  Package and Account.
In the Package type, a Node Reference field is provided as field_account.

I have two packages that each have a reference to one account.

In the Package display, a link is given for the Account.  Clicking on that link shows the Account.
--now my problem--
On that Account page, I wish to add a block that provides links back to the two Packages.

I have been trying and trying to use Contextual Filter and just can't get it...
Appreciate all the help,
--Scott

Under the contextual filter, check 'Provide default value' under 'When the filter value is NOT available' and select 'Content ID from URL' as the type. Your view should work.

Conceptually, you wish to list 'Packages' in the Context of the Account you are displaying.


Easy Question: Filter a View By Tax Term Menu Style Not Exposed Filters I dont know if im having a blonde moment or not. Im sure i learnt how to do this about 9 years ago way back on drupal 4 but ....well i seem stuck.

I have a page view. /match-previews. Its using the same vocab as im using across my website. I was wanting to create a menu link in the sidebar to each football league. I have it set up with an exposed filter but really i would prefer to have it as a menu system.

Ive tried cloning the page and adding a /match-previews/% page but thats where i seem to be stuck. Maybe just making up some normal pages and making a block view for each and taking the term from the page could be the way to go.

Can anyone put me out my misery as ive been at it too long for now tonight.

Thanks

my page is here if it helps
http://ukfootballbet.com/match-previews/

You can use the /match-previews/% as a contextual filter (advanced tab).  Here is a good tutorial on setting it up (http://www.metaltoad.com/blog/using-drupal-contextual-filters-views)


Programmatically create a organic group How would you programmatically create an OG group? I have tried node_save() but to no joy.

It's simpler than attaching node as group post:

  <?php
  global $user;
  $node = new stdClass();
  $node->type = 'group'; // Change this to group node type name.
  $node->uid = $user->uid;
  $node->title = t('Title'); // Change title generation
  $node->body = t('Body'); // Change body generation
  $node->og_description = t('Group description'); // Change group description generation
  $node->og_selective = OG_CLOSED;
  $node->og_register = OG_REGISTRATION_NEVER;
  $node->og_directory = OG_DIRECTORY_CHOOSE_FALSE;
  $node->og_private = 0;
  node_save($node);
  og_insert_group($node);
  og_save_subscription($node->nid, $node->uid, array('is_active' => 1, 'is_admin' => 1));

(ofcourse you also need to check the return values from alle the three functions)


Restrict User Roles in viewing a Node Content Type without installing a module Currently I want to keep my site slim without having to install big modules to do a small function. I know I can use the content_access module to restrict a user role to view a specific content type, but I was wondering how can this be done without any additional modules installed.

I have a content type of "widget" and I don't want it view-able by anonymous users. It should only be viewed by staff. How can you restrict/hide this content type from anonymous users without installing a module for it?

You can control node access using hook_node_access

e.g:

/**
 * Implements hook_node_access
 */
function MY_MODULE_node_access($node, $op, $account) {

  $type = is_string($node) ? $node : $node->type;

  if ($type == 'type_of_interest') {
    // Require administer nodes permission to view
    if (($op == 'view') && (!user_access('administer nodes', $account))) {
      return NODE_ACCESS_DENY;
    }
  }

}


Select only one radio button in a webform What I need to do is allowing to select only one radio button in a multi-column radios, but each column is in a
, so they are like in different groups. Here is an example of the code:

$form['submitted']['fieldset_time']['time8am'] = array(
  '#type' => 'radios',
  '#options' => array('8:30', '8:45'),
  '#prefix' => '
',
  '#suffix' => '
',
  '#title' => '8 a.m.',
  '#weight' => 8,
);

$form['submitted']['fieldset_time']['time9am'] = array(
  '#type' => 'radios',
  '#options' => array('9:00','9:15','9:30', '9:45'),
  '#prefix' => '
',
  '#suffix' => '
',
  '#title' => '9 a.m.',
  '#weight' => 9,
);

With this code, the radios are displayed in 2 columns but I can choose two options, what can I do to only allow to choose one?

The problem with the radios approach is that they're separate form fields, so the browser is correctly allowing only one selection per field.

Instead, you should use radio - https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#radio and specify the attribute of name to only allow one value to be selected.

I'm assuming this is going to be built programmatically in a loop instead of procedurally, but I'll demonstrate as if this was hard-coded. Also, in a perfect world you'd add markup in the theme, not in the form definition.

$form['submitted']['800_title'] = array(
  '#markup' => '8 a.m.',
  '#prefix' => '
',
);

$form['submitted']['830'] = array(
  '#type' => 'radio',
  '#value' => 'default',
  '#return_value' => '0830',
  '#title' => t('8:30am'),
  '#attributes' => array('name' => array('time')),
  '#prefix' => '',
  '#suffix' => '',
);

$form['submitted']['845'] = array(
  '#type' => 'radio',
  '#value' => 'default',
  '#return_value' => '0845',
  '#title' => t('8:45am'),
  '#attributes' => array('name' => array('time')),
  '#prefix' => '',
  '#suffix' => '
',
);

$form['submitted']['900_title'] = array(
  '#prefix' => '
',
  '#markup' => '9 a.m.',
);

$form['submitted']['900'] = array(
  '#type' => 'radio',
  '#value' => 'default',
  '#return_value' => '0900',
  '#title' => t('9:00am'),
  '#attributes' => array('name' => array('time')),
  '#prefix' => '',
  '#suffix' => '',
);

$form['submitted']['915'] = array(
  '#type' => 'radio',
  '#value' => 'default',
  '#return_value' => '0915',
  '#title' => t('9:15am'),
  '#attributes' => array('name' => array('time')),
  '#prefix' => '',
  '#suffix' => '
',
);


Views menu tabs with a dynamic view I have built a DYNAMIC VIEW to display city data, broken out as tabs on the page -- it is a modified verion of the taxonomy term page view.  It uses view menu tabs for this segregation, and Taxonomy Menu (of city names) to trigger the view.

The tabs all work correctly. The problem is the VIEW tab, which shows all results for the subject city (this is not a view display that I created). I don't want an "all results" tab, and I would like the Overview to be the active tab. However, it does not work to set the Overview as the default menu tab -- counterintuitive. (Have fiddled with this a lot! This year, and a project last year in D6.)  All the desired tabs are set as "menu tabs". The paths are of this format: taxonomy/term/%/travel/guide/overview

The so-called menu parent path (default tab) doesn't really exist. It appears that the default taxonomy term page behavior creates the VIEW tab. Have the Taxonomy Term Page view enabled also with different path than my city view:

I can hide the VIEW tab with CSS, but then there is no active tab.  Would like the Overview to be the active tab, hence first visual info.

NOTE: This issue is similar to this one (unresolved), but trickier because of taxonomy page behavior. Using Menu Tabs with Views 3 (Drupal 7)

  Confirmed. I have a similar issue: the default tab always seems to use the parent menu item's path, instead of its own. I guess, what we'd really like, is that the parent menu item required by default tab item, exist only virtually but never be used on its own. Gonna file an issue for that. – Artur Apr 21 at 9:24

You need to understand that the default tab is not used for anything but the title and the weight of it. For an example, check node/%node/view in node_menu. Also check how node/%node is not a tab and yet when you are on example.com/node/1 you see the View because it's the default.

So. Since Drupal already provides a page on taxonomy/term/% all you need to add is a dummy Views display contents irrelevant, path should be taxonomy/term/%/does_not_matter_what with the title 'Overview' and a nice, negative weight and "default menu tab". All other displays are going to be "menu tabs" plain and these can get paths like taxonomy/term/%/travel.

You can play the same game with a Views display of your own instead of a Drupal provided page if you set that display as a page and the dummy as a children.

To summarize

Have a page, a Views display or a Drupal page at foo/bar.
Add a display at foo/bar/dummy with the title of the default tab and set it as type default tab.
Now add any number of foo/bar/baz displays with the relevant titles as a normal tab.


Field edit limit for users I need to set a limit on the number of times a field can be edited.

use case: the name of the user (field_name_user) can only be edited once or twice.

I tried node edit limit and field permissions but neither won't fit the task. Is ther any other module out there or a way to achieve this?

I think you can achieve this using an entity field, in this case the user entity, and some PHP Code.

Add a Field that counts the numebr of editions. Then, alter the entity edit form (in this case again, the user edit form) and:

Hide the field (with #access FALSE, for example).
Add your custom submit handler to the entity edit form.
If the field value is minor than the max edit count allow to edit
then increment the field value in a custom submit handler.
If the field value is equal to the max edit count then deny the
edition (deny the edit form, hide the field or whatever you want and
fit your needs).

Also don't forget to hide the field when the entity is shown (check the entity display settings page).


"Save draft" form button for anonymous users I am using the Webform module to create a form. I've only just realised that the "Save draft"button is available only for authenticated users, which is a shame! Is there an easy way of making the "Save draft" button available for anonymous users as well?

The condition is on line 1977 of webform.module.

You can remove the && $user != 0 condition, but the comment above is valid. Removing the anonymous user check allows the form state to be saved in the database, with uid=0 and a valid sid.

Removing the same anonymous user check on draft form retrieval, however, does not result in the active draft being returned to the anonymous user.

This functionality would require patching the webform module to allow storage of the $form_state in $_SESSION, or in a client-side cookie, which could be read as part of the draft form retrieval process. It would not be difficult to do, but would be a significant change in the webform module.

If you wish to pursue this, open a feature request in the Webform issue queue on Drupal.org, and message me with the link.


payment processing with stripe I was just wondering if there was any module that implements the stripe api for payment processing. I'm using drupal 7. Stripe is a new payment processor that people say is better than paypal so I'd like to try them out. they're at stripe dot com

There's no ready module for this, since stripe.com has https://stripe.com/api so it should be made as custom module for payment


Render custom twig in a specific language I need to specify the language,
which the drupal renderer uses,
when generating a custom render array.

$renderArray = [
    "#theme" => "DNMBE_email",
    "#body" => [
        "#theme" => "DNMBE_emailBody_groupMessage",
        "#author" => $groupMessage->author,
        "#group" => $groupMessage->group,
        "#message" => $groupMessage->message,
    ],
    "#leadin" => $partials->leadin,
    "#leadout" => $partials->leadout,
];

$render = \Drupal
    ::service('renderer')
    ->renderRoot($renderArray);
$html = (string)$render;

#theme parameters resolve to twigs, which, among other things, contain {{ "From"|t }} markup which is incorrectly rendered as From.

I already posted a similar question, which was marked as duplicate, with the answer suggesting using \Drupal::languageManager()->setConfigOverrideLanguage($language). I do not get the expected result.

When using the t() function, you can supply as third parameter an array, which can be used to specify the language. The renderer however does not take extra parameters, thus also not passing it to twig.

I verified that /admin/config/regional/translate has got the translated string, case-sensitive. I also use ['#cache']['max-age'] = 0 and I don't "precalc"-store any Drupal objects.

Currently, the only working way seems to be by passing local context - including a langcode in the render array and using |t([], {'langcode': 'XX'}) resp. {% trans with {'langcode': 'XX'} %} as mentioned in https://www.drupal.org/project/drupal/issues/2049241


How can I add a CSS class to all the tables? I want to add a table class to all the tables, automatically. How can I achieve this by overriding a theme function?

If your table is rendered using theme('table'), you can preprocess it from your theme function.

function my_theme_preprocess_table(&$variables) {
  $variables['attributes']['class'][] = 'table';
}


How can I programmatically alter a view query? I need to be able to pass a date+time argument to a view. When I add a date field as a contextual argument, the query is only passing this in Y-m-d format. I need to include the time so that I can get a list of events that are happening at a certain time.

I think I should be able to use views_query_alter to change the ->where condition, but I'm not sure where to go from there. If I do this:

function mymodule_views_query_alter($view, $query) {
  if ($view->current_display == 'mydisplay') {
    dsm($query->where[0]['conditions'][0]['field']);
    $query->where[0]['conditions'][0]['field'] = ???
  }
}

This is the output from the dsm:

DATE_FORMAT(node__field_session_date.field_session_date_value, '%Y-%m-%d') = :node__field_session_date_field_session_date_value

How do I change that %Y-%m-%d to include the time in the correct format?

I would approach this from a different angle. You can create a new Datetime argument type (a views plugin) and then add an association for your desired field to your new argument. This means we aren't modifying a query in an unpredictable way, and you can see in configuration that the argument is different. You can set this up to use any date format you wish, but keep in mind that time zones may affect the values.

First, we'll create the new argument type. We're extending the existing base Date argument and only changing the date format. The @ViewsArgument value will need to match the argument id value in the field assignment later on.

mymodule/src/Plugin/views/argument/FullDatetime.php:

<?php

namespace Drupal\mymodule\Plugin\views\argument;

use Drupal\datetime\Plugin\views\argument\Date;

/**
 * Argument handler for a full datetime (CCYYMMDD-HHMM).
 *
 * @ViewsArgument("mymodule_full_datetime")
 */
class FullDatetime extends Date {

  /**
   * {@inheritdoc}
   */
  protected $argFormat = 'Ymd-Hi';

}

And now we'll create a new argument assignment for the Session Date field.

mymodule/mymodule.module:

/**
 * Implements hook_views_data_alter().
 *
 * @param array $data
 */
function mymodule_views_data_alter(array &$data) {
  $data['node__field_session_date']['field_session_date_full_datetime'] = array(
    'argument' => array(
      'field' => 'field_session_date_value',
      'field_name' => 'field_session_date',
      'id' => 'mymodule_full_datetime',
      'table' => 'node__field_session_date',
    ),
    'group' => $this->t('Content'),
    'help' => $this->t('Date in the form of %format.', array('%format' => 'YYYYMMDD-HHMM')),
    'title' => $this->t('@field', array('@field' => 'Session Date (Full Datetime)')),
    'title short' => $this->t('@field (@format)', array('@field' => 'Session Date', '@format' => 'YYYYMMDD-HHMM')),
  );
}

Now you just need to add the Session Date (Full Datetime) argument to your view in place of the argument you were trying to override.


Passing a node variable into views filtering I have content type called "season", which has a custom field. This field can have two options: Helloween and Christmas. Article content type contains the same field.

I want to create a View, which would sort articles by actualy selected field value of single "season" node. Is this possible in Drupal7?

Yes, this is possible.  You are wanting a context filter.

More details about your situation will let me give a better answer.


Displaying a Page Before Drupal Bootstrap starts Is it possible to display page before drupal starts.
for example displaying a nice jQuery animated page first and then after some time, loading drupal or providing a link to the drupal site on that animated page.

To precisely answer your question, Yes.  If a file exists, drupal will not get involved.  Therefore, if, for example, you went to www.yourhost.com/splash.php, and splash.php existed in your web root/directory, it would be run without drupal getting involved.  In there, if you had a link to www.yourhost.com, where drupal's index.php exists, then upon clicking that link, drupal would bootstrap up and do it's thing.

If this is not what you are asking, you could investigate the Front module that allows you to have different front pages based upon roles.  Here, you could, for example, have a fancy splash page for anonymous users that goes away after they login.

If that doesn't work for you, then you could fake this out in a custom module using your own custom logic in either the boot() or init() hooks.


Drupal 7 connection to MS SQLServer/PostgreSQL I'm building an architecture of an integrated system of databases that are going to be the infrastructure of about 60 websites.

since databases are going to be massive (more than 30000 articles will be inserted in the database, thousands of books and its abstraction and etc) I'm really worry about the efficiency and ability of MySQL to handle the data.

I'm not very experienced in the theory of Database Management System, so this is my question, Can MySQL handle this amount of data? if not Can Drupal 7 connect to MSSQL Server and work with it as good as it works with MySQL? what about PostgreSQL?

Thanks

Can MySQL handle this amount of data?

Yes, MySQL can theoretically handle many millions of rows (see How many rows in a database are TOO MANY?).

What actually matter are your server resources, configuration, and indexes. If you're not sure about the first two, consult with a professional dba who will be able to help you fine tune your settings for both Drupal, and, more importantly, the specific usage of your app.

Drupal core tables are heavily indexed (as are many tables provided by contrib modules), so it'll probably come down to the custom/contrib modules you have installed from that respect.

  if not Can Drupal 7 connect to MSSQL Server and work with it as good as it works with MySQL? what about PostgreSQL?

Yes, Drupal can use both MSSQL and PostgreSQL. How well any of those perform will entirely depend on the same things mentioned above. I doubt you'd see massive differences in any of them, unless your app is used in a particular way that one or another is better suited for (but the only way to work that out is by benchmarking).


How do I load the user object? I need to get the global $user object in Drupal 8.
I did $account = \Drupal::currentUser(); in the definition of getSubscribedEvents() (a static method) inside a class file.

I get the following error when running drush cr:

  exception
  [error]
  'Drupal\Core\DependencyInjection\ContainerNotInitializedException'
  with message '\Drupal::$container is not initialized yet.
  \Drupal::setContainer() must be called with a real container.' in
  /Applications/MAMP/htdocs/drupal-8.0.x-dev/core/lib/Drupal.php:129

What is wrong in my code?

Since you are using a getSubscribedEvents() static method, I get you are implementing an event subscriber. In this case, you don't access \Drupal::currentUser() (and any static method returning a service that \Drupal exposes) in that method since it would be getting called too early, when Drupal has not yet initialized the dependency container.
That static method is supposed to return a static array describing the events to which the module wants to subscribe; the methods used to subscribe to the events will eventually take a different action basing on the user currently logged-in, and the user permissions that user account has.

Event subscribers are services, and as such they get their dependency injected. Instead of using \Drupal::currentUser(), you define @current_user as one of the arguments of your service, which is what the authentication_subscriber service does.

class: Drupal\Core\EventSubscriber\AuthenticationSubscriber
arguments:
  - '@authentication'
  - '@current_user'
tags:
  - { name: event_subscriber }

If you look at AuthenticationSubscriber::__construct(), you will see how it gets the current user object.

public function __construct(AuthenticationProviderInterface $authentication_provider, AccountProxyInterface $account_proxy) {
  $this->authenticationProvider = $authentication_provider;
  $this->filter = ($authentication_provider instanceof AuthenticationProviderFilterInterface) ? $authentication_provider : NULL;
  $this->challengeProvider = ($authentication_provider instanceof AuthenticationProviderChallengeInterface) ? $authentication_provider : NULL;
  $this->accountProxy = $account_proxy;
}

In your case, I would use the following code.

mymodule.services.yml

services:
  mymodule.eventsubscriber:
    class: Drupal\mymodule\EventSubscriber\MyModuleSubscriber
    arguments:
      - '@current_user'
    tags:
      - { name: event_subscriber }

src/EventSubscriber/MyModuleSubscriber.php

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class MymoduleSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    // Return the array describing the events to which you subscribe.
  }

  public function __construct(AccountProxyInterface $account_proxy) {
    $this->accountProxy = $account_proxy;
  }

}

Notice that @current_user is an instance of AccountProxyInterface, so for example, you can check the user has some user permissions with $this->accountProxy->hasPermission().


AJAX Edit Node and update Im reading up on how to add AJAX functionality to nodes and am stuck. Where exactly do I place  #ajax in order to make the edit field updae via ajax? Specifically is it an existing php, js, html, css file that handles this? Do I add it to the node or block?  I've read that its fairly simple but drupal isn't my native language so i'm still learning.

I've tried using this module ajax_form_entitty

but it wont load the newly created node after submission it directs to a blank page. I've been told to point the node to a div and insert the div in the header, but I have no idea how that should look.
here is what i've done (which doesn't work)

All help is appreciated

EDIT:

Reading Material
I've tried following along with this as one possible way to go about it but have no clue how to implement anything.

To answer the question of "where" do you add the AJAX functionality in a node form, the answer is in a form_alter. That can be done in a custom module or the theme's template.php file. I recommend a module so the functionality remains even if you change your theme.

A great resource is the examples module which is a group of example modules with great comments that assist developers in implementing Drupal functionality. In fact, there's is a submodule called ajax_example that adds ajax functionality to a a field in a node (exactly what you are looking for!). Here's an excerpt from ajax_examples_node_form_alter.inc:

/**
 * Implements hook_form_FORM_ID_alter() for the node form.
 *
 * Adds two fields to the node form, second only appears after first is enabled.
 */
function ajax_example_form_node_form_alter(&$form, &$form_state, $form_id) {
  $node = $form['#node'];
  $form['ajax_example_1'] = array(
    '#type' => 'checkbox',
    '#title' => t('AJAX Example 1'),
    '#description' => t('Enable to show second field.'),
    '#default_value' => $node->ajax_example['example_1'],
    '#ajax' => array(
      'callback' => 'ajax_example_form_node_callback',
      'wrapper' => 'ajax-example-form-node',
      'effect' => 'fade',
    )
  );
  $form['container'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  // If the state values exist and 'ajax_example_1' state value is 1 or
  // if the state values don't exist and 'example1' variable is 1 then
  // display the ajax_example_2 field.
  if (!empty($form_state['values']['ajax_example_1']) && $form_state['values']['ajax_example_1'] == 1
      || empty($form_state['values']) && $node->ajax_example['example_1']) {

    $form['container']['ajax_example_2'] = array(
      '#type' => 'textfield',
      '#title' => t('AJAX Example 2'),
      '#description' => t('AJAX Example 2'),
      '#default_value' => empty($form_state['values']['ajax_example_2']) ?
                          $node->ajax_example['example_2'] :
                          $form_state['values']['ajax_example_2'],
    );
  }
}

/**
 * Returns changed part of the form.
 *
 * @return renderable array
 *
 * @see ajax_example_form_node_form_alter()
 */
function ajax_example_form_node_callback($form, $form_state) {
  return $form['container'];
}


How Can I do a content type with a 1:n field inside? I'm a bit lost about how Drupal manage content.

For example, I want to create a new content type called Game. When I create a "Game" I want to introduce "Platform" and "Release date".

For example:

Title: Sonic the Hedgehog.Description: Whatever.
Released on:
Platform: Mega Drive Date: 23 june 1991
Platform: Arcade Date: 1991
Platform: Nintendo Switch Date: 2018

I want both platform and date to be keys for sorting games, so clearly platform might be a "vocabulary" in taxonomy?...I'n not really sure. How would be your take on this?

It seems Field collection/tabular data solution is what you're after.

In Drupal 7 the popular module for that was Field collection.

In Drupal 8 Paragraphs seems to be popular, although its description is pointing heavily to the current fad of designing content pages with separate sections, it is still a solution that allows for a more structured group of references. Then you reference the Paragraph you constructed for this particular purpose from within your nodes.

A more abstract solution similar to Paragraphs but more flexible is Bricks. Although its description is pointing to Layout integration you don't have to be distracted by that, it's still a great entity reference grouping mechanism you can use to construct your node structure.

I think Bricks might be better suited for your particular case since you'll always be using the same platform/date structure, but investigate both and see which fits you best.

In short, you need references from your nodes to the platform, and date, and they need to be grouped in pairs. You can do that by creating the abstract reference (brick) from your node, that in itself holds two other references (to platform and date). Platform items (entity reference) can be Taxonomy terms, Date can also be Taxonomy or Date fields, it all depends on your details, what type of data it is, how you're expected to manipulate it, etc.


Hide local tabs in specific content type I want to hide the local tabs for a specific content type. How can I do this? I don't want to complete remove it since I want to show them in other content types

Have you tried Tab Tamer ? If you're using D7 a port in on its way.


Custom menu named arguments i was wondering is it possible to create custom menu named arguments in D7. I can do this

function MY_MODULE_menu(){
  $items['my/callback/%user'] = array(
    ...
    'page callback' => 'MY_MODULE_callback',
    'page arguments' => array(2),
    ....
  );
}

and it will load the user entity. So instead i want to do this:

function MY_MODULE_menu(){
  $items['my/callback/%my_entity'] = array(
    ...
    'page callback' => 'MY_MODULE_callback',
    'page arguments' => array(2),
    ....
  );
}

and my custom entity to be loaded.

Yes, name your function my_entity_load and it will be passed the id.

From the Drupal hook_menu documentation (emphasis mine).

  Auto-Loader Wildcards Registered paths may also contain special
  "auto-loader" wildcard components in the form of '%mymodule_abc',
  where the '%' part means that this path component is a wildcard, and
  the 'mymodule_abc' part defines the prefix for a load function, which
  here would be named mymodule_abc_load(). When a matching path is
  requested, your load function will receive as its first argument the
  path component in the position of the wildcard; load functions may
  also be passed additional arguments (see "load arguments" in the
  return value section below). For example, your module could register
  path 'my-module/%mymodule_abc/edit':

  $items['my-module/%mymodule_abc/edit'] = array(
    'page callback' => 'mymodule_abc_edit',
    'page arguments' => array(1),
  );

  When path 'my-module/123/edit' is requested, your load function
  mymodule_abc_load() will be invoked with the argument '123', and
  should load and return an "abc" object with internal id 123:

  function mymodule_abc_load($abc_id) {
    return db_query("SELECT * FROM {mymodule_abc} WHERE abc_id = :abc_id", array(':abc_id' => $abc_id))->fetchObject();
  }


Render form with ajax submit I have a custom form in a module, similar to this example:

function mymodule_form($form, &$form_state) {
   $radio_options = array(...);
   $form = array();
   $form["wrapper"] = array("#markup" => "

");
   $form['choice'] = array(
       '#title' => '',
       '#type' => 'radios',
       '#options' => $radio_options,
   );
   $form['submit'] = array(
       '#type' => 'submit',
       '#value' => t('Vote'),
       '#ajax' => array(
           'callback' => 'demo_form_ajax_submit',
           'wrapper' => "test-ajax",
           'method' => 'replace',
           'effect' => 'fade',
       ),
   );
   return $form;
}

function demo_form_ajax_submit($form, $form_state) {
   var_dump("something");
}

And I'm printing that form in template like this:

   <?php print render($form['choice']); ?>
   <?php print render($form['form_build_id']); ?>
   <?php print render($form['form_token']); ?>
   <?php print render($form['form_id']); ?>
   <?php print render($form['submit']) ?>

The form is printed correctly and even the button shows the ajax icon when clicked, but it does not work. When I check the logs it shows 2 errors:

Notice: Undefined index: form_build_id in ajax_get_form() (line 325 of...
Invalid form POST data.

It is similar to this issue Ajax not working for themed form but it does not work even adding drupal_render_children($form); at the bottom of the template.

Notes:

I added drupal_add_library('system', 'drupal.ajax'); in the module.
I'm using jQuery 1.7
I also tested drupal_render() instead of render().

Instead of print rendering the individual items, you can try to build your form using the drupal_get_form core function, which allows Drupal to add all the extra components to the form (including the Ajax call).

So in your template it would like like this:

$output = drupal_get_form('mymodule_form');
print drupal_render($output);


custom block tpl with custom module I have created a block-custom.tpl.php, the following is the code inside:

Hello World

Subject:<?php print $block->subject ?>

Content:<?php print $block->content ?>

My custom module code:

        function custom_block_info() {
          $blocks['my-block-id'] = array(
            'info' => t('Block Name'),
          );
          return $blocks;
        }

        /**
         * Implementation of hook_block_view().
         */
        function custom_block_view($delta='') {
          $block = array();
          switch ($delta) {
            case 'my-block-id':
              $block['subject'] = t('Block Name');
              $block['content'] = custom_contents();
              break;
          }
          return $block;
        }

        /**
         * custom html block
         * @return string
         */
        function custom_contents() {
          return '

              Hello World, this is a example custom Block

          ';
        }

I placed the tpl file in /module/block/ directory

I followed the tutorial of the following web page (I know it is for Drupal 6)
http://eureka.ykyuen.info/2010/11/11/drupal-customize-block-template-file/

Of course, the result is nothing, anything I am missing? How to override the block.tpl.php?

You have to put your code into an custom module. Creating Drupal 7.x modules should get you going. You should never change code of core. This will be lost (or at least causes tidious manual work) the next time you update drupal.


form attached JS attributes I'm trying to convert this:

<script type="text/javascript" data-main="/Scripts/submenu/main" src="/Scripts/require.js"></script>

into something like this:

$form['#attached']['js'] = array(
        libraries_get_path('lib').'/Scripts/require.js' => array(
            '#attributes' => array('data-main' => 'main'),
        ),
);

but I can't seem to find the way to add an attribute :(
Any Ideas?

From what I remember, drupal_add_js, which ultimately is called, doesn't support attributes in the script element. You can use drupal_add_html_head to add js with other attributes; the docs page has some examples on how to do this.


Module admin configuration permission I have a custom module, saidbakr_tools and I want to apply permissions to access its administration page found admin/config/administration/saidbakr_tools. All what I have to got from the official module tutorial is to prevent access to it by preventing access to the admin pages.

The code I am using is the following one.

function saidbakr_tools_menu() {
  $items = array();

  $items['admin/config/administration/saidbakr_tools'] = array(
    'title' => 'SaidBakr Tools',
    'description' => 'Settings for SaidBakr Tools!',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('saidbakr_tools_form'),
    'access arguments' => array('administer saidbakr_tools'),
    'type' => MENU_NORMAL_ITEM,
  );

/**
 * Implements hook_permission().
 */
function saidbakr_tools_permission() {
  return array(
    'administer saidbakr_tools' => array(
      'title' => t('Access content for the SaidBakr Tools module'),
    )
  );

I cannot prevent other users with access to administrative pages to access the configuration form for my module.

Is there any error in my code? How can I achieve what I am trying to do?

Since you're not declaring an access callback, the access callback defaults to the user_access() and passes your access argument into it based on the hook_menu().

Now, when we check the code of user_access(), we notice the following code.

// User #1 has all privileges:
if ($account->uid == 1) {
  return TRUE;
}

So the first created admin account will always have access. You then said:

  But I could not able to prevent other Role's users that has access to
  admin pages from accessing its configurations,

If you added another user with the Administrator role, and the permission is unchecked for the Administrator role in the Permissions page, your code should work and I can confirm it. So please check if:

You have the permission unchecked
You have cleared all caches or maybe just the menu cache
The admin user you are currently using to test the page's access is NOT the first admin user created


related news and articles block on content page based on tags I have to create a block that contain five article based on the tags which is get displayed on the content page.Below is the view i created.

The output of this view is

here in the sidebar the article having the same tag in the content page is shown,but the content is getting repeated twice.can anyone tell me why the content in the block is getting repeated

most probably you have more tags on the related content, so it is shown several times. try selecting "distinct values" in Query settings


multiple entity type in entity field query how to add mutilple entity_type and bundles in EntityFieldQuery?

$query->entityCondition('entity_type', 'profile2')
       ->entityCondition('bundle', 'user_profile');

Is there any way to do like this

$query->entityCondition('entity_type', array('profile2','user'))
       ->entityCondition('bundle', array('user_profile','property'));

This should work:

$query->entityCondition('entity_type', array('profile2','user'))
      ->entityCondition('bundle', array('user_profile','property'), 'IN');


Module or template mod for making development site look different from live site When I have my development and live site open in the same browser I sometimes mix them up because they look the same.
What tricks do you all use to distinguish them?

The Environment Indicator works well for that.  It works best with a local_settings.php file, in my experience.


Field Reference Module Problem I have created 2 content types :

Team (Fields: Title, Logo (Image Field)
Game (Date, Team "A", Team "B")

Created a Reference Field at Game content type to pull the logo of each team.

However, when I create a new View table format, everything displays fine, but at the frontpage where I get this message:

  Strict warning: Only variables should be passed by reference in >field_reference_field_formatter_view() (line 316 of >/Users/*/sites/all/modules/field_reference/field_reference.module).

This is line 316 of views.module

$field_entity = !empty($item['entity_id']) ?

I can see that there's something about the fact that the Field Reference is pulling a .JPG file but there's no proper formatter in Views (default, teaser, etc),

Don't know how to correct this,(not a developer) any ideas?

The better option is that you should select a formatter for the image field so that your views work properly when displaying logo images on to it.


Clearing the render cache after being programmatically logged in This issue is on a Drupal 8 site.  I have no reason to think it would behave any different on Drupal 9.
We have a scenario where we are having trouble with caching of a custom block.
This block replicates the behaviour of the Login block in that it checks for an authentication state and presents either the user.login or user.logout route.
This looks to be working.
We also have a login state happening where a user account can be "Not Quite Logged In" (NQLI). We are extending Terms with an IP field and adding an IP Login User user reference field.  When a user hits the site and they are not logged in we check if their IP matches one mentioned on the Terms and if one matches the referenced user is programatically logged in.
When a NQLI user is logged in the Login block still presents a "Log in" link. This is the desired behaviour so the user can still access the login page to log in as an actual personal account.
This is working also.
When a user has accessed the site from a known IP and is logged in as a NQLI user, clicks the "Log in" link, logs in as their own account and is redirected back to the page they came from they are successfully logged in as that personal account.
This process works.
What doesn't work is that the "Log in" menu item is still present in that block on this page.  If you click off to any other page the "My account" and "Log out" links are there as expected.  If you click back to the page you logged in from it still holds the "Log in" link.
We've tried clearing the cache with \Drupal::service('cache.render')->invalidateAll(); in hook_user_login() and hook_preprocess_html().
This is one of my first Drupal 8+ projects. I've been working with Drupal since 4.6 and am very much feeling like a junior dev once again. I'm hoping that there is an obvious place or process to do this that I've just not been able to find. My google-fu has reached its limit on this one.

You need to add cache contexts to your block. Cache contexts tell Drupal that the block needs to be cached differently for different circumstances. In your case, whether or not the user is logged in. you can read more about it here: https://www.drupal.org/docs/drupal-apis/cache-api/cache-contexts


How to make the Views Slideshow controls actually work? I installed the module Views Slideshow 7.x 3.1, including the dependent modules as well as the jquery.cycle.all.js (version 3.03) in sites/all/libraries/jquery.cycle.

I am able to create a slideshow with a numeric pager showing 1 2 3 for the 3 slides I have added.

However, the pager numbers aren't linked and the previous and next buttons look like links but nothing happens when I click them.

Have searched for a solution but found nothing.

Also, the slideshow doesn't cycle, just stays on the 1st slide.

Would it be possible to share the link?

It is also possible that there is a jquery conflict (ran into this issue a while ago). In my case it was superfish + flexslider, both with their own jquery source that were not interchangeable. This lead either the slider not working, or the menu not working.

I solved it by using jQuery.noConflict();
https://api.jquery.com/jQuery.noConflict/


How to use Form API when the form callback is a method? How can I use AClass::FormCallback() as $valid_callback on the code below?

class AClass {
  public function FormCallback() {
  }
}

$valid_callback = ?

drupal_get_form($valid_callback);

drupal_retrieve_form() uses function_exists() before calling the form builder, and that function doesn't work if you pass a string such as 'AClass::FormCallback'. If you pass it an array, e.g. array('AClass', 'FormCallback'), you get an error about the function expecting a string.

What you can do is to use a custom function containing code similar to the following one, and use it as form builder.

function mymodule_form_builder($form, &$form_state) {
  $class = $form['#class_callback'];
  $method = $form['#method_callback'];

  if (method_exists($class, $method)) {
    $args = array_merge(array($form, &$form_state), $form_state['build_info']['args']);
    $form = call_user_func_array(array($class, $method), $args);

    return $form;
  }
}

The code is simplified, and it doesn't contain code to check any possible error condition. It works also just in the case of static methods.

For an explanation of the values passed in $form_state, see the documentation for drupal_build_form().


Entitybrower access denied for non-admin user I have created an entity browser for taxonomy terms that is used as an entity reference select form element on a node. This allows users to browse terms grouped by vocabulary, see synonyms etc. The view that it is using has the permission "View published content" and all users including anonymous have this permission. I do not see any permission settings in the entity browser setup itself or in the general permissions for the entity browser module.
The browser works well for the admin user but gives an access denied to editor users.
What can I check to investigate this?

There's a separate permission for entity browsers - on the permissions page (/admin/people/permissions), they're grouped under Entity Browser. You'll need to give any roles that will use the browser the Access [My Browser] pages permission.


One content type with several fields or several content types? currently I'm working on a master data management system in Drupal.
We've got products for different sales channels (like ebay, magento, amazon etc.)
On field where I'm struggling is: Category
(CatEbay, CatMagento, CatAmazon, etc.)
for one and the same product.

Two options:
Add more fields to a sales channel (content type) or add different sales channels.
If I've got different sales channels, I need to implement a relation as well as the translation might be tricky.

If I simply add several category fields, it doesn't look very nice, but makes everything quite easy.

There is something like:
https://drupal.org/project/bundle_inherit
but does it work with translation or export node + it's alpha2 and we are in a production environment ... maybe it just adds complexity without a lot of benefit.

Would there be a disadvantage to point out by going the 'adding fields' way?

Thanks,
Chris

According to me,

You should only build one content type : "Product". Create the required fields according to your need.
Then, Create taxonomy terms like "Clothing, Electronics, etc." and then use entity_reference module to refer the node(i.e Product in this case).
That's it, Done.
Just create some products and go to taxonomy and add products.
For displaying products on page, You should plan to theme taxonomy pages.


How to transfer field content of a view to a another view as a filter by clicking this content entry Example:
View 1, field "city", content "Berlin"
By click on "Berlin" ->
opens View 2 (filter on "Berlin") in a separate block.
Is this feasible? How do you do that?

Btw: activating the second view in a block by a click - it seems impossible, isn't?
Which way: Make view per page and then -> into a block???

{{field_example__value}}

view-> Field-Content field_example _> overwrite output.

Works as well. Thx to 4*4 again.


How to use CSS preprocessor LESS.js with Drupal 7? I would like to use LESS, the CSS preprocessor, with Drupal 7 projects.

What are the required steps to use LESS in Drupal?

There is the LESS CSS Preprocessor module for drupal.