Drupal Commerce: How to manage different payments (a total amount can be pay in different shares and the user can choose in how many shares) I´ve just installed the Drupal Commerce module in D7, and after watching the video tutorials I think it´s fairly complex, maybe it´s just too much for what I want to do.

I´ve this site where we only sell e-courses. Each course has a total cost, but people can pay just a small part to get enrolled.
The problem is that people have a minimum to pay, but they can pay a bit more if they want, so even is the total price is fixed, I get people to pay different amounts of money each time.

In example:

Course A costs 1000.

To get enrolled you have to pay 100, and then 100 per month (those are recurring payments).

Now, one student can pay 200 when he enrolls, and then after that he can, if he wants, to pay in 200 shares instead of 100 shares. Maybe he can pay 300 to get enrolled and then shares of 100 each.

How may I manage that with Drupal Commerce? Is it possible?

Thanks!

There is Commerce Installments

  Commerce Installments allows you to create installment payments for
  products in a Drupal Commerce store.

Make sure you read Issues for Commerce Installments


Upgrade drupal using drush: Failed to check available update I am trying to upgrade Drupal from 7.14 to 7.18 using drush up command.

Nothing gets updated and I see a bunch of failed warnings:

Failed to check available update data for CCK.
Failed to check available update data for CKEditor.
...
Failed to get available update data for 51 projects.

I can however download modules using drush dl module_name
All commands are run as root.

As tenken suggested, you might try adding -d for debug to your drush command or -v for verbose.

Beyond that, I suggest trying to set $conf['update_max_fetch_time'] to a higher value (I usually set it to 360). It sounds like you may be running into an issue where fetching the update information is exceeding the timeout.


How are node and field tables related in MySQL? I am working on a query that involves the field_data_body Drupal table, and I have been asked to return corresponding node ids for the relevant rows in field_data_body.

However, after reaching a copy of what I think is the accurate database diagram for Drupal databases here -

https://www.drupal.org/files/er_db_schema_drupal_7.png

I don't see how the node table relates to the field_data_body table, so I don't know what kinds of joins I could do to connect them.

I am a DBA working with the database so I am using only SQL. Although if there is a better way to return a report linking these two (in PHP, etc.) I'd be grateful if someone could let me know that, too.

Thanks for any help,
jrdevdba

Fields belong to entities; entities are generic, and the same field can be shared amongst any number of different entity types. So you'll find potentially data from a number of different entity types in any given field table.

All field tables take the same basic form, with the entity_type, entity_id, language and deleted columns used as the differential (with delta added to make up the primary key, and allow multiple cardinality).

So a manual join for a node to the body table might look like this:

SELECT title
FROM node n
INNER JOIN field_data_body b ON b.entity_type = 'node' AND b.entity_id = n.nid AND b.language = 'und' AND b.deleted = 0

Regarding a "better way", the Views module is usually the best solution for such things. I've never used it but I also understand Forena Reports might be useful too.


Commerce Stripe and 2.0 version of library with namespace? I am working on an integration with Commerce Stripe and the new Connect functionality.  This however requires the 2.0 version of the library which can be found here https://github.com/stripe/stripe-php/releases.

I have downloaded the source code for this and put this in my stripe-php directory.  The stripe-php library has a namespace of Stripe.  I have defined my hook_libraries_info as follows

function bh_test_namespace_libraries_info() {
  return array(
    'stripe-php' => array(
      'name' => 'Stripe API Client Library for PHP',
      'vendor url' => 'https://stripe.com/',
      'download url' => 'https://github.com/stripe/stripe-php',
      'dependencies' => array(),
      'version arguments' => array(
        'file' => 'VERSION',
        'pattern' => '/(2.\d+(\.\d+)?)/',
      ),
      'files' => array(
        'php' => array(
          'init.php',
        ),
      ),
    'xautoload' => function($api) {
        $api->namespaceRoot('Stripe', 'lib');
    },
),
);

}

I have installed the xautoload module.  However, the classes are still not loaded.  Does anyone have an idea as to what I am doing wrong?

Download the 2.x uc_stripe version of the gateway for Stripe - it has code that works (https://www.drupal.org/project/uc_stripe) as you are seeking - the version 2.0 library uses \Stripe\Action-to-Take:: instead of Stripe_Action-to-Take::  Stripe Connect however is a whole other issue requiring a OAuth2 flow and JSON working with the Stripe Webhooks to get it working initially and THEN one can use the API for the rest of the issues for nmaintainance


How to enable block "overlay" with a gear How to enable the gear in the top-right corner of a block in Drupal 7 as shown in the screenshot below?

I have several Drupal 7 installations with Bartik theme and only one of them has it and I can not find, where to enable it for the others.

You just need to turn on the core Contextual Links module, and make sure that all roles that should be able to see those links have the "Use contextual links" permission.

If it's still not showing, check to see if your theme has a custom block.tpl.php file. If so, make sure that the $title_prefix and $title_suffix variables are being printed out (see the original template file).

The contextual links output is contained in one of those vars (I think it's $title_suffix actually) so the links won't be printed unless the correct one of those vars is also printed.


How do I properly print the $node array in a views row template? I'm writing a custom views-view-row-rss--content-type.tpl.php file in Drupal 6.

How do I properly print the $node array?

I have tried print_r($node) and even used node_load(). I'm not sure where to go next.

Install and enable the Devel module.

Next, wrap the variables you wish to debug in dpm() or dd()

dpm() will output to the browser if possible.

dd() will output to a file on your server.  For example on my Ubuntu dev box it outputs by default to /tmp/drupal-debug.txt


How to write a self join query in drupal 7 using db_select I want to write a self join query, However I dunno how to write it in drupal 7 using db_select().

The query will look like this

  SELECT * FROM msg where sender = receiver

Both sender and receiver fields are part of the msg table.

A query using db_select is a lot slower than a 'vanilla' db_query call...for a query as simple as the one you're doing just run it through db_query:

$query = db_query('SELECT * FROM msg where sender = receiver');


How to show user info in DIV based on link click? I'm currently trying to make a 'biography' block with Drupal profile pictures and when you click on them more information (user fields that has been filled in by the Drupal user) will dynamically display in a block. To be more specific, this is what I want:

https://css-tricks.com/forums/topic/change-content-in-div-based-on-link-click

I tried to make a Views block displaying the profile pictures. These pictures will function as thumbnails. The things is, I have no idea how it will show more information when you click on them (without going to the profile page). Is there a Views trick, Jquery way or any other method I can try?

Have a look at the Colorbox module. Some more details about it (from its project page):

Colorbox is a light-weight customizable lightbox plugin for jQuery. This module allows for integration of Colorbox into Drupal.
Images, iframed or inline content etc. can be displayed in a overlay above the current page.
Features

Works as a Formatter in entities and in views.
Excellent integration with core image field and image styles and the Insert module
Choose between a default style and a number of other styles that are included.
Style the Colorbox with a custom Colorbox style in your theme.
Drush command, drush colorbox-plugin, to download and install the Colorbox plugin in sites/all/libraries.

Credits: rooby (in a comment below the question).


why #submit not apply in form I create a menu and in callback of it call this function

function floristdev_own_price_choice(){
  module_load_include('inc', 'node', 'node.pages');
  $form = node_add('customflower');
  $form['#submit'][]='floristdev_own_price_choice_sub';
      //      unset($form['#action']);
  dsm($form);
  return drupal_render($form);

}
function floristdev_own_price_choice_sub($form,$form_state){
    drupal_set_message('I called');
    dsm('blah blah');
}

but the floristdev_own_price_choice_sub never call ( I put die and drupal_set_message to test is it call )
where the problem, I am using drupal 7.

This is probably what's happening...

node_add() calls drupal_get_form() internally, which finalises the form and commits submit/validate handler data to the cache.
You're modifying the data in the form array after it's been saved to cache.
When the form submits, the page reloads and the API grabs the cached submit handlers from the store. As your submit function was never saved alongside that data, the API doesn't know about it.

You should use hook_form_alter() as already noted by Jimmajamma in the comments, then you won't have this problem at all.


adding input format for CCK fields in drupal Is there any way by which I can add a input format for the CCK added Text Fields ?
By default its only there for Body field in any node/add , I want this for other fields to evaluate PHP Code.

Multi line text fields switch to filtered text. For single line text fields the answer is no.


Should I enable a feature I created on the same site? I created a view and some configurations and used features to save it into code. When doing so, I used the GUI interface and selected Advanced Features and named a file path (sites/all/modules/custom) and then clicked "generate". In doing so, the code was saved to that file path. It is now listed in the website under features > custom but it is listed as disabled.

What is the best practice for this scenario: should I enable it or keep it disabled since I clearly would like it to be active and part of the code? Thanks!

Sure, you enable it. By that you keep track of changes you make on either development environment.

For example you edit some settings on your local dev site, then the activated feature will recognise the changes. Then you recreate the feature and commit the updated files to your repo. On live then you pull the file changes, which your activated feature there recognises as well.

Now you revert the feature on your live site and by that sync the settings you made on dev to live. All by having the feature activated on all instances you work with.


What's the limit of drupal? I want to know what's the limit of drupal?:

Maximum number of nodes .
Maximum number of content type .
Maximum of files 's size .

And That without interruption of service .
I am using Apache + mysql +redhat  .
Thank you very much

That depends on a lot of factors: hardware, configuration of your LAMP stack, ...

The only real way to test this is to benchmark it yourself, on your hardware, under your circumstances.

There's no real answer to this question.


Difference between Field and Field Instance? When we go to the path /admin/structure/types/manage/article/fields and use the Add new field option or the Add existing field option, does that create a field, create a field instance or attach a field instance? How to differentiate between them? So, programmatically, when to use field_create_field, field_create_instance and field_attach API?

In the field API documentation it only mentions the admin UI and never talks about the path where to create both fields and field instances. So it's confusing. I don't even know if I even make sense.

A field is the basic definition of a field itself.
A field instance is an instance of that field, attached to an entity/bundle.

Fields are created with field_create_field
Field instances, with field_create_instance

To check if the field, or instance exists, use

field_info_field or
field_info_instance

When you create a field through the UI, Drupal always creates a field instance on that entity/bundle.

If you're adding an existing field, the field data is cloned and a field instance is created on the new entity/bundle.

Lastly, field settings apply globally to that field, field instance settings can vary between entity bundles.


How to translate Organic Groups Menu? I can translate a normal menu easily, but how do I translate an Organic Groups Menu?

Good question (+1) but be aware that this is a known issue about the OG Menu module.

There are a few issues related to it, and issue 2348821 contains a great summary of these (related) issues. It also includes some patches (the patch in #9 seems to be the recommended one to consider).

The issue is sill in status "needs review", so maybe you want to consider participating in that review? I.e. check if that patch works for you, and update the issue with your review results?


access denied error on user registration module I created a custom registration form using the code I show below. It works on my test site, but on my live site, it returns an access denied error. I am not sure what the problem is.

function medical_reg_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['#theme'] = 'medical_register';
  $form['actions']['submit']['#value'] = t('Next');
}

The setup is the same so I am rather perplexed. The test site is local. Are there some configurations which make a big difference?

You will get a 403 on user/register if you are already logged in.


Overwrite the title for a particular taxonomy page Can anyone help me on how to overwrite the particular taxonomy page title in Drupal 7?

Let us say I have 4 or more taxonomy page. I need the page title to for 3 pages and not for 1 page. If my url is http://localhost/drupal/companies/* the title should be overwritten as "Hello"; if the url is http://localhost/drupal/technology/* the default page title should  appear.

It is easily done with the Taxonomy Title module.
It adds a "Term page heading" field for terms. Simply edit your term and you'll see.


How do I retrieve the field data  associated with an entity, using EntityFieldQuery? I'm still confused about the entity concept in Drupal 7.
I have a node type audio with an MP3 field. I'm able to use EntityFieldQuery to find all the  audio nodes, but I need the URL of the MP3, which is stored in the "file_managed" table, and I don't find a way to retrieve it.

This is what I have:

// Query audio nodes
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'audio')
  ->propertyCondition('status', 1);
$result = $query->execute();

There is no URL in the $result array. At least I can't find it there; I only get the fid.

When EntityFieldQuery::count() is not invoked, what returned from EntityFieldQuery::execute() is an array having the following structure:

[entity type] => array([entities])

[entity] => array([relevant ID] => [entity object])

The relevant ID is normally the entity ID, as in the query you reported. See entity_create_stub_entity(), and entity_get_info() to understand what information the entity object contains.

To get all the fields associated with the entity you are querying, you just need to execute the following code.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'audio')
  ->propertyCondition('status', 1);
$result = $query->execute();

if (!empty($result['node'])) {
  $nodes = entity_load('node', array_keys($result['node']);
}


How can I display lots of rows of information from a database in my drupal module? In the example_page I believe it shows something like this:

function foo() {
    return array('#markup' => t('bar'));
}

And the function foo would be used for a page callback in the menu hook to create a page. However, In my module I plan on using a db_query to access a database table and with it display many rows of data.

Is there a better way to do this than stuffing all of my output into #markup? It could be done with lots of concatenation, but it would be rather messy and it seems like there should be a better way.

If you're looking to build an HTML table then the theme_table() function will help a lot. See the docs page for full details but this is a basic example:

function MYMODULE_page_callback() {
  // Header for the table
  $header = array('id', 'name');

  // Get your data
  $data = db_query('SELECT id, name FROM {my_table}')->fetchAllKeyed();

  // Loop through the data and add rows to the table
  $rows = array();
  foreach ($data as $id => $name) {
    $rows[] = array(
      $id,
      $name
    );
  }

  // Return the themed table
  return theme('table', array('header' => $header, 'rows' => $rows));

  // You could also use:
  return array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows
  );
}


How do I append a unique menu ID to the menu? I'm using Drupal 7 and I want to append a unique ID to specific menus. My search result gives me the way to change the item of the menu, but I want to change the menu itself.
Is there a way to do that?

You can use the menu attributes module to add custom classes, id's, names etc... to any menu item in Drupal. Very handy module when you are looking to alter Drupal's menu system to create a custom look.


How can show pdf preview first image? Hope you can help me.

I use drupal 8.

I want pdf preview like this http://prntscr.com/j08ljo.

Need uploud pdf file in node and showing just first image in front page.

I check use module pdfpreview https://www.drupal.org/project/pdfpreview

Have with tutorial and dependence. Setup ImageMagick and configured it in image toolkit.
Sent in server files with imagemagick and write path.

"Path to the package executables" ... http://prntscr.com/j08ogh

After this showing in display manage full content "pdf preview" http://prntscr.com/j08r9i

But nothing happened. I hear about "may be i need install for other way imagemagick"

Can you help me?

Thanks for your future answers.

You have to firstly install imagemagick in your operating system.
for Ubuntu please follow below procedure:-

(1)https://medium.com/@sanjaywrites/install-latest-version-of-imagemagick-in-ubuntu-16-04-c406ddea1973

(2) https://www.enovate.co.uk/blog/2015/12/16/how-to-install-imagemagick-from-source-on-ubuntu-14.04

For window download imagemagic exe file.
https://imagemagick.org/script/download.php

once your Operating System have magicmagick  then install these module pdfpreview https://www.drupal.org/project/pdfpreview

and do a needful change as shown in image

and on your view  do a needful change as shown in image


Multi user registration As per the requirement, we need to have two separate registration forms student and companies with different kind of fields.

We planned to use current drupal registration as student registration form with multiple custom fields. (And the values will store in the users table of DB)

Now please provide us a kick-off for creating custom company reg. form which have different fields compare with the student reg. form and store the values in separate table in the DB.

Kindly suggest us.

I'll use default registration for students. Submit of second form will add different role (and register too).

Check this module too: http://drupal.org/project/user_role_field/


Can Commerce be setup to skip Cart/Customer Can the module Drupal Commerce (7.x-1.7) be setup so that a user can just click 'Buy' on an item and then be taken to a payment processor such as Paypal to pay? I've tried to find a way to do this but the Commerce set of modules is just a little overwhelming at the moment.
I need to be able to do this as I'm selling a virtual currency to my users and they are used to a quick process and they don't wish to give out billing information.

Yes, it's possible but would need testing out and tinkering.

You could disable the checkout pages, other than payment / offsite payment redirect

Either at

admin/commerce/config/checkout by setting the panes to disabled
or perhaps with hook_commerce_checkout_page_info_alter and removing the pages.

You could then add a Rule

Event: After adding product to cart
Action: Redirect to page "checkout"

Which will hopefully take the user off to PayPal / offsite payment.

Again, needs testing, but theoretically possible.


Creating programatically a node that has a programtically created image field that should stay empty I'm dealing building several modules that should cope with automatic creation of content synchronized with external sources.
The whole process is automatized, e.g. everything had been created programatically.
My content type has and image field attached to it.
When appempting to create a node without defining what this image field should contain (and it should stay empty), I fall with exception:

    PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048
    Column 'fid' cannot be null: INSERT INTO {file_usage} (fid, module, type, id, count)
    VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4);
    Array ( [:db_insert_placeholder_0] => [:db_insert_placeholder_1] => file [:db_insert_placeholder_2] => node [:db_insert_placeholder_3] => 264 [:db_insert_placeholder_4] => 1 )
    in file_usage_add() (line 657 of /usr/local/drupal7/includes/file.inc).

When on hook_node_presave I'm adding an image to this field all works correctly, but I would like to leave this field empty, that may affect the rest of development process.

If I create the node type programatically but add the image field manually -- all works ok. I tried it, then printed the definition of this field using function field_info_field() and copied some values of there into my code, but it didn't help.

Here is my image field definition:

...

'field_member_photo' => array(
'label' => t('Member Photo'),
'field_name' => 'field_member_photo',
'type' => 'image',
'module' => 'image',
'active' => '1',
'locked' => '0',
'cardinality' => '1',
'deleted' => '0',
'widget' => 'image_image',
'entity_types' => array('node'),
'settings' => array('uri_scheme' => 'public', 'default_image' => 0,),
),

...

Would appreciate any thought about how to solve this problem.

I think this is already been covered here some where but i'll answer this any way because creating fields manually is not something easy.

Let's start:
1. First thing - create the field through the UI
2. Export the fields with features. In the latest version of features, features devide the export to to diffrent things: file with all the fileds settings and a file with all the field instances. From the settings of the field that features create you need only the settings: cardinality, field name, module and settings. From the instance you will need the settings: label, required and the widget. You can save them to a function.

After you saved the settings you will need to use a couple of functions for next you will install your module or anything like this: field_info_field(), this function will let return you the settings of the field if he exists, if not you will need to create it with the function field_create_field() like this:

field_create_field($field_config);

The argument you'll need to give her is the settings of the field you saved later. For attaching the field to an entity you'll need to use the function field_create_instance that get the instance settings you save with three more keys:

field_name - the name of the field
bundle - node type, message type etc. etc,
entity_type - the entity type: node, comment, message etc. etc.

You can see here hot it's done:

// This is the instance settings you saved.
$instance;
$instance += array(
  'field_name' => $field_config['field_name'],
  'bundle' => 'article',
  'entity_type' => 'node',
);

field_create_instance($instance);

You can have a look in the module OG in the function og_create_field() and how he saved fields inside hook. This could very easy and other module you will wrote can be based on this if you have a very a lot of fields.


Custom module permission option not available I developed a custom module and enabled it from admin panel https://site/administer/modules/list . But at permissions page https://site/admin/user/permissions there is no option for the administer or other users to enable it.

As you can see my custom module named is notification module but there is no option to add permission for that.

Edit

I have hook_perm as follows

function hook_perm() {
  return array(
    'access GA admin tab',
    'access check backend tab',
    'access GA admin menus',
    'access GA autocompletion',
    'bypass GA field verification',
  );
}

Is there any relevance for this to the administer permission?

Update

My bad , i was given the same hook_permission values in another module , so it got overwritten with the other module , and my module permission got freezed !

Here is to implement the hook permission

/**
 * Implements hook_permission().
 */
function form_example_permission() {
  return array(
    'administer your module' => array(
      'title' => t('Administer permission for your module'),
      'description' => t('Some description that would appear on the permission page..'),
    ),
  );
}


Newbie Simple D and Views question about grouping and "exclude from display" First time Views project simple question about Views and a HTML list of nodes with Taxonomy term.

I have a basic list of nodes with shared taxonomy terms. The page displays all the nodes and taxonomy terms. When I add a group (under Style: HTML List), I see a new page element added duplicating the taxonomy term. Then, under fields is a checkbox, "Exclude from display" which has a description to suggest this fixes the duplicates when using groups.

Now all the data is excluded! None of the other Field items has this Exclude checked. Each time I made these updates the changes were made immediately. Still, I cleared the cache before posting this missive. Why is all my node data missing from the page with this one use of Exclude? Is this a bug?

What was the problem? After adding "Grouping", I mistakenly thought Filter might contain the Exclude solution. I added it. Then, I recall, clicking Remove, but evidently I did not, or whatever.

Next, I found the correct setting: "Fields: Exclude from display", and then saved. But, what I saw on my end-user page (not preview) between changes was, 1) Grouping take effect, 2) Filter do nothing, 3) Exclude make a "blank page". I'm thinking there are some changes which take effect on the end-user page right away and other that do not.

I'm going to try a new Views Development Workflow: 1) Export often, 2) Use save between each change, 3) Roll Back when things get weird. Repeat. And use the Preview instead of looking at my end-user page.


How to change a term URI based on content type I have 2 content types (photos, videos) and both have a term reference to a "topic" taxonomy.
The topic terms are showing on the node display pages and I would like to link to "/photo/%" for photos and "/video/%" for videos instead of the default "/taxonomy/term/%".

How can I do that?

My answer is going to use two modules, that are tools, not solutions. You will get the flexibility to do most anything you want with the paths, at the cost of needing to understand how the modules work. I will provide an outline of the required configuration below, there are useful videos here, and I will try to update the answer if you get stuck anywhere specific.

Install and enable the Page Manager, as well as Panels
Go to admin/structure/pages/add, and add a Page, with the path video/%video_term
On the next page, click "Change", and pick "Taxonomy term: ID", then pick ID, or Name, as it suites you.
Pick any layout, and just move on until you can click "Finish" to end the wizard. Now fill your layout with whatever content you wish.
Repeat steps 1-4 for your "photo" page.

Since Drupal doesn't allow you to use a variable at the first level, you can't do /%content_type/%term, so instead we create two pages. Personally, I would opt to do something like /products/%content_type/%term, as a single page will lower your maintenance burden down the road. That however, will require understand "Variants", to accommodate two pages in one. The videos will explain that.


Unnecessary showing admin content in main theme In one of my sites I have the bug: when I submit some admin forms, for example after editing a view, or create a taxonomy vocabulary the result page appears in the main site theme instead of admin theme.
If I simply visit these admin pages, for example /admin/structure/taxonomy they appears in admin theme as designed. Also these admin pages is showing in admin theme if i refresh them after form submitting.

So the front-end theme appears only after form submitting on only some cases. For example taxonomy vocabulary creation has this bug, but taxonomy term creation does not have it.

No themekey or some similar modules installed.

What can be a cause?

If you use customError module, make sure you your theme dropdown setting is set to "Default theme" in yoursite.com/admin/config/system/customerror.


How to prevent SubFormState storage leaking into parent? I have ajaxified form where I add or remove plugins. If plugin is present it provides its configuration form.

I am using the SubFormState, as one should, but I have noticed that if plugin sets data into the form state's storage(ie. it also uses ajax), they will leak into the parent form state.

Beside key collision(high probabilty with multiple plugins) the main issue I am facing is that once I remove a plugin but add it again, the data from previous configuration is still present in the form state storage so I end up with already configured plugin form, which is highly undesired.

This is happening because the plugin has no way of knowing it has been removed from the parent form so there is no way to unset the data from storage and the parent form has no way of knowing the plugin(s) put something into the storage as well, so there is no garbage collecting possible.

I am wondering if I should Implement a plugin interface that would have "flushState" method that I would have to invoke when I would remove the plugin from the form or there's a better way to do this?

So far, I have solved it by using #array_parents for getting/setting values into form state storage in plugin forms since there cannot be a key collision in parent form this way.

Small issue with this is that I have to provide the whole parents in there. So if the plugin form is not flat, I have to add all those additional parents in there since they will appear in the ...

... additionally to this in ajax plugin form submit handlers and ajax callbacks I have to get the the "root" element(ie. the form element for the plugin) by detecting #array_parents on the trigger and extracting the proper form element by #array_parents and extracting the #array_parents from it to get to the data in the storage.

Overall it is a massiv DX fail. I have a ***load of plugins and to bulletproof them this way will take a lot of unnecessary time now.

I was thinking about extending the SubformState as KeyedSubformState where the state would "hide" the plugin's storage under provided key so the parent form would control this and be responsible for avoiding key collision and the plugin form doesn't have to be altered in any way(since values are already taken care of) but I have decided not to do it this way since it feels like adding additional layer is not a good idea in the long run...also it won' work for ajax submit handlers since they receive the full form and state and not the subform element and state.

If anyone has a better solution, I'm all ears. But for now it seems plugins are treated like homeles people :D

Also, for the love of god, do not use #parents in plugin form. Or you'll be leaking values into the parent form. Overall, just make the plugin form as dumb as possible. Flat and no ajax, just to be safe.

This is, currently working, plugin with ajax.

/**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $ajax = [
      'wrapper' => Html::getId($this->getPluginId() . '-countries-ajax-wrapper'),
      'callback' => [get_called_class(), 'ajaxRebuildCountries'],
      'progress' => [
        'type' => 'throbber'
      ]
    ];

    $form['allowed_countries'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Allowed countries'),
      '#prefix' => '
',
      '#suffix' => '
'
    ];

    $country_list = $this->countryManager->getList();

    // @see https://drupal.stackexchange.com/questions/243812
    // @see https://www.drupal.org/node/2902121
    $state = $form['#array_parents'];
    $state[] = 'allowed_countries';
    $state[] = 'countries';

    if ($form_state->has($state) === FALSE) {
      $form_state->set($state, $this->getSetting('countries'));
    }
    $countries = $form_state->get($state);

    $form['allowed_countries']['countries'] = [
      '#type' => 'table',
      '#default_value' => [],
      '#empty' => $this->t('No countries have been added yet.')
    ];

    foreach ($countries AS $iso => $level_1) {
      $row = [];

      $row['iso'] = [
        '#markup' => $iso
      ];

      $row['label'] = [
        '#markup' => $country_list[$iso]
      ];

      $row['level_1'] = [
        '#type' => 'value',
        '#value' => []
      ];

      if ($level_1_list = Address::hasLevel1($iso)) {
        $row['level_1'] = [
          '#type' => 'select',
          '#title' => Address::getLevel1Label($iso),
          '#options' => $level_1_list,
          '#default_value' => $level_1,
          '#multiple' => TRUE
        ];
      }

      $row['delete'] = [
        '#type' => 'submit',
        '#value' => $this->t('Delete'),
        '#submit' => [[get_called_class(), 'deleteCountrySubmit']],
        '#name' => 'delete_country_' . $iso,
        '#ajax' => $ajax
      ];

      $form['allowed_countries']['countries'][$iso] = $row;
    }

    $form['allowed_countries']['add_country'] = [
      'country' => [
        '#type' => 'select',
        '#title' => $this->t('Add country'),
        '#options' => array_diff_key($country_list, $countries),
        '#ajax' => $ajax + ['trigger_as' => ['name' => 'add_country_submit']],
        '#empty_value' => '',
        '#empty_option' => t('- Select -')
      ],
      'submit' => [
        '#type' => 'submit',
        '#value' => $this->t('Add country'),
        '#submit' => [[get_called_class(), 'addCountrySubmit']],
        '#name' => 'add_country_submit',
        '#ajax' => $ajax,
        '#attributes' => [
          'class' => ['js-hide']
        ]
      ]
    ];

    return $form;
  }

  /**
   * Form submit handler for attaching a new allowed country.
   *
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   */
  public static function addCountrySubmit(array $form, FormStateInterface $form_state) {
    $element = static::getFormElement($form, $form_state);

    // @see https://drupal.stackexchange.com/questions/243812
    // @see https://www.drupal.org/node/2902121
    $get_country = array_merge($element['#parents'], ['add_country', 'country']);
    $get_countries = array_merge($element['#parents'], ['countries']);
    $set_state = array_merge($element['#array_parents'], ['countries']);

    $country = $form_state->getValue($get_country);
    $countries = $form_state->getValue($get_countries);
    $countries[$country] = [];

    ksort($countries);

    $form_state->set($set_state, $countries);

    $form_state->setRebuild();
  }

  /**
   * Form submit handler for removing allowed country.
   *
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   */
  public static function deleteCountrySubmit(array $form, FormStateInterface $form_state) {
    $element = static::getFormElement($form, $form_state);

    $country = substr($form_state->getTriggeringElement()['#name'], strlen('delete_country_'));

    // @see https://drupal.stackexchange.com/questions/243812
    // @see https://www.drupal.org/node/2902121
    $get_countries = array_merge($element['#parents'], ['countries']);
    $set_state = array_merge($element['#array_parents'], ['countries']);

    $countries = $form_state->getValue($get_countries);
    unset($countries[$country]);

    ksort($countries);

    $form_state->set($set_state, $countries);

    $form_state->setRebuild();
  }

  /**
   * Ajax callback for rebuilding the allowed countries form elements.
   *
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *
   * @return mixed
   */
  public static function ajaxRebuildCountries(array $form, FormStateInterface $form_state) {
    return static::getFormElement($form, $form_state);
  }

  /**
   * Helper method to retrieve the form element containing the plugin
   * configuration "form" from the parent form for ajax calls since
   * there is no SubformState involved and we are getting the whole
   * parent form.
   *
   * @param array $form
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *
   * @return mixed
   */
  public static function getFormElement(array $form, FormStateInterface $form_state) {
    $trigger_parents = $form_state->getTriggeringElement()['#array_parents'];
    $key = array_search('allowed_countries', $trigger_parents);
    return NestedArray::getValue($form, array_slice($trigger_parents, 0, $key + 1));
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValue(['allowed_countries', 'countries']);

    // Fix Level 1 administrative area.
    $values = array_map(function($value) {
      if (is_array($value) && isset($value['level_1'])) {
        return $value['level_1'];
      }
      return $value;
    }, $values);

    $form_state->setValues(['countries' => $values]);
    parent::submitConfigurationForm($form, $form_state);
  }


Editing the post time displayed for comments in Drupal 7 I need to display the post time of comments for a particular content type. I want these post times of comments to be in the "time ago" format.

Example: 1 minute ago

How can I do this in Drupal 7?

There is a native function in Drupal to format date intervals, it is called format_interval.

Usage example:

 // Date since forum post was created
 format_interval(REQUEST_TIME - $variables['topic']->created)

Hope this helps, happy coding!

PS: See the answer I gave on your stackexchange post for the longer custom version you can also use.


Split the node edit form into multiple pages (preferably using panels variants) The task

My goal is to split the node edit page with the main field forms staying on the default one (the add page itself or mynodeurl/edit), and some additional field forms on the other pages (e.g. mynodeurl/option & mynodeurl/otheroption).

I think the best way to do this (and the way I want it to work) would be using a couple of variants for the node add/edit page (Panels Module), with the url path's being filtered through the string: url path selection rules.

The problem

I have no idea how to make the string url path selection rule work like that (I practically dont know anything how the string url path's selection rules work for the node (or node add\edit pages) at all, since I've only seen people implementing the url path based selection rules on custom pages and never on nodes).

How I've tried to solve it

I've done some playing around setting url path's like: /option option /option nodetype//option etc. to the node template and the node add\edit form variants, the only thing that worked is when i set my main node view variant to trigger when: Current path is not "/option" , and set the additional variant to trigger when Current path is "/option", the exactly same thing didnt work for the node add\edit page. (see http://shot.faintrush.me/xfvu1c0aic.png <- this screenshot).

The only working variant is using the Node template page, and adding forms there doesn't work which makes it useless for me. (If you know how to make forms work on the Node template page you'r also very welcome to answer here).

Of course the */option is probably not the best thing to put there, it's just the only one I found that's at least a bit alive.

Additional info

By default my url's work as I have explained here -> https://drupal.org/node/1993068 (i made those url aliases being created automatically but in a different way from using a pathauto + a custom token)
To make the links like siteurl.com/nodetype/25/edit work i use the sub-pathauto module (i have tried setting the sub-pathauto url depth to 2 and accessing siteurl.com/nodetype/25/edit/option with the settings on the screenshot above - didn't work).

More additional info

I also tried to make this work by creating a custom Page with the /node/%node/option path and assigning %node the Node edit form: node ID context, but then I'm running into another problem because the Node id doesn't actually match the url path and there's no way for me to assign the right context to the node edit form - the unique content type node id that i'm using in urls (again, read the issue from the link a bit higher) is not to get by any token or variable, the url alias is just being generated once by the rules module.

I posted the same issue (written in a little bit different words) to the drupal official  website issue queue to the panels module but there seems to be no activity there for a couple of days so I'll give it a try here.

Any help would be appreciated!

Please have a look at Multistep Nodeform.

  For each step you can define which fields should be included in this
  step. "Fields" includes core-fields like "Title", "Body" or "Authoring
  information" as well as fields defined by other modules (e.g. Date).


how could I access users profile using settings parameter in drupal behaviours? I have a behavior as follows:

Drupal.behaviors.mymodule = {
  attach: function(context, settings){
    jQuery("#edit-user-address",context).change(function(){
      console.log(" user id and other fields "+settings.user.id);

    });
  }
}

How could it be achieved?

You should use Drupal's drupal_add_js function with the 'settings' option (more info).

Example:

global $user;
$uid = $user->uid;
drupal_add_js(array('myModule' => array('uid' => $uid)), 'setting');


What can we do to remedy the unrecoverable error we encounter for any Drush command? We used Drush on our server without any problems up until now. Actually we didn't do / change anything relating to Drush.

But now, on every Drush command we issue, we only get an error like so:

  Drush command terminated abnormally due to an unrecoverable error.

Same error also occurs for Drush status. Only drush --version shows "Drush version: 6.6.0".

We installed drush via Composer. And the server is already restarted.

What can we do about this problem, which is a huge problem for us?

Make sure your Drush commands are issued from the appropriate subdirectory of your website (change to the directory where your Drupal site is installed and try again).

Since your question did not specify that, it "might" be the reason why ALL your DRUSH commands are failing ...

Refer to this issue for other possible causes (things you may want to check).

If you recently enabled contributed and/or custom modules, try to temporary disable them to check if the Drush issue gets resolved by doing so.


specify context on hook_menu drupal I would like to check if particular node instance exists then load that node. if the instance does not exist, then display message. So far:

function MODULE_menu() {
    $items['ds-some'] = array(
        'title' => 'Some',
        'page callback' => 'some_display',
        'access arguments' => array('access content'),
        'type' => MENU_NORMAL_ITEM,
        'file' => 'inc/some.pages.inc',
    );

    return $items;
}

function MODULE_theme(){
    return array(
        'render-some' => array(
            'template' => 'page--some',
            'variables' => array(
                'node' => NULL
            ),
            'path' => path_to_theme().'/templates',
        ),
    );
}

in file inc/some.pages.inc

    function some_display(){
            $build = array();

            $nid_some = db_select('node', 'n')
                ->fields('n', array('nid'))
                ->fields('n', array('type'))
                ->condition('n.type', 'SOME_TYPE')
                ->execute()
                ->fetchCol();

            //load first instance
            $someNode = node_load($nid_some[0]);

            if (!empty($shopNode)) {

//Attempt 1
    //            $build['ds-some'] = array(
    //                '#theme' => 'node',
    //                '#node' => $someNode,
    //                '#view_mode' => 'full',
    //            );

//Attempt 2
    //            $build['ds-some'] = node_view($someNode, 'full');

                $build['ds-some'] = array(
                    '#theme' => 'render-some',
                    '#node' => $someNode,
                );
            }
            else {
                drupal_set_message(t('It appears there is no instance present');
            }
            return $build;
    }

The first two attempts ended with the title of the Node instance but Drupal is no rendering the whole page(template file, views, etc). In my last attempt, i use custom theme function that it works, however. It is not rendering the context for the node type specified. How to specify context when working with hook_menu(), so that the context configured will load blocks and views? Thank you for any help.

I don't know how the Context module handles Entity types, but it loads entity type definitions using the entity ID (from the URL). In your case, you are creating a menu item without any arguments, just specifying business logic in the callback, and your menu item path is not a node path. That's why the Context module can't find any entity type definition. In this case you can specify additional context reactions by path (by your custom path) and display blocks.

You don't need to specify double fields method; you can write much simpler code.

$nid_some = db_select('node', 'n')
  ->fields('n', array('nid', 'type'))
  ->condition('n.type', 'SOME_TYPE')
  ->execute()
  ->fetchAll();

If you need to fetch only one row from the database, you can use the following code.

$nid_some = db_select('node', 'n')
  ->fields('n', array('nid', 'type'))
  ->condition('n.type', 'SOME_TYPE')
  ->range(0,1)
  ->orderBy('nid', 'DESC') // Additional sorting
  ->execute()
  ->fetchAll();


How can I show list of users that bookmarked article? How can I do it? I using flag module and I want to have the list of users that bookmarked article. Can I do it only with views?

If you really want to do this with Views you will need the following:

A Content View for articles
with a Nid as a Contextual Filter, in order to limits the results to the article node you are interested in
one relationship that will restrict your results to content that has been flagged with the bookmark flag (by any user)
one relationship that will return all users that flagged content using the flag from the relationship in (3).

Here is a Screenshot of the View:

and one of the end-result, in a sample node:

Hope this helps!


print and print_r in Drupal 7 I'm working on some code for a custom Drupal 7 module the problem is i'm dealing with many arrays and strings. I have tried to use print(), and print_r() to output values so i can see what i'm working with but nothing is printed to the screen. Is Drupal 7 preventing this from happening? How do other Drupal 7 module developers output values? for example in JavaScript i can use console.log() and for PHP i would normally use print(), print_r(), and echo. But looks like Drupal is not permitting this from working in my PHP code.

UPDATE:

In my module i have .inc file inside this file i have a method called list_builder($delta){} Inside this i have a switch() to handle different lists based on the $delta. This method is being executed on the cron_hook. It processes data from some outside sources and builds a json file. I'm at the point of building my json output but dealing with a lot of variables and need to be able to look at the variables at each spot in the process to know what data i'm dealing with while i build the output. I'm looking for a way to diagnostically test/display variables as i work on this module. I'm looking for a universal solution that works no mater what i'm doing.

It's the same as in other PHP applications with separate V layer - print and print_r, being directly PHP functions, don't know about anything in View layer of Drupal application. They cannot pass their output to theming chain, cache systems in place and so on. That said, they often works, but that's more a coincidence.

For array inspection, you should either use xdebug or, if you don't have time, patience or skill to set it up, use Devel module. Specifically, dpm, dvm, dpr and dvr functions will be useful for you. See this helpful demo page for details of their use.

TL;DR: Install Devel, replace print and print_r() calls with dvm(). Profit.


Drupal version control - professional development I have been assigned to develop a site in Drupal. I will be working on it alone. Is there a need for version control? An if yes which is optimal for drupal? How should I set the development process? (ex:make a testing site locally, then get it live). Thank you in advance.

If you've got a complex setup, you may want to look into the Aegir project, which is a Drupal-based tool for managing Drupal site installations.

If your needs aren't big enough to require Aegir, a lot of the tasks which it does can also be automated using Drush, which is a command-line tool for managing a Drupal site.

Even if you feel Aegir is overkill, you should definitely use Drush - it will make your life a lot easier when it comes to deployment between your development and live versions and management thereafter.

As for version control: If you're writing any of your own code, then yes, you should be using version control. If you're simply using Drupal plus third-party modules, then you probably don't need it, since you're not in charge of the code anyway. But you might find it useful nonetheless, because there's always a chance you might find yourself needing to tweak a third party module (or even the core) to get things to work the way you need to, and at that point you will need version control, and it will help if you already have it set up.

You can't very easily do version control on your site content, because it's all in the Drupal database. You can do a certain amount by moving your site structure from database to code using the Features module, at which point it becomes possible to version control it in the same way as other code, but your actual content remains in the database.

To do version control on content, the main option you have is the Diff module, which allows the database to store multiple versions of page content, which can then be administered.

Hope that helps.


What are recommended modules or processes which support rating based comments or reviews? I am new to Drupal and I am planning a directory site where users can review and rate the service of a shop or company.

I'm thinking of something like this (taken from yelp.com):

Any recommended modules or processes which support such feature in Drupal 7, i.e. for rating based comments or reviews?

Rating

The VotingAPI module (available for both D6 and D7) offers a framework to developers of Drupal modules about voting and/or rating. It uses a standardized API and schema for storing, retrieving, and tabulating votes for Drupal content.

VotingAPI offers these key features:

Create/Retrieve/Update/Delete operations for voting data.
Whenever a vote is casted, it calculates the results and caches them. These calculations can either be the default calculations (average, total, etc), or they can be implemented via custom tallying functions.
Via its integration with the Actions module, it can trigger workflow steps whenever votes are casted and results are tallied, such as promoting a node to the front page, hiding a comment flagged as spam, or sending some eMail.
It integrates with the Views module, which allows for slice and dice of the content of a site based on user consensus. And tt provides functions to format vote data to display them to users.

Typical rating related modules with a stable release for D7:

Rate (D6 and D7).
Fivestar (D6 and D7).
Voting API Bayesian (D7).
Star Rating (D7, no VotingAPI dependency).
Raty (D7-beta2).

Views / Rules / Flag / Message

Everything above relates to "Rating" (or voting). Some more modules that you may want to consider (= add to the mix of modules you might want to consider):

The Flag module, which is typically combined with the Rules module also to create all sorts of interesting site features. If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters. There is a similar set of 8 video tutorials about the Flag module.
If you also add the Views module, you're already pretty close to a great mix of modules to create the site you're looking for. Maybe also review the set of 30 video tutorials about the Views module.
For more details about the Message module, refer to some interesting Use Cases detailed within its Community Documentation.


How to save multi date and time in node programmatically? I want to save multi Date value in a node programmatically.

$node->field_event_date['und'][0]['value'] =?;
$node->field_event_date['und'][0]['value2'] =?;

getting the below value after print the form_state

[field_event_date] => Array
                        (
                            [und] => Array
                                (
                                    [0] => Array
                                        (
                                            [show_todate] => 1
                                            [value] => Array
                                                (
                                                    [date] => 07/02/2015
                                                    [time] => 10:30AM
                                                )

                                            [value2] => Array
                                                (
                                                    [date] => 07/02/2015
                                                    [time] => 12:30PM
                                                )

                                        )

                                )

                        )

Getting error

$node->field_event_date['und'][0]['value'] =
    $form_state['input']['line_item_fields']['field_event_date']['und'][0]['value']['date'];

$node->field_event_date['und'][0]['value2'] = $form_state['input']['line_item_fields']['field_event_date']['und'][0]['value2']['date'];

But i need both date and time. I think i need to combine date and time and convert it into time stamp to save but do not understand how to combine and convert.

If converting the two is your problem following may help you

foreach ($form_state['values']['field_event_date']['und'] as $key=> $value) {
  $node->field_event_date['und'][$key]['value'] = strtotime($form_state['values']['field_event_date']['und'][$key]['value']['date'] . ' ' . $form_state['values']['field_event_date']['und'][$key]['value']['time'])
}

strtotime() should be good enough.

I am assuming you are doing node_save() some where.


How to redirect on Access Denied When getting a 403 error, Drupal is not redirecting to the URL configured in the Site Information settings. Instead, it keeps the URL in the address bar of the browser, uses the page template (page--XYZ.html.twig) for that same URL and only the content of the page ({{ page.content }}) reflects the URL I've configured in the site information settings.

Does anyone know how to get a full redirect to the configured 403 page?

Well, by now I just found that my question is technically wrong. Drupal is not supposed to do any redirect (HTTP 301/302) on access denied errors (HTTP 403). This is not how HTTP works (as mentioned by @Hudri in the comments).

On an access denied error, Drupal replaces the actual page content with the one from the "Default 403 (access denied) page" site setting. The URL being accessed is valid. It's just that we don't have the permission to see its contents.

I just figured what I was actually wanting to do, was telling Drupal not to use that page's regular template file (page--xyz.html.twig) on the case of an HTTP 403 error, but instead, to use a different one.

Found useful instructions on how to theme HTTP error pages here: https://www.axelerant.com/resources/team-blog/customizing-http-error-pages-in-drupal-8


Threaded comments pager ajaxified I require threaded comments with pager but instead of loading a new page when pager is clicked, I want the data to be loaded via ajax. There are 2 problems I have with page load -

Loading a new page itself
I have a number of contents with there comments on a single page and clicking a pager for any comments list takes me to a new page, hence a new page for all the comments lists on the page, not only the one I had clicked.

Any help is appreciated. Thanks.

install views module and create a new view with comments as base, block as output, and the actual node as context.
set it to use ajax, et voilà.

then - add this block to the content section and limit its visibilty to the corresponding content type.

to make sure the JS of views is added you have to add them manually. so in you template.php - add
function YOURTHEME_preprocess_page(&$vars, $hook) {
//Reload the javascript into the scripts. $vars['scripts'] = drupal_get_js(); } - may be even better to check the $vars if you're on the desired content type


How do I alter a language item link? I am looking to modify the default output of Drupal 8 of links in a certain situation, the language switcher. Ideally I want to be able to do that in a twig template and not have to produce a massive php file that overwwrites that whole link generation system and add a BIG if for the cases I need to overwrite.

I think the output layout should be controllable in the twig template similar to this answer (this answer outputs the same url for every languages)

I am using bootstrap as a base theme so i'd like to use the bootstrap markup for my links (btn btn-primary, dropdown)

Here is my code I am trying to make links--language-block.html.twig

{%- if links|length == 2 -%}
    {# show only alternate language button #}
    {%- for key, item in links -%}
        {%- if not item.attributes['#options']['set_active_class'] -%} {# <--- this is always true!? #}
            {{ item.link['#title'] }} {# #url is always the same what ever the language it is pointing to! #}
        {%- endif -%}
    {%- endfor -%}
{%- elseif links|length > 2  -%}
    {# show selected language in button and other languages in drop down #}
    <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">{{ selectedLanguage }}</button>

        {% for key, item in links %}
            {%- if not item.attributes['#options']['set_active_class'] -%} {# <--- this is always true!? #}

{{ item.link['#title'] }}

            {% endif %}
        {% endfor %}

{%- endif -%}

Anyone has an idea on how to do this?

Ok I found 2 ways to do that.

1. In a custom theme

You can alter variables in your my_theme.theme file. You need to figure out the name of the function you need. ex: my_theme_preprocess_twig_file(), in my case I needed my_theme_preprocess_links__language_block() You need to take the twig file name and replace all - for _.

my_theme.theme:

function my_theme_preprocess_links__language_block(&$variables) {
  $currentLanguageCode = \Drupal::languageManager()
    ->getCurrentLanguage()
    ->getId();
  // replace key of active language with 'activeLink'
  foreach ($variables['links'] as $i => $link) {
    /** @var \Drupal\language\Entity\ConfigurableLanguage $linkLanguage */
    $linkLanguage = $link['link']['#options']['language'];
    if ($currentLanguageCode == $linkLanguage->get('id')) {
      $variables['links']['activeLink'] = $link;
      unset($variables['links'][$i]);
    }
  }
  // if there is only 2 languages remove active one
  if (sizeof($variables['links']) == 2) {
    unset($variables['links']['activeLink']);
    // give class 'btn btn-primary' to alternate language
    /** @var \Drupal\Core\Url $alternate */
    $alternate = current($variables['links']);
    $alternate['link']['#options']['attributes']['class'][] = 'btn';
    $alternate['link']['#options']['attributes']['class'][] = 'btn-primary';
    $variables['links'] = [$alternate];
  }
}

2. In a custom module

You can also create a module that will change those same variables. There is a big difference in the values of the variables because this preprocess happened earlier in the flow. The name of the function is also quite different, ex: my_module_api_to_modify_alter(). In my case I needed to modify the language_switch_links from the language.api.php. You can find all alter function by searching for *.api.php files in drupal 8. Those are there as a reference for exactly that.

my_module.module:

function my_module_language_switch_links_alter(&$variables) {
  $currentLanguageCode = \Drupal::languageManager()
    ->getCurrentLanguage()
    ->getId();
  // replace key of active language with 'activeLink'
  foreach ($variables as $i => $link) {
    /** @var \Drupal\language\Entity\ConfigurableLanguage $linkLanguage */
    $linkLanguage = $link['language'];
    if ($currentLanguageCode == $linkLanguage->get('id')) {
      $variables['activeLink'] = $link;
      unset($variables[$i]);
    }
  }
  // if there is only 2 languages remove active one
  if (sizeof($variables) == 2) {
    unset($variables['activeLink']);
    // give class 'btn btn-primary' to alternate language
    /** @var \Drupal\Core\Url $alternate */
    $alternate = current($variables);
    $alternate['attributes']['class'][] = 'btn';
    $alternate['attributes']['class'][] = 'btn-primary';
    $variables = [$alternate];
  }
}

And my Twig template for both cases links--language-block.html.twig:

{% if links -%}
    {%- if links|length == 1 -%}
        {# show only alternate language button #}
        {{ (links|first).link }}
    {%- else -%}
        {# show selected language in button and other languages in drop down #}
        <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">{{ links['activeLink'].text }} </button>

            {% for key, item in links %}
                {% if key is not same as("activeLink") %}

{{ item.link }}

                {% endif %}
            {% endfor %}

    {%- endif -%}
{%- endif %}


Get yesterday's content with contextual filter in views block I have a view and I try to show only yesterday's content.
I add a contextual filter "Content: Created date".
If I select "Current Date" from "Provide default value" its works perfectly.
But I select "PHP Code" its not working whatever I write. I try a lot of format.

In this topic there is a solution but its not work either;

return date("d", strtotime("-1 day"));

How can I do that?

Try this one

Content: Post date (>= -1days)

Instead of this

return date("d", strtotime("-1 day"));


How do I flag and categorize Drupal Commerce related products? Given that there isn't a related products contrib module yet.

What is the canonical means (with priority of maintainability, developer experience) to flag related products and thus have them displayed in views ?

Would it include setting up content types with many different taxonomy vocabulary fields? Another product reference field?

The core taxonomy module offers a flexible system for sorting content. You can easily build views based on content type and taxonomy.


Does the cron using Drush must be setup locally or on the server for the production website I have been reading about the Drush cron and explanation that mentions in this documentation. Wondering do we add that crontab entry for drush locally or on the server where the website is for the production site? This confusion is because the article mentions drush aliases.

This is the crontab entry suggested

  10 * * * * /usr/bin/env
  PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
  COLUMNS=72 /usr/local/drush/drush --root=/path/to/your/drupalroot
  --uri=your.drupalsite.org --quiet cron

Here is the part that is confusing

  Specifying the Drupal site to run

  There are many ways to tell Drush which Drupal site to select for the
  active command, and any may be used here. The example uses the --root
  and --uri flags, but you could also use an alias record if you defined
  it in a global location, such as /etc/Drush/aliases.Drushrc.php.

Does it refer to aliases on my local or possible aliases on the server which may have dev, qa and other related sites.

TL;DR You should add it on the server!

Whereas it's possible to add it locally and use a remote alias to run it on the server it would be unreliable (requires your local to be online 24/7) and inefficient.

That said, you can also add "local" aliases on your server for convenience, to avoid adding the --root and --uri flags to the command in your crontab.

You can add any number of Drush aliases anywhere you want; so on your local machine you can have a "foo.local", "foo.staging" & "foo.prod" aliases for your site. And on your staging and production servers, you can simply add "foo.staging" and "foo.prod" so that you can access all of your environments in a cohesive and consistent manner.

The advantage is that if you define an alias "foo.prod" on the production server, you can replace your crontab command with this:
/usr/local/drush/drush @foo.prod --quiet cron

It's customary to have the same aliases set up across all servers for that very purpose.


How do I programmatically add and fill a field to taxonomy terms of a specific vocabulary? I want to programmatically do two things:

Replace the default multiline Description field of taxonomy term
with my own, plain text, single line field. I mean - to visually
replace - I understand this is an entity property and all I can do
is to hide it and create another, plain text field.
Populate the vocabulary through taxonomy_term_save() - putting the description strings into the newly created field.

Would anyone be kind and provide a skeleton of code to achieve it?

This is really two questions.

For the first, I would use hook_taxonomy_term_view to alter $build['description']['#markup'], like so:

function custom_taxonomy_term_view_alter(&$build) {
  $build['description']['#markup'] .= '<p> And this is more stuff.<p>';
}

For the second, taxonomy_term_save() can take a description field as described on the API docs page.


How can I sort a view based on a rewritten field? I have a view of a content type that contains two different date fields (one with date repeats and one multivalued single dates). Only one date field is filled out at any given time. In the view's display, I have combined the two fields by hiding the first date field and rewriting the second and including the replacement token of the first and second. Is there any way to now use the rewritten field to sort the view in ascending order based on this combined date field? It appears it sorts it based on the original value of the date field.

I have done my research and have only found old, somewhat-related, threads with dead-ends.

views sorting by rewritten field?

Table does not sort on rewritten field, but on original field

Views: custom field for sort criteria

Sort by global:custom text. Is it possible?

I was hoping there is a new or sneaky way of making this happen.

If you don't want to go for the module route, this is one alternative:

1) install Computed Field module
2) add a computed field to your content type
3) in the field settings, in the Computed code (PHP) textarea, you can access the field data.

Get your date fields in your current langugage to a variable.

$repeating_dates = field_get_items($entity_type, $entity, 'field_repeating_date_example');
$multidates = field_get_items($entity_type, $entity, 'field_multidate_example');

Your date values can now be found in

$repeating_dates[0]['value'],
$repeating_dates[1]['value'],
$repeating_dates[2]['value'], etc.

$multidates[0]['value'],
$multidates[1]['value'],
$multidates[2]['value'], etc.

Do whatever logic you need with your date fields and assign the result to

$entity_field[0]['value']

Now you have a sortable field you can use in views, but first you have to update all the nodes as the computed field will only be computed and saved to the database at node save. There are many ways to do this, one is using Views Bulk Operations, it gives you an option to re-save nodes at admin/content.


image optimize Issue I have installed S3 File System module, and all image files are served from AWS S3 bucket. The images served from S3 are not compressed. How to compress those images?

Following is the message I get when checking with page speed:

  Compressing
  https://example.s3-us-west-2.amazonaws.com/s3fs-public/test.jpg could
  save 22.4KiB (26% reduction).

When uploading images into Drupal, those are uploaded as it is and not compressed. To compress them you can check Image Optimize (or ImageAPI Optimize) Module.

Another solution is to add custom code in your custom module, which will compress image before a record is inserted into file_managed table, check code below:

/**
 * Implements hook_file_presave().
 */
function [MODULE_NAME]_file_presave($file) {
  if (!empty($file->filemime) && (strpos('image', $file->filemime) >= 0)) {
    $compressed = _[MODULE_NAME]_compress_image($file->uri, $file->uri, 75);
  }
}

/**
 * Helper function to compress images while uploading.
 *
 * @param string $source_url
 *   Source image URL.
 *
 * @param string $destination_url
 *   Destination image URL.
 *
 * @param string $quality
 *   Percentage of Image quality to compress.
 */
function _[MODULE_NAME]_compress_image($source_url, $destination_url, $quality) {
  $source_url = drupal_realpath($source_url);
  $destination_url = drupal_realpath($destination_url);

  $info = getimagesize($source_url);

  if ($info['mime'] == 'image/jpeg') {
    $image = imagecreatefromjpeg($source_url);
  }
  elseif ($info['mime'] == 'image/gif') {
    $image = imagecreatefromgif($source_url);
  }
  elseif ($info['mime'] == 'image/png') {
    $image = imagecreatefrompng($source_url);
  }
  else {
    return FALSE;
  }

  //save file
  imagejpeg($image, $destination_url, $quality);

  //return destination file
  return $destination_url;
}

NOTE: Change [MODULE_NAME] with your module name.


How to configure blocks per node? I'd like to build a Drupal 7 module that generates a block which contains (along with some static HTML to be used as template for a JavaScript library) a node-specific value to be passed on to a web service. (The web service will return relevant data for the contents of the node.)

How should a block receive node-specific data? Module configuration seems to be global, and blocks cannot be configured individually.

Should I modify the main content-type of the node by adding this "node-specific data" as an extra field even if this value is only used in my module?

Use the Block API to add the blocks

i.e:

hook_block_info
hook_block_view

Use menu_get_object to get the node object for that page.

e.g:

function mymodule_block_view($delta){
  $block = array();
  switch($delta){
    case 'my_delta':
     if ($node = menu_get_object('node') && $node->type == 'my_type') {
       $block['subject'] = t('Example block on %node', array('%node' => $node->title));
       $block['content'] = render(field_view_field('node', $node, 'body')); // for example
     }
    break;
  }
  return $block;
}


How to enable "Menu primary tabs"? I want to enable Menu Primary tabs in my site, but I can't find how to enable them.
Any suggestions please?

Under Menus > Primary Links > (select items to enable by checking the menu items)
Check to ensure primary links are specified in the blocks by visiting 'Blocks' configuration.

Is this what you're looking for?


Apply custom css class while rendering an image Here I want to add an attribute for custom css class, is this possible using field_view_value, field_menu_image is my image's machine name

$image = field_get_items('node',node_load($nid, NULL, TRUE), 'field_menu_image');
$output=field_view_value('node', node_load($nid, NULL, TRUE), 'field_menu_image',$image[0]);
print render ($output);

field_view_value returns a renderable array so you should be able to just do.

$image = field_get_items('node',node_load($nid, NULL, TRUE), 'field_menu_image');
$output=field_view_value('node', node_load($nid, NULL, TRUE), 'field_menu_image',$image[0]);
$output['#item']["attributes"]["class"] = array('test');
print render ($output);


How can I stop Views from eating my query strings when rewriting a link? I have a view and I am trying to rewrite the links by appending a query string.

[name_1] is the name of the location.  The various values for age[] are the taxonomy term IDs for an exposed filter, and friends is a profile field.

Under Rewrite results, I have checked Output this field as a link.  This is my link:

location/[name_1]?age[]=27&age[]=31&age[]=35&age[]=39&age[]=43&age[]=44&friends=1

When I cut and paste the query string into the URL bar, it works fine.  However, when I tell views to rewrite the string I get URLs that look like this:

location/mexico?friends=1&age[]=44

This gives me no results and a broken view.

It appears that the query strings are processed in reverse, and it only accepts the first value for age[]-- even though when I type the same thing into the URL bar it is OK.

I tried replacing the symbols in the rewriting string like this:

location/[name_1]age%5B%5D=27&age%5B%5D=31&age%5B%5D=35&age%5B%5D=39&age%5B%5D=43&age%5B%5D=44&friends=1

Now, when I access the view, I no longer get an error, but none of the age (taxonomy term) checkboxes are checked and the URL looks like this:

http://localhost:8888/en/location/mexico?age%255b%255d=44&friends=1

So, clearly most of the age[] values are still disappearing for some reason.

How can I rewrite the query string so that views outputs it properly?

EDIT: According to Jimajamma's comment, D6 Views suggests using %5B%5D, as I have already tried (I'm on D7).  &#91;&#93; didn't work for me either (this combo doesn't even work in the URL bar).  Perhaps this is a bug in Views?

EDIT 2: As per the answers, this appears to be a bug in Drupal Core/Views, not a configuration error.  So I attempted to avoid using Views rewrite results output as a link feature and instead just rewrite results and code the link in HTML.

The only problem with this approach is that some of the terms have spaces in their names, and I was using the convert spaces to dashes option provided by the output as a link setting to get around this.  So now the links for terms that have no spaces work properly, but the links for terms with spaces are broken...

Issue is not with views. What views does is it calls drupal_get_query_array to build the query array. And as of now drupal_get_query_array does not support same name array in the query params. All it does is just explodes the query and saves it as follows;

$result[$param[0]] = isset($param[1]) ? rawurldecode($param[1]) : '';

So if you see the see it is going to be overridden and it is just going to store

array ('age' => 44, 'friends' => 1)

I have created a ticket and reported this issue and attached a patch as well at https://drupal.org/node/2023815

The same patch should work for 7.x as well.

Alternatives

So Views php / Custom module looks like a good alternative without hacking the core.


Basic question with respect to Drupal form API I am learning the Drupal Form API. I am new to HTML and PHP also.
I read in a book how to define a form in Drupal, where they used the following example:

/**
* Define a form.
*/
function formexample_nameform() {
  $form['user_name'] = array(
    '#title' => t('Your Name'),
    '#type' => 'textfield',
    '#description' => t('Please enter your name.'),
  );
}

What will the HTML equivalent of above example be?
Similarly, to validate the form they did it as follows:

/**
 * Validate the form.
 */
function formexample_nameform_validate($form, &$form_state) {
  if ($form_state['values']['user_name'] == 'King Kong') {
    // We notify the form API that this field has failed validation.
    form_set_error('user_name',t('King Kong is not allowed to use this form.'));
  }
}

What will be HTML equivalent of both of these functions?

The HTML produced from the first function (the form builder) can be roughly seen checking the code for the theme functions, which are at least two: theme_textfield(), and theme_form(). The exact output can change basing on the theme being used, and third-party modules installed on the site.

For the validation handler, the function that adds the class for form fields with a validation error is _form_set_error(), while the list of the validation error messages are set with form_set_error(), which uses the following snippet:

  if ($message) {
    drupal_set_message($message, 'error');
  }

The messages that are set with drupal_set_message() are then output with theme_status_messages().

Also in this case, the real output depends from the theme being used, and from other modules installed on the Drupal site; both can alter the output used for the rendering.


Why does my admin menu link for my custom module not get created? I am creating a module in Drupal 7. The module is working well now, but I doesn't create an admin menu link.

I used the following code:

<?php
function question_mark_menu() {
    $items = array();

    $items['admin/question-mark'] = array(
        'title' => 'Question mark',
        'description' => 'Manage your question mark',
        'page callback' => 'question_mark_page',
        'access arguments' => array('administer question mark'),
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}
?>

I tried to clear my cache but nothing works.

What is wrong in my code?

The path for the configuration menu is at admin/config, so try this:

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

  $items['admin/config/question-mark'] = array(
    'title' => 'Question mark',
    'description' => 'Manage your question mark',
    'page callback' => 'question_mark_page',
    'access arguments' => array('administer question mark'),
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

Also, make sure your user has the 'administer question mark' permission that you have specified.


Multilanguage page title I've created a multilingual drupal page (English as default and german).
On the english page the title works correctly, but on the german page the title is still Drupal (I changed it in the settings and it works in my browser tab header)

How can I make it work?

supermew

Here are a few pointers which might help:

If you are talking about the name of your site, then please use the Admin > Configuration > System > Site information page to configure it - once in English and once in German.
If you are talking about a page node you created, then:

Make sure that you enable translations for the title property from content translation settings.
Make sure you use the Translate tab on the node to input the German title for your page.

Having done everything above, if you still do not see the German title on the German version of your page, try clearing cache from the Configuration > Development > Performance page.

References:

https://www.drupal.org/docs/8/multilingual/translating-content


send fields in a email I'm fairly new to D7 and I don't know where to start. I have a "Event" CT(ContentType) with many fields in it. Dates, prices, text, html description.

I need to put some fields in a plaintext email and send it to a specific adress. Thats the data export for a ticket system. Some of these fields need to be reformatted. Date => Timestamp, MD5 Hash etc. Textblob with HTML Tags => plaintext, etc.

Also it needs to be saved. So the User can see if its already submitted.

I'm a bit overwhelmed where to start. I think a module and drupal_mail() is the right way to start. How would you do it (General direction)?

Thx in advance
T

The Email Example in the Examples Project should be just the thing for you.


Login form and registration form not properly displayed I am using D7, with the help of Modal form module i am trying to display the login and registration form in a overlay effect. When the user visits /user/register or /user/login i get the overlay but not the form. I have attached a snapshot for further reference.

Where am i wrong in displaying this form?

Thanks.

Modal forms (with ctools)

  Supported forms Log in
  (modal_forms/nojs/user/login) Request new password
  (modal_forms/nojs/user/password) Create new account
  (modal_forms/nojs/user/register) Contact
  (modal_forms/nojs/user/contact)

It is also possible to build links manually.

    Modal Login
    Modal Login


How to theme the page template for search results I want to change the page template when displaying search results. This seems straigh forward when dealing with a content type, but what is the content type for "search results".

E.g. I'll like to use something like page--search_results.tpl.php but I'm not sure of the correct name.

Note, I'm happy with the formatted output of the result items, so I assume I wouldn't be changing the templates under drupal/modules/search...

Thanks

You can use a template, eg, page--search.tpl.php which would match the path to search and anything under it, eg, search/node/term, or you could create one called page--search-node.tpl.php which wouldn't match just the search page itself, but only search results from nodes, or you could use a template suggestion inside a preprocess_page() hook, eg, something like

mymoduleortheme_preprocess_page(&vars) {

  if (arg(0)=='search' && arg(1) && arg(2)) { // we are somewhere down in search/node/term or similar
    $vars['theme_hook_suggestions'][] = 'page_my_template_for_search_results';
  }
}

and then create a template file page-my-template-for-search-results.tpl.php.

In any case, http://drupal.org/node/1089656 has some great documentation on template suggestions in D7.


Modification of HTML mail template I am using HTML Mail module. I have created an html email template specific to my form(webform) in the template folder of my theme directory. My form name is newsletter and the template name is htmlmail--webform--newsletter_email.html.twig

I want to override the email body based on a particular language. But my problem is that hook_mail_alter doesn't work in my case.

Drupal API documentation for  hook_mail_alter says that hook_mail_alter() allows modification of email messages created and sent with MailManagerInterface->mail().

Any help?

The hook hook_mail_alter() should work in this case.

Have you double checked if your module is activated and you have cleared your cache after adding the hook?

Also i am not sure if your template will work, because normally all templates are working with dashes instead of underscores.


How can I grant anonymous users access to the locale language select form without hacking core? I am attempting to override the user registration from at user/register to allow users to select their own language upon login.

Based on this helpful answer, I came up with this override:

function hook_form_user_register_form_alter(&$form, &$form_state, $form_id) {

  $form['locale']['language'] = array(
    '#type' => (count($names) <= 5 ? 'radios' : 'select'),
    '#title' => t('Language'),
    '#default_value' => $user_preferred_language->language,
    '#options' => $names,
    '#description' => $mode ? t("This account's default language for e-mails, and preferred language for site presentation.") : t("This account's default language for e-mails."),
  );

However, it doesn't work because of the following code in locale.module:

  $form['locale'] = array(
    '#type' => 'fieldset',
    '#title' => t('Language settings'),
    '#weight' => 1,
    '#access' => ($form['#user_category'] == 'account' || ($form['#user_category'] == 'register' && user_access('administer users'))),
  );

Simply deleting && user_access('administer users') from locale.module and clearing the cache makes it work, but if I do that I'm hacking core.

How can I remove the bit about && user_access('administer users') without hacking core?

You should be able to just replace the #access property for the element added by the locale module in your form alter:

function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  // Use exactly the same access logic as the original,
  // without checking for the 'administer users' permission
  $form['locale']['#access'] = ($form['#user_category'] == 'account' || ($form['#user_category'] == 'register'));
}

That's essentially the same as taking the && user_access('administer users') part out of the core file.

All you need to make sure of is that your module hooks are run after those of the locale module (so the element actually exists when you try to alter it), which you can see how to do here.


How to limit direct access to URLs of nodes that are shown in a video gallery created with Views? I have made a video gallery using Views. But I only want that the page accessible to public and prevent access to each of the videos individually.

The videos had to be created as a type of content, so all of them have accessible ULRs like /content/video-1, etc.

Try content access module and prevent access to video content individually( or also you can set access to it for you desire roles )

  This module allows you to manage permissions for content types by role
  and author. It allows you to specifiy custom view, edit and delete
  permissions for each content type. Optionally you can enable per
  content access settings, so you can customize the access for each
  content node.

Also you can use Node View Permissions module, but I suggest use Content access module.

(if you want work with drupal for future is better getting involve with this useful modules)


How to force a theme to use a sitewide custom menu Ok so Im coming from wordpress where I could just hook a menu into the header of every page and create my own custom menu. I'm trying to do the same with drupal but it's so confusing! Im building my own custom theme so if I can start small with this question. How can I insert a sitewide menu with a custom template onto every page of the site. Something like this.

<div id="top-menu">
   <---hooked in functions from the template.php--->
</div>

How can I insert a sitewide menu?

You can use Context to insert menu blocks into regions.
Contexts can be set to be site wide.
Make sure that your theme supports the region into which you are inserting the menu block.  The region should be defined both your theme's .info file and also it's relevant templates (generally the page template).

Making a menu with a custom template

You can use the devel_themer module to sniff what templates you can implement to override the menu's default theming.


How to print $banner; without ? After moving some animation code from page-front.tpl.php to a block, the paging animation is broken.

Good:

Broken:

The slide code is:

 Event One

 Event Two

 Event Three

      1
      2
      3

When I move the above code into a block and output via print $banner;, there is some extra
 which breaks the animations:

 Event One

 Event Two

 Event Three

      1
      2
      3

Is it possible to force print $banner; to output the raw content of a block, without the
 and
?

Update: Changes made to work for Drupal 6 as your tag states 6.

It looks like the system is using the standard block.tpl.php with this code:

<div id="block-<?php print $block->module .'-'. $block->delta; ?>" class="clear-block block block-<?php print $block->module ?>">

<?php if (!empty($block->subject)): ?>

<?php print $block->subject ?>

<?php endif;?>

<?php print $block->content ?>

What you need to do is add another block template file, and take away the
 tags you want to eliminate.  To do this, add a template named block-module-delta.tpl.php to your active theme.

For block-module-delta.tpl.php

Module = the module that's creating the block (views, block, etc)
Delta = the internal id assigned to the block

So if the block module made the block, and it has an id of 4, you'd name the template file block-block-4.tpl.php, and you'd put this PHP/HTML in the template file:

<?php if (!empty($block->subject)): ?>

<?php print $block->subject ?>

<?php endif;?>

<?php print $block->content ?>

Notice how I eliminated the
 and
 from the template.


How can I check the changes for the fields at form alter submit? I am using hook_form_alter() with custom submit handler ().
At submit I want to check if there is any change in the content except node->expire then my custom code will run.

but at $form_state['value'] I am also getting: nid, vid, uid, created changed etc.
and I have field type as taxonomy term reference and media files.

I do not want to  hard-code the fields name as admin may add new fields later on.

Try comparing both $form_state[input] and $form_state['values'] .

After that check both values using the key's in foreach loop and compare both values, if changed then do your things there.


How do I disable caching for the Forum module or, alternatively, how do I fix caching? I use the normal standard Drupal Forum module with a clean Drupal 8 installation. After I have installed it, I have a problem where "2 new posts" shows for all users. In other words, the /forum page is caching and showing the cached page of one user for the other user.

So I have two options

Disable caching for /forum <--- I don't mind doing this for now, as there aren't many users at the moment so I have time to fix this properly later.
Figure out why this page is caching the way it is. As mentioned, I am using a clean installation with hardly any confirm and this still happens.

Can someone confirm if the /forum page normally does this or if something is probably wrong with my installation? Or maybe I'm missing some setting? Or maybe caching is meant to be disabled for this to work?

Any help would be greatly appreciated!

This documentation is the most suitable for your query: https://www.drupal.org/docs/8/api/cache-api/cache-contexts

Please learn all the details on that page and the other associated page. This may resolve your issue.

Thank you.


Is there any way to set a node to be shown in 2 menus? I have a node "my-node" which I set to be shown in the Main Menu so far so good.

I created another menu: "My Menu".

Is there any way to show my-node in both menu: Main Menu and My Menu

If I edit the node and go under Menu settings it allows me to choose just 1 Parent item

Use the Multiple Node Menu module

  This module modifies the "Menu settings" in standard node editing form
  to allow managing multiple menu links to a node.


What are the replacement patterns or tokens for Profile2 URL of a particular user? I just need to know how to key in token replacements for any given users different profiles. In my projects a user can have multiple profiles associated with the account. I am just having problems with tokens on how to locate or recreate those urls.

Try like this

First Install Pathauto Module.
Login in drupal as administrator, and goto Configuration. Under 'SEARCH AND METADATA' select 'URL aliases'.
Select 'Pattern' tab and goto 'USER PATHS' and click on 'REPLACEMENT PATTERNS' a list will appear.
Select 'Users' and again some more option will be displayed, select 'name' and the 'pattern for user account page paths should be displayed as '[user:name]' and save it.
In the same window 'Bulk update' tab and check mark the User Paths and click Update.

The following output will be http://example.com/username.


Implementing Google CSE Results Code I'm trying to implement the Google CSE Search Results code on a page that I created called search-results. When I implement the code using CKEditor (PHP mode) and save the page, the code does not show up when the page is rendered?

I was able to enter the Search box code no problem but I cannot seem to get the search results code to load on a page? I created a static html page and it works fine but will not work when I create the page in CKEditor. I also tried creating a block but this did not work?

How can I get the Google CSE Search results code snippet in a Drupal page? I'm not interested in using any of the Drupal modules for CSE as I don't like the way they render the results.

You should be using Google Custom Search Engine Module instead of embedding the code. Using this module would give you better integration option.

Additional Info: Avoid using PHP Filter as its creates security risk.


performance: rule set or triggered rules? I need to create some rules like "when create photo, when create video, when create story" but all use the same Event "after content is saved"...

so, what's the best way? a rule that trigger a rule set with various rules or varios indepedent triggered rules?

i.e:

RULE SET

rule (when create content) >
    event (after content is saved) >
        set (set: when create content) >
            rule (when create photo) >
                if:
                do:
                    rule (when create video) >
                        if:
                        do:
                    rule (when create story) >
                        if:
                        do:
                    rule (when create page) >
                        if:
                        do:
                    rule (when create product) >
                        if:
                        do:

total:

1 set
6 rules
1 event

TRIGGERED RULES

Rule (when create photo) >
    Event (after content is saved) >
        if:
        do:

Rule (when create video) >
    Event (after content is saved) >
        if:
        do:

Rule (when create story) >
    Event (after content is saved) >
        if:
        do:

Rule (when create page) >
    Event (after content is saved) >
        if:
        do:

Rule (when create product) >
    Event (after content is saved) >
        if:
        do:

total:

5 rules
5 events

thanks.

I believe the performance different is marginal, so I would chose the most maintainable.

Anyways in regards to performance my bet would be on the last option. Events function pretty much like a SQL where clause, so having more events doesn't hurt performance in itself. The number of rules that has to be fetched from the database, and initialized does effect performance, along with the number of queries that need to be executed.

So Rules will (most like) in the first case be running two queries. One to get the rule set based in the event and one to get the 5 rules in the set. It will need to instantiate 6 rules classes.

In the second case, rules will run a sigle query and only need to instantiate 5 rules classes.

So with fewer queries and rules classes that need to be instantiated the last version should be the most performance optimized. I doubt that you actually will be able to measure this though.


How to restrict file access based on file path under private directory? I have a list of files under  sites/default/files/private/abcde/manuals/.

I want to add restriction to the files based on certain logic which I can add in the code in a hook.
The logic would be based on a parameter set in by the admin.
So if the value  set to allow in the admin settings form , I would like to give access to view or download files under 'sites/default/files/private/abcde/manuals/' else would like to prevent user from accessing it.

Requests to files in the private file directory are routed through Drupal and access logic for these requests can be added by implementing hook_file_download.
The only argument to that hook implementation is $uri, which is the URI to the file. Using string comparison to see if you want to act upon this request should get you what you need.

Quoting the docs:

  If the user does not have permission to access the file, return -1. If the user has permission, return an array with the appropriate headers. If the file is not controlled by the current module, the return value should be NULL.