Asking a branching series of questions I want to be able to ask users a question, and, depending on their answer, go to some other question. Webforms does not handle this well, since it seems to assume that the user answers most of the questions. I'm looking for something like

What price range do you want?

If between $100 and $200, go to question 2
If between $200 and $300, go to question 3
If between $300 and $400, go to question 4

And so on.

At the end, I need to be able to see all of their answers in order to perform a
DB query, so their responses will have to be "accumulated" as they go. I don't
strictly need to have their answers stored in the DB, but it would be nice. I'm
fine with programming in a hackish special case with hardcoded targets, but a
clicky-button interface would be preferable, if such a module exists.

I feel like there should be some relatively-easy way of doing this, perhaps with
the Form API and fields on nodes, but I can't quite put my finger on how it
would be done.

Look at webform conditional or update your webform to >4.0-alpha2.

I have done a 2-way or 3-way branch on a form with a few sub-pages of questions for each branch. It's kind of a pain but its very doable.

Webform results will show you only the answers they had to complete depending on conditions and validations.


How to merge posts from 5 different website and import one post to drupal by feeds I want to create a music reference website With drupal 7.So explain my diagram and want to help me .

I specified 5 other music website that give direct download link to users.in other 5 sites musics post with a title + description + download links.such as all other websites that post download music or software.
I want to take ONE post Title of these websites + ALL direct links and import to drupal .So for every imported music post I have a Title + 5 download direct link from 5 defferent website.So user can Go to my site and download A music from 5 download link from 5 defferent sites.

1- I can give Titles of new posts from feed (rss) of these sites.

2- How Can I merge 5 titles of these sites to One title (equivalent music titles) - for example titles of one website post is "free download of music from SINGER called SONGNAME" .
This Title take and other 4 sites title merge or ignore Then Download links Attached (link url ONLY) to same Post.

3- I want to import and show only URL of Download links to user.without upload it to drupal or filefield modules.only url.no file.

please Help me.how can I do it?
I Worked with feeds module previously.

1) Create one content type with title and download file link with unlimited or five number of values can be added.

2) Get the fed from 5 sites for one particular title and create the node respective title and fill the 5 respective download link.


different sidebars for different taxonomy vocabularies I have few blocks I would like to show in sidebar of term page but not for all taxonomy term, only for a certain vocabulary. I can write taxonomy/term/* but it will appear the block on all term pages. Is there a way to limit it by certain vocabulary?

If you have pathauto installed then go to the admin/config/search/path/patterns (You find this when in the URL Aliases in the Admin, There would we tab named as Patters)

There you can define a pattern for each vocabulary. Set different url patterns for each of the vocabulary and then you should be able to use than in the block configuration.

Please note that you would have to do bulk update on taxonomy before the urls can take effect on existing terms.

OR

You could use the context module with has much more control over what to display. You can create a context of the type Taxonomy Term and select the vocabularies you want the block to be shown when that condition is true display the required blocks.


Include custom node id when POST'ing data through the REST API Is it possible to include a custom node id when POST'ing a node using the REST API? Knowing the node id in advance makes it easier to update the nodes in a future stage.

I think the default REST services don't allow that. You could implement yor own. It would need logic that prevents that existing nodes are overwritten exactly.


Link existing social media accounts to drupal account Both upon registration and/or user editing later on, how could one give the user the ability to link his acccount with a plethora of social networks such as Facebook, LinkedIn, Skype, Google+, Twitter, etc?

I am not looking for an oAuth solution to (just) log in or register with one of the afforementioned accounts instead of a standart drupal one, I am looking for a way to give the user the ability to log in and/or register with either one of those accounts.

Is that technically possible? If yes, is there a one-in-all solution modulewise?

EDIT: to give some extra clarity, the ability to link your social networks' account(s) is a requirement upon registration too. Something like a "field-like" behaviour that will somehow store the connection with the social network account. Kinda blunt but you get the idea.

May be you are looking for this module. It supports many providers for register and login integration.

Basic version is free. More details check below link!

http://janrain.com/products/engage/engage-pricing/


How to customize the page /node/add? On Drupal 8, there is a page on /node/add. I want to customize this page by replacing the links with buttons, but I have not found a template to do that.

I have also enabled the debug mode, but there is no template suggestion.

How do I customize the page?

Ajouter du contenu

Annonce

Article

Discussion

Recette

Forms are manipulated in Drupal 8 predominantly by using services, twig templates and yaml files, rather than hooks. Hooks are still used, but the code in the hooks is limited in comparison with Drupal 7.

On the other hand, new D8 concepts such as Services and Event Subscribers have become much more important.

Here's a good tutorial showing how to alter the Drupal 8 login form:

https://www.foreach.be/blog/how-manipulate-forms-drupal-8

Follow the steps in the tutorial to create a simple form_overwrite module.

When you get to the step where you create the src/Routing/RouteSubscriber.php file, you'll diverge slightly from the tutorial.

Instead of altering the routeSubscriber for user.login, you'll want to alter the one for node.add:

<?php

/**
 * @file
 * Contains \Drupal\form_overwrite\Routing\RouteSubscriber.
 */

namespace Drupal\form_overwrite\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {
  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // This is the one from the linked article
    if ($route = $collection->get('user.login')) {
      $route->setDefault('_form', '\Drupal\form_overwrite\Form\NewUserLoginForm');
    }
    // This is the one you want to write
    if ($route = $collection->get('node.add')) {
      $route->setDefault('_form', '\Drupal\form_overwrite\Form\NewNodeAddForm');
    }
  }
}

Armed with this knowledge, you should be able to adapt the linked tutorial to suit your needs. Good luck!


Importing content to a content type with images and associated data I'm trying to import images with ALT text and tooltip text into Drupal for a content type.

I'm using Feeds and Feeds Tamper to import the rest of my content right now, like so:
http://learningwithsage.com/wp/?p=212

And here's a technique for importing just the images:
https://www.drupal.org/node/1851322

But I'm still unsure how to do the tooltips and ALT Fields for the images.

Anyone?

In Drupal content is store in Databases (SQL) this your text and any link that you inside your content. Images are files that can be call from your content, module or theme.

Tooltips is mainly a front-end work, this is part of the theme or a module. So you do not necessary import from the content from your another framework (or website). You added a module or a theme that support Tooltips.

Here are few modules for Tooltips:

qTip
BeautyTips
Field Tooltips
Tipsy

You should pick one of these module and you should be good to go.


How do I render contextual links for blocks I render in my code? I loaded a block subject and content with module_invoke() and used render() for rendering them. I want to use contextual links for this block. How can I render them too?

This is the code I am using insde the page--front.tpl.php template.

$block = module_invoke('block', 'block_view', '4);
print render($block);

What code should I instead use?

$block = block_load('module', 'delta');
print drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));

Too bad we have to use private functions from the block module (_*()) to achieve this.


Toggling view modes of Views results with Display Suite I asked a similar question about a month or so ago, and the answer was to use the Views Modes module.  That module required the PURL module.  The problem is the PURL module leaves parameters on your URL all over the site, and have not figured out a way to turn it off.  Others have posted a support issue and it goes ignored.

So, I'm back to the drawing board.  I have nodes that are rendered, using view modes defined in Display Suite.  Is there a way I can toggle between view modes in Views?  What I'm really trying to do is provide a bunch of filter checkboxes, along with the ability to toggle between view modes, but I need to find a solution for the view modes first.

Is there a module that makes this easy, or do I need to write some code.  If I do need to write some code, how should I approach it?

Solution that I use sometimes.

Create a content type with one or more multiple-value block reference fields.
This is like a "cheap" version of panels..
Create your views displays as blocks. One for each version.
Create a custom module to define a block that acts as the "switcher" between the two. Put some dummy content for now.
Create two nodes with the block reference.

One that has the switcher and the Views display A.
One that has the switcher and the Views display B.

Set url aliases for both nodes.
Flesh out the "switcher" block. E.g. make it keep the url query parameters. Make it look different depending on whether you are on A or B.
If you want, you can have a separate block for the exposed filters, that you also add via the blockreference.
Use Display suite or some other way to arrange the different blocks on the page.

The benefit of block reference + ds over theme regions is that you don't spam your theme regions with one-page-only blocks.


Should I use the Workbench Access module to implement the workflow we have in mind? I am new to Drupal altogether and have a question about a site i was asked to work on. We think that Workbench Access will solve our problem but we have not yet figured out how to make it work the way we want.

I have a large site and I have the users setup, and Roles setup, etc. But what I want to do is let users edit submit edits (for approval) on only one portion of the site (the staff portion to edit/update their own info). I also want an email to be sent (to me) for letting me know they submitted a "needs review" request if possible.

I know this might be a lot to go over but I would really love any help or a good walk through for this.

The Workbench Access module seems to only partially cover your needs.
If it was up to me to implement a solution for the challenge you're trying to solve, I'd go for another approach, as further detailed below.

Have a look at my answers to either of these questions:

How to implement a multi step approval with webforms/entityforms based on form components?
How can I allow anonymous visitors to submit content?

These answers explain how you can implement a workflow that is pretty (though not exactly) similar to what you are looking for.

To do so, it "only" requires you to use these modules (and regular content types):

Rules.
Node Convert.
Flag.
Content Access.

And by using such approach, it does not require modules like "Webform" or "Workbench" (modules that are typically involved for these kinds of workfows).


Problem with adding Views - they cannot be saved I have problem with creating new views (or clone old ones). All process is doing well, I choose my filtres etc; but when I'm trying to save it's an error - and they don't show in the views list (even if it's said that it "has been saved"). I've already tried several times but it doesn't work. I dont know why - before I didn't have this problem...

Have you tried running update.php? Or try clearing the Drupal cache which you can do quickly with drush using drush cc all.

I find this is always a good place to start.


Related nodes by taxonomy term in a view block of drupal7 I want to show related nodes to the current node in a block using taxonomy terms.
In my site say x is my taxonomy vocabulary and x1,x2,x3,x4,x5,x6 and x7 are the taxonomy terms under it. A node could be tagged with any of these taxonomy terms.
Say node T is tagged with x2 and x3.
node W tagged with x3, x1 and x5.
node c tagged with x2 and x6.
node R tagged with x2 and x7.
F tagged with x4,x6.
H tagged with X2,x5.
Now when the node T is displayed I want items having any of the taxonomy terms similar to the current node i.e. X2 or x3 but the priority should be x2 i.e. list all the related nodes with x2 as tag first and then only with x3. so in the above case i need related nodes in the order C R H W? How is it possible by using views in drupal 7?

There will be a significant amount of customization (in the form of a module) to get this done through views. I've created a sandbox module that you can install to get things working and so you can play around with it (see views.api.php in the views module).

Once enabled you should find a new contextual filter value called "The node whose taxonomies you want to relate". This contextual filter default will take the current node ID and return nids of nodes that share the same terms in vocabularies that you select. Therefore, please set the view display as a block.

If you need to know how to group by term using views, please see this answer.


How to manage a field collection in a table? I have a field collection called My links.

My links contains these fields:

Organization Name (Text Field)
Description (Long text with summary)
Link Url (Link Field)

This is a pain to manage because I need to scroll down really often since I have at least 45 links in there.

Is there a way to manage these link in a table format?

Thanks a lot

Yes, with the Field Collection Table module:

  Provides a table formatter for the Field Collection module.


Drupal services add location I am trying to add a location to a node using Drupal services.

This is the JSON sent to the service

{
   "node":{
      "type":"restaurant",
      "title":"Restaurant from JSON API",
      "field_restaurant_location ":{
         "und":{
            "locpick":{
               "user_latitude":"22.38131",
               "user_longitude":"114.168639"
            }
         }
      }
   }
}

I can not get it to save the location to the node. Any ideas ?

Should anyone else have this problem, the correct answer is:

{
    "node": {
        "field_restaurant_location": {
            "und": [
                {
                    "country": "us",
                    "latitude": "-26.2041",
                    "locpick": {
                        "user_latitude": "-26.2041",
                        "user_longitude": "28.0473"
                    },
                    "longitude": "28.0473"
                }
            ]
        },
        "title": "Restaurant from JSON API",
        "type": "restaurant"
    }
}


When creating a 'status' entry with the statuses module, stop it from creating a double post Am using statuses 7.x-1.0-unstable4+43-dev. I've spoken to some of the "maintainers" on the drupal.org site and none have been able to answer this question, blamed another module or have ignored my question. So I'm taking this question to the greatest site on earth, Stack Exchange!.

When I create a 'status' from a user profile page. It create 1 entry in the DB but displays a duplicate of the entry on the user page. According to the one of the maintainers, its an issues with views. I've tried to tinker with views to no avail. I was also told it was a problem with one of the contrib submodules... The problem with that is.. I ONLY HAVE THE MAIN MODULE ENABLED! So, do you gurus have any idea why this would create a duplicate display of a single entry in statuses?

Gosh, never posted here before, but the rules seem kind of draconian. I don't have a fix for this, but I thought I could relate that I've had the exact same problem and note some of the things I've tried.

I notice than when I look at the View under "Preview" and specify a user_id, it works perfectly. My hope is that IceCreamYou (the main contributor, who is particularly arrogant, when you read his responses to questions) will stumble upon this and a lightbulb will go off in his head.

Otherwise, my suggestion would be to intercept the SQL (you can see it with the Devel module), try to roll your own (with the inclusion of the DISTINCT keyword, which when I add it to the query generated removes the duplicates).

Note that the code for the "statuses" view is embedded in the Statuses module, so you'll have to extract it from there first.

If this sort of post is against the rules, feel free to delete it :-)


Cannot edit new View Since I updated to 8.6.10, I can no longer edit a new view. I can create a view but  when I go to the main interface after clicking Save & Edit, nothings works. No matter what I click on, aside from the brief display of turning wheel, nothing happens.

I have checked the log and no error messages and strangely, existing views are working well.

Update:
Error message from DevTool console shown below

If the views are working but you cannot edit, then could something wrong with the views_ui module.

There are two differend modules:

Views: for views functionality
Views_ui: for changing views with the web browser at admin section.

Views do not need the Views-ui module activated. This is only for changing existing views. Therefore you can try to deactivate views_ui module and reinstall it.

(Cache clearing is always a good idea, but I think this have you done.)


How to share content and files with other users within the site (not in facebook or other social media)? Users would like to be able to share content with other users within the site (not on Facebook or any other social media).

For example, if I read a blog that I like and think my colleague would be interested I could click 'SHARE' and send it to another user's profile or work e-mail address. Or tag someone? This would require a notification to the user that they have shared or tagged in something.

It would be great to be able to do this with blog posts, files, photos, and videos. "

Besides the custom approach identified above, you may also want to look into using the Forward module.

https://www.drupal.org/project/forward

It includes some basic tracking for reports as well.


New taxonomy template On Drupal 7, I am trying to create a different version of the default taxonomy template file for a theme. When a user clicks on a taxonomy term, the new template file is used instead of the default one.

So far all I have managed to do is finding the correct template file name (page--taxonomy.tpl.php). The problem that I have is that the variables copied from the template file the Taxonomy module uses simply don't work, as they are obviously not being populated.

<?php if ($content = render($page['content'])): ?>
  <div id="taxonomy-term-<?php print $term->tid; ?>" class="<?php print $classes.' channels-'.strtolower(str_replace(' ','',$term_name)); ?>">
    <?php if (!$page): ?>

<a href="<?php print $term_url; ?>"><?php print $term_name; ?>

    <?php endif; ?>

      <?php print render($content); ?>

<?php endif; ?>

So any variable beginning with $term is NULL. What/where do I call to populate these?

The only template file used from the Taxonomy module is the taxonomy-term.tpl.php file. If a theme implement that template file, it receive the following variables. (The list is partial; for the complete list see the documentation.)

$term_url: Direct URL of the current term
$term_name: Name of the current term
$term: Full term object

page--taxonomy.tpl.php is a page template that Drupal uses for pages with a URL matching taxonomy/*. It is a page template, for which the variables are different. In particular, it doesn't get any $term* variable.

References

taxonomy_theme()
theme_get_suggestions()


Custom actions not appearing in the Trigger/Action settings page I am developing a custom module which defines custom Triggers and Custom actions.
When I add or change an action, this action doesn't inmediatelly appear in the select list of the Triggers admin page.

I refresh, flush all caches and even activate/desactivate the Trigger Unlock module (which seems to work), but now when I create a new custom action, I go nuts to make it appear.

You can appreciate in the image and code what I am talking about (notice the Description has not changed after update).

/**
 * Implementation of hook_action_info().
 */
function commercegate_action_info() {
    return array(
        'commercegate_show_message' => array(
            'description' => t('Show message 1.'),
            'type' => 'commercegate',
            'configurable' => false,
            'hooks' => array(
                'commercegate' => array('callback_sale','callback_cargeback'),
            )
        ),
        'commercegate_show_message2' => array(
            'description' => t('Show message 2.'),
            'type' => 'commercegate',
            'configurable' => false,
            'hooks' => array(
                'commercegate' => array('callback_sale','callback_cargeback'),
            )
        ),
    );
}

Anyone familiar with this problem? Thankyou

To allow a new action to appear on the triggers page, you need to visit the administration page at admin/settings/actions, or call actions_synchronize().


Warning: Invalid argument supplied for foreach() in form_select_options() (line 2837 of includes/form.inc) I get the following erros on selecting the selectbox.
Here onchang of this field will populate another checkbox with city details id zipcode using ajax callback.

 $zipcode_options = get_all_zipcodes_ascending();

  // Populate Ort on auktion clone.
  $selected = isset($auktion->zip_code) ? $auktion->zip_code : NULL;
  $selected = isset($form_state['values']['zip_code']) ? $form_state['values']['zip_code'] : $selected;
  $ort_options = _ajax_city_dropdown_options($selected);

  $form['zip_code'] = [
    '#type' => 'select',
    '#title' => t('PLZ'),
    '#options' => $zipcode_options,
    '#default_value' => isset($auktion->zip_code) ? $auktion->zip_code : "",
    '#select2' => ['width' => '100%', 'placeholder' => t('Enter a zipcode'), 'allowClear' => TRUE],
    '#empty_option' => '',
    '#validated' => TRUE,
    '#required' => TRUE,
    '#ajax' => array(
      'event' => 'change',
      'callback' => 'ajax_example_dependent_dropdown_callback',
      'wrapper' => 'dropdown-second-replace',
    ),
  ];

Referenced many links but cannot find a solution to resolve this issue.

References:

https://www.drupal.org/node/586576

populate drop down from results using ajax

http://techqa.info/drupal/question/203725/help-understand/solve-this-warning:-invalid-argument-supplied-for-foreach%28%29-in-views-that-requires-class-registry-clean-to-mend

Looking on the code i suspect  that error lies in these lines-
$selected = isset($auktion->zip_code) ? $auktion->zip_code : NULL;
 $selected = isset($form_state['values']['zip_code']) ? $form_state['values']['zip_code'] : $selected;
$ort_options = _ajax_city_dropdown_options($selected);

And according to my understanding adding these lines will fix this warning-

 $selected = isset($auktion->zip_code) ? $auktion->zip_code : NULL;
$selected = isset($form_state['values']['zip_code']) ? $form_state['values']['zip_code'] : $selected;
$ort_options = _ajax_city_dropdown_options($selected);
if(!is_array($ort_options)){
    $ort_options=array();
}

Assuming that _ajax_city_dropdown_options($selected); returns options for second select list/ Check Boxes there can be some options in first Select List or there is none selected in first list for which there is no values available for second list. So returning an empty array will address this situation and prevent this error form appearing.


Generated: not cached yet (either no one has visited the page recently, or something is preventing the cache from being generated). I just spin a test Drupal7 site and having some issue w/ getting boost module to work(

$ cat /etc/redhat-release
Scientific Linux release 6.4 (Carbon)
$ uname -a
Linux XXX.XXXXX.XXX 2.6.32-358.23.2.el6.x86_64 #1 SMP Wed Oct 16 11:13:47 CDT 2013 x86_64 x86_64 x86_64 GNU/Linux
$ rpm -q drupal7 php php-pecl-apc
drupal7-7.23-3.el6.noarch
php-5.3.3-23.el6_4.x86_64
php-pecl-apc-3.1.9-2.el6.x86_64
$ drush -r /usr/share/drupal7/ -l alexustest pm-list | grep '(boost)'
Performance and scalability  Boost (boost)                                  Module  Enabled        7.x-1.0-beta2
$

this is what I get via "Boost: Pages cache status" block:

  File: cache/normal/alexustest/_.html

  Generated: not cached yet (either no one has visited the page
  recently, or something is preventing the cache from being generated).

I'm not sure what I am doing wrong. Can someone help me?

Please logout, visit same page as anoymous user then login and visit again. I think you can see cached page message.


Why did my site crash when I moved module and theme folders? A little background, I am quite new to Drupal and IT in general, so this may be a silly/basic question (I am going to start learning HTML, CSS, PHP, etc. for Drupal). I first set up my Drupal site by following the steps on drupalize.me, and then I installed the Sublime Text Editor 3. I realized I had already installed some contributed modules and the Bootstrap theme from drupal.org, but I didn't have contrib and custom folders for modules and themes, both. So I created them and moved the contributed module folders to the contrib folder under 'modules'. I also moved the contributed Bootstrap theme folder to the newly created contrib folder under themes. Then I tried to load my website but it said 'The website has encountered an unexpected error'.

What went wrong here and how can I move my already installed modules and themes correctly to their respective contrib folders?

Drupal keeps an extensive cache of all functions in (contrib) modules and the files in which those functions can be found. Since you moved the files, Drupal is probably attempting to call a function from a file that is no longer there. (It should have thrown a more detailed error in your webserver log.)

Steps to repair could be to move the files back to their original position (Drupal works fine without contrib and custom folders, but it might be easier for yourself). Or enter the database and attempt to empty all tables that end in _cache. That should make Drupal reïndex the functions.


feeds not update exist node and only add them I am using feeds module in order to import node from csv file,
The mapping equation is

and the updating criteria set to

and my csv file contain this

guid,field_type,field_model,field_cost,
1,type1,model1,cost300,
2,type1,model2,cost300,
3,type1,model3,cost300,
4,type1,model4,cost400,
5,type1,model5,cost5,
6,type6,model6,cost6,
7,type7,model7,cost7,
8,type8,model8,cost8,
9,type9,model9,cost9,
10,type10,model10,cost10,

my problem is every time i import csv file the recorded added to my node (not update or replace), where is the problem?

The problem is here NOT UNIQUE field set.after set a field as a unique field every time the nodes will update(replaced).
To  set a field as unique click a button below not set as unique , check unique checkbox and update then it will set as unique.


Drush make and svn:externals I'm planning to use drush "make" function for my new D7 projects.

I would like to know if there is a way to detect, in my project, the repertories managed by "svn externals".

I mean, is "drush generate makefile" command, able to launch "svn propget svn:externals" function (by example), and store these properties in the generated .make file.

So it will "svn propset svn:externals" properties on "drush make" function call ?

Is there an option for that ?
Thanks.

Make files allow you to connect to SVN repositories as sources for install profiles, modules, themes, and libraries. They do not, however, have built-in support for propget or propset.

Drupal repositories are all git based so I'm afraid SVN support is bulwarked to a bare minimum. See the drush_make documentation for the supported SVN parameters.

As an aside, take a look at update Drupal using Drush with svn support for some other ways to incorporate Drush + SVN into your workflow.

NOTE: It sounds like you're using Drush 4.x and the drush_make extension, so my answer is assuming that is true.


How to extend default user registration page in Drupal 7? I would like to extend the default user registration page by adding more fields that will be stored in the same users table of database with the default fields.

What is the easiest way to do that? Could explain how to achieve this?

In Drupal 7, you just add the fields to the user entity in "Administration » Configuration » People » Account settings » Manage fields."
Then, for every field there is the "Display on user registration form" checkbox.


How to get the shipping address programmatically in drupal commerce - what wrapper should i use? I need to get the shipping address (shipping country to be precise) programmatically in drupal commerce. I have the $order object. How can i get the shipping address?

EDIT - Ok i did this

 $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
 $shipping =  $order_wrapper->commerce_customer_shipping->value();

Now i need to wrap it up again, but i don't know the type

$shipping_wrapper = entity_metadata_wrapper(?, $order);

Whatshould i put instead of the question mark?

Ok i did this in this way

function commerce_shipping_biagetti_service_rate_order($shipping_service, $order) {
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $shipping = $order_wrapper->commerce_customer_shipping->commerce_customer_address->value();
  //$shipping is an array containing all shipping data


Setting up the private file directory (nginx) Problem

I'm trying to set-up a private file directory for Drupal on an LEMP stack (Ubuntu 12.04, nginx, MySQL, PHP), I wasn't 100% sure about the permissions or set-up so I thought I'd ask, how should you do it?

So Far

It needs to be a folder which is writable by the webserver but not accessible from the web.

Example:

Location: drupal_root/privatefiles

Permission: chgrp 775 www-data privatefiles

Nginx config: (goes into /etc/nginx/sites-available/mysite):

server {
         listen 8080;
           root /srv/www/mysite/public;

           location ^~ /privatefiles {
             internal;
           }

        ...
        }

Would that be enough? It recommends on the official page to have the folder outside the Drupal root. What difference would this make?

Have a look at Perusio's config, it has all the information and explanation you need. Here is a quote from it:

  This config assumes that private files are stored under a directory
  named private. I suggest sites/default/files/private or
  sites/<sitename>/files/private but can be anywhere inside the site
  root as long as you keep the top level directory name private. (...)
  Example: Calling the top level private files directory protected
  instead of private.

location ^~ /sites/default/files/protected {
  internal;
}

  Now any attempt to access the files under this directory directly will
  return a 404.

...

  The usual practice involves setting up a directory outside of
  files directory and giving write permissions to the web server user.
  (...)  I think it to be less advisable, in the sense that now there's another directory that is writable by the server.

  I prefer to use a directory under files, which is the only one that is
  writable by the web server, and use the above location (protected or
  private) to block access by the client to it.

In short, marking it as internal is enough.


Revert a Feature Component programmatically I have a Feature installed using an Installation Profile. But I always have to go and Revert a particular Component so that it's no longer Overridden (so that, for example, the Feature's Blocks appear).  I just wanted to know if I can take this step programmatically using code itself in the Installation Profile.

In the screenshot below, I've shown the component that has to be reverted programmatically (in the screenshot, it's already reverted back so check box is not available).

Here are a few thoughts though on resetting your features programmatically or as add-on install scripts.

You could use Drush to reset the Feature:

drush features-revert [feature name]

Another thought would be to use features_revert() during the install process:

features_revert(array('module' => array('component')));

The Strongarm module could be useful as well to force your Feature to retain its default state I think.

I have to agree with @Letharion in his comment on your OP.  I would want to know that other important things aren't being mistakenly modified during the install process.


Font-Awesome issue: how to remove menu-link text from a menu item with font-awesome icon? I installed the module Font awesome icons (with it's library) & the module Menu attributes; I've configured them, and now have a working font-icon in my main menu.

The problem is that instead of the desired icon, there is a combination of icon&Text (img1), and I need only an icon to appear... If there was an option to delete the text I would do that, But I haven't seen such an option - The menu-link text seems to be mandatory (img2).

I though of the css command text-indent: 200px to remove the text but the font itself is also text... Any ideas how to safely remove the text without removing the icon? Thx,

In this case you're better off using a background image. Save yourself the hassle.

.menulink{
  Width: 25px;
  Height: 0;
  Padding-top: 25px; /* height of image */
  Overflow: hidden;
  Background: url(images/home-25x25.png) 0 0 no-repeat;
}


Registration form customization to meet COPPA and similar "under 13" laws? I want to add an extra field for user age. If age is below 13, it should show another text input for getting mail address of user's parent or other legal guardian. Accounts with age under 13 should only be activated after email verification by said parent.

How can I add this field, validate age and process validation mail?

Simply go to Home > Administration > Configuration > People > Account settings and add fields you need. Use Conditional Fields module to conditionally show a text box.

Now you need to use Rules. See registration rules post for example - what you want is to automatically enable account if checkbox is empty, and send email if checkbox is checked. How to do the very last thing, and how to process verification link, is a material for a separate question.

Questions that may help with further development a bit:

How do I Send HTML Emails via Rules?
how to create rules to send email notification for node reference content?
and more...


drupal7 Webservices create a node I am using Drupal 7 and creating a webservice.
and using http://delta.indivar.info/tanenttest/drupalgap/node this webservice. i am trying to create a node using poster plugin of Firefox
and i am passing parameters as

type='page'

it shows  ["Access denied for user anonymous"]

i can't give permission for Anonymous user. is there is any way so that only authenaticate user can create node.

When using the Poster plugin for Firefox, you need to be logged into your Drupal site in another tab. Then you can use the Node Create resource. Keep in mind that you'll need to pass along the X-CSRF-Token in the header of the request. You can get the token from here, after logging in:

http://www.example.com/?q=services/session/token


Change the formatting of a label in Drupal 7 When viewing the teaser for a node, all labels are output as uppercase.  I want them titleized (meaning the first letter of every word is capitalized).  What's the best way to go about doing this?  Currently there is no CSS effecting the label field, so I know Drupal is just outputting all capitals.

I don't know why Drupal is rendering the label text in all capitals, so I was looking for a theme preprocessor function in the Drupal 7 API that could maybe dig into the label data and then change it to all lowercase from there, but I couldn't find anything concrete.  I could then apply CSS to format the label how I want.  However, until I know HOW Drupal renders the labels I can't apply any CSS that will have the desired effect.

EDIT: I changed the title from "Change label in teaser output to lowercase" to "Change the formatting of a label in Drupal 7" as I think that the question can be answered in a less specific sense, and I may have found the reason my labels are turning up in all caps.

Something is odd about this as you say your labels are in lower case but they are being rendered in all caps.  I would view it with Firebug / Chrome Web Inspector to make sure there is not a higher level selector in your CSS that's transforming it to all caps in which case you would have a tough time going back to title case if your selector does not override the one thats making it all caps.

At any rate you can't transform all caps back to titlecase but you could with jQuery:

https://stackoverflow.com/questions/3471157/css-text-transform-capitalize-on-all-caps

Also see this for reference, http://www.w3.org/TR/CSS21/text.html#propdef-text-transform

"capitalize
Puts the first character of each word in uppercase; other characters are unaffected."

But before you go an add some JQuery, I would take a serious look at your CSS with Firebug to make absolute sure that something is not transforming it to all caps in the first place.


"Access denied" whenever trying to edit IMCE User-1 profile After reinstalling IMCE, I am trying to see the User-1 profile by accessing the "admin/config/media/imce/profile/edit/1" URL. But it shows following error "Access denied. You are not authorized to access this page."

I have verified (URL admin/people/permissions) that administrator has privileges for IMCE module. Also rebuilding permissions is not helping here.

Earlier I changed the Drupal admin from the mysql database. I simply done undo on this operation.
Have a look in your database.


How do I get the node ID from the taxonomy term ID? In Drupal 7, we are using taxonomy_select_nodes() to get a list of nodes using a taxonomy term.

What is the equivalent in versions after Drupal 7?

Use loadByProperties():

$nodes = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadByProperties(['field_tags' => $tid]);


Why can not Drupal find my theme for a custom block? I read this answer, but I can not figure out, why my block is not shown. My block is activated in footer and should appear on <front>.

/**
 * Implements hook_theme().
 */
function poll_dialog_theme() {
  return array(
    'poll_dialog_output' => array(
      'variables' => array(
        'title' => NULL,
        'content' => NULL,
        'popular_content' => NULL,
      ),
      'template' => 'theme/poll_dialog',
    ),
  );
}

function poll_dialog_block_info() {
  $blocks['poll_dialog'] = array(
    'info' => t('Poll Dialog'),
    'cache' => DRUPAL_NO_CACHE, //there are a number of caching options for this
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function poll_dialog_block_view($delta = '') {
  switch ($delta) {
    case 'poll_dialog':
      $block['subject'] = t('poll_dialog');
      $block['content'] = _poll_dialog_block_content();
      break;
  }
  return $block;
}

/**
 * Callback implemented by hook_block_view().
 */
function _poll_dialog_block_content() {
  $static_title = t('Static Title');
  $static_content = 'static content';

  return theme('poll_dialog', array(
      'title' => $static_title,
      'content' => $static_content,
      'link' => l('Poll', 'some url'), array('attributes' => array('target' => '_blank'))),
    )
  );
}

You're calling a non-existent theme function. Your code should be:

return theme('poll_dialog_output', array(
    'title' => $static_title,
    'content' => $static_content,
    'link' => l('Poll', 'some url'), array('attributes' => array('target' => '_blank'))),
  )
);

or, even better:

return array(
  '#theme' => 'poll_dialog_output',
  '#title' => $static_title,
  '#content' => $static_content,
  '#link' => l('Poll', 'some url'), array('attributes' => array('target' => '_blank'))),
);

The main point is that the name of the theme function you call needs to match what you've used in hook_theme().


Speed difference between db_select and EntityFieldQuery Is there any performance difference between db_select and EntityFieldQuery?

I would like to re-write portions of the site removing db_select in favour of using EntityFieldQuery.

I hope that i will able to replace few db_select calls with one EntityFieldQuery call, also.

There might be a slight difference in performance but I guess it depends on your implementation. As you said yourself: it might be possible to replace a couple of db_select queries with EntityFieldQuery, although I can't really think of a situation where you'd be able to do that, if your db_selects are solid.

If I'm not mistaken EntityFieldQuery actually uses db_select or at least a SelectQuery to fetch data. I also think EntityFieldQuery looks up information about the entity that needs to be  queried (ie: base table), this is cached though.

My guess is EntityFieldQuery would be somewhat slower, but the only way to see if you're losing any performance is by benchmarking (timing) it.

All in all I wouldn't worry about the performance of EntityFieldQuery. The biggest advantage of EntityFieldQuery is that it adds another layer of abstraction, making your code more loosely coupled and more cohesive. It's also pluggable so somebody could change the backend without you having to change any of your code.


Drupal Users while developing: Methodology I have recently been working on a Drupal project that due to time constraints had to be put up in a relatively infantile stage with the registration in place (using Profile2) and attempted log-ins blocked.

The problem that I have run into is that users have registered to the site in the interim time between my last update+commit and now.

I have exported the authmap, profile, profile_type, users, users_roles, webform_emails, webform_roles, webform_submissions, webform_submitted_data, & zendesk_users tables and imported them into my local environment. There doesn't appear to be any bugs .. *knocks on wood*.

Is this the only option for me? Does anyone have any insight as to how to best handle a situation of this nature?

I would suggest using Features to deploy your changes if you aren't already. That way there shouldn't really ever need to be any database changes going upstream, so this problem will be averted.

Any database changes that do ned to be made can go into hook_update_N functions in your Feature module's .install file

EDIT

In favour of other popular opinions, there is also the Configuration Management module which attempts to backport the CM functionality from D8 back to D7.

  The configuration management module enables the ability to keep track
  of specific configurations on a Drupal site, provides the ability to
  move these configurations between different environments (local, dev,
  qa, prod), and also move configurations between completely different
  sites (migrate configurations) without the use of modules with all
  configuration being owned by the site.


How to set multiple entity references as default values using the hook_form_alter() I have a node which when renders an adds an entityform to the page.

The node has a entity ref field which references multiple other nodes. (eg: Products A, Product B, Product C, etc)

What I need is a rating from each user for each product who views the node.

Eg :
Node 1 | User 1
Product A : rating1
Product B : rating2
Product C : rating3

Node 1 | User 2
Product A : rating4
Product B : rating5
Product C : rating6

How could i establish such a thing?

You can use Fivestar and Voting API for rating the product

The Fivestar voting module adds a clean, attractive voting widget to nodes and comments and any entity


url of custom theme not showing up with page.tpl I've a custom theme. page.tpl has the html markup for my template. And I created some paths like 'about-us', 'terms' via my custom module.

Now, my problem is when I access the above defined paths. They are just showing up the contents defined in the callback function.

What I've to do if I want to show the contents in the content region of my page.tpl

Please help me.

----- THIS IS FIXED NOW :: THANKS FOR YOUR HELP -------

Thanks everyone for helping. I changed the contents of the callback function, print to return. It solved the problem.


Views slideshow with two pagers I want to have a views slideshow as the following:

Two content types which one has image field and the other has video field.
I need to have two pagers for the slideshow, one pager for content type (image) and one for content type(video).

I searched for a solution but i couldn't fine one, also tried to make the pager as a views then using views field view module but no luck.

This photo will explain what i looking for:

Any tips?
Thanks

You could do this using three views.

Make the center part of the screen a view which uses a URL argument to know which node to pull the image/video from.
Make the listing of possible photos a view. Make each link to view #1 and passes in the node id.
Make the listing of possible videos a view. Make each link to view #2 and passes in the node id.

To put all three views on one page you have several options. You could use the module Panels or make each view a block and put them into different regions.


How to export the contents of nodes in a view I have a view that displays content based on some criteria. I would like to export all of the content of the results of the view into a text document or Excel spreadsheet, as I am intending to edit them for a book. Any idea how to do this?

The module I use for this is http://drupal.org/project/views_data_export

You create a new style and attach it to your existing page/pane, you can export:

CSV
Microsoft XLS
Microsoft DOC
Basic TXT
XML


Any way to add something similar to Olark or Zopim Olark and Zopim are live chat services. Is there any module to add this feature to a Drupal site? I took a look to 'chat room' module but it is not what I need.

I don't know of a free Drupal service to do this.
Olark has a Drupal guide to get it working on your site. There is also the Olark Chat module. I know that VPS.NET and Lullabot are both using Olark.


How do I get $form_state from hook_entity_update()? I've manipulated the edit node form via hook_form_BASE_FORM_ID_alter() to insert a select pull-down menu.

In my module, I've implemented hook_entity_update() to fire when the edit node form is submitted. How do you get the form_state in hook_entity_update()? I want to save the user's choice from the select pull-down.

$form_state is not available there.

You might want to consider using fields and widgets, then you get a lot for free.

If that's not an option then you can register a so called #entity_builder:

function menu_ui_form_node_type_form_alter(&$form, FormStateInterface $form_state) {
  // ...
  $form['#entity_builders'][] = 'menu_ui_form_node_type_form_builder';
}

function menu_ui_form_node_type_form_builder($entity_type, NodeTypeInterface $type, &$form, FormStateInterface $form_state) {
  $type->setThirdPartySetting('menu_ui', 'available_menus', array_values(array_filter($form_state->getValue('menu_options'))));
  $type->setThirdPartySetting('menu_ui', 'parent', $form_state->getValue('menu_parent'));
}

The example is for the node type config entity, but it should work pretty much the same way for a content entity. book_form_node_form_alter() is an example for nodes.


How to serve the same page for all URLs? I am using Drupal 7 as an API to send JSON data to a Backbone application. It is a single page site with its HTML markup in html.tpl.php.

Everything works fine with the Backbone router when I start on the homepage and navigate with internal links but when I refresh a page or type a URL directly I get a Drupal 404 error.

How can I make unknown pages to serve the same page all the time?

The .htaccess redirects to index.php so it's not a browser 404 but a Drupal 404.

In case someone has the same issue, it only happens when connected to Drupal's admin panel. I solved it by disconnecting…


Integrate ddmegamenu in drupal menu There is a menu plug in called ddmegamenu http://www.dynamicdrive.com/dynamicindex1/ddmegamenu.htm

I want to integrate in drupal 7 menu system. I don't know form where to begin
i tried drupal megamenu module, but it is not giving same effect as ddmegamenu.

can anyone guide me how to format menu tree to apply ddmegamenu to my theme..

Dont bother, your basically going to have create module for something like that and someones already done it. This is probably the best mega menu for drupal, just install and away you go. You can add anything you want to the dropdowns, views, blocks, etc.

http://drupal.org/project/om_maximenu


How to implement a Comment Reply Form through Views and using JS? We have a comment body, using views, where we have the name, comment, picture, and date for each of the posted comments. At the end of all comments we have a comment body, where one can add a comment.

Now this works great for a linear comment system, but we want a threaded system in place. In views, I can add a reply comment link, but that takes me to a new page.

What I want is JavaScript based action, such that the comment form, goes below the reply link when reply button is clicked. Is this possible via views?

If not, what's my best option?

UPDATE

I enabled a module called ajax comments. This works great with default drupal comment system, but not so much with views. I added the required classes, and got the basic thing to work but the newly added comment doesn't appear until you refresh the page. Also the message (queued for moderation) comes at the bottom of the page.

If someone has set this module up successfully with views, please let me know.

Have you looked at Inline Ajax Comments?


Does superfish module support multiple languages? Does superfish module support multiple languages in drupal 7?  From the CMS, I seem to be able to translate each menu item into english and french.  But Superfish is only outputting the english version of the menu.  So does superfish handle multiple languages?  If it does, how do I enable it?

Heh, it looks like they've released a version of Superfish with what was supposed to be just a temporarily disabled support for translations.

You can either

apply patch found at http://drupal.org/node/1112928 or
use an older version of Superfish


behaviors javascript executing I want to pass params via Drupal to my JS file. I have no problem fetching them with the code below,
the problem is that as the  $(document).bind('leaflet.map'  function executes FIRST, it is not able to find the
user_name parameter

my_module.module

  function my_module_preprocess_html(&$variables) {

  $user_name=$GLOBALS['user']->name;
  drupal_add_js(array('my_module' => array('user_name' => $user_name)), array('type' => 'setting'));
  drupal_add_js(drupal_get_path('module', 'my_module') . '/js/external.js');
  }

external.js

(function($) {

Drupal.behaviors.fewo_map= {

 attach: function (context, settings) {

 alert('get params');
 //we can fetch the data
 user_name=settings.fewo_map.user_name;
}

}

$(document).bind('leaflet.map', function(e, map, lMap) {

//it fires first, so is unable to get user_name data
alert('leaflet')

console.info(user_name)
})

If I do...

(function($) {

 Drupal.behaviors.fewo_map= {

 attach: function (context, settings) {

  $(document).bind('leaflet.map', function(e, map, lMap) {
    alert('leaflet')

    console.info(user_name)
    })
  }
 }
})

the result is the same

Also tried using JS injector, no success neither. I need the user_name as parameter to define the settings inside leaflet 'function'
Thanks

Difficult to separate your php from javascript, but if you set js variable with this php code it should execute first and can be used within leaflet js function later:

<?php render('<script>var username = "'.$GLOBALS['user'].'";</script>'); ?>


How to use Rules to populate reference product after creating a Commerce product? After a Commerce product is created I need to create a new product display node and reference the product in a field.

This is my first time using Rules. I can create a new product display node but I cant figure out how to populate the 'referenced product' field.

Despite the limited information in your question, you should be able to create such rule (using the Rules module) like so:

Use a Rules Event that is related to "When Commerce product is created" (something similar to "After saving content"?).
Add a Rules Condition to make your referenced product field become available to use in a Rules Action. This condition can be either of those alternatives:

"Entity has field".
"Content is of type".

Add Rules Action "Set a data value" for your referenced product field.


Send email with URL of same page as the email link? We have a page that displays a logged-in user's selections from a Flag Lists process. The page includes code to generate the specific URL of that page, so it can be copied and pasted elsewhere. (essentially a "share this" type of thing, but this is definitely not intended for social media) That code is:
    " onclick="this.select();" />

We want to provide an email link (ideally, a button) which sends a preformatted message including this URL, to a specific person's email address. (i.e. always to the same person) I am having trouble visualizing how this can be done, since the interface I am using for adding an email link (via CK Editor) isn't able to process the "current-page:url" PHP code and just displays it as code in the resulting message.

Any suggestions? -- Thanks! --

insert a Drupal token of the current page url into the WYSIWYG. This token is provided by drupal 7 core I believe.

See the Token Insert module.

  This module allows you to insert tokens into a textarea. It supports
  both plain text and wysiwyg textareas. The format used for the insert
  is compatible with Token Filter.

  This module contains three modules:

  Token Insert UI: Allows you to select which tokens are available for
  the insert, by default all tokens are shown. This module doesn't have
  to be enabled to use the others.
  Token Insert (text): Add a fieldset
  under each textarea, works for both plain text fields and wysiwyg
  fields.
  Token Insert (wysiwyg): Adds an extra button to wysiwyg
  editors and opens a popup to select the token to insert.


Using Webform to create a node So i know there are answers around not using Webform, but i require the reporting and tracking functionality of webform, so please stick to using it.

I am needing to create a node based on a questionnaire that is filled out so i can then display the answers of each submission in a list view/ detailed view setup. they are stories that users are able to tell to the world then have displayed on the site.

Any ideas?

You should use Rules module in the following way:

Install and enable Rules module
Install and enable Webform Rules (https://drupal.org/project/webform_rules)
Create a new rule
Choose the "After a webform has been submitted" event
Optionally set your conditions
Add a new action "Create a new entity" of type "Content"
Add the neededs action to add properties to the created entity
Add the save action

Note: You can use Tokens available with "Set a data value" .


How can I serve different view blocks based on media queries? I have 4 view blocks that I want to show up as carousels on mobile. I'd like to be able to clone them, turn the clones into carousels with this module https://www.drupal.org/project/slick, then serve them in place of the others somehow. I know I can use css to serve both and hide them but that doesn't sound like a good idea.

You can try Browsecap and Browsecap Block modules to show blocks only on mobile devices.


Upload zip & unzip to multiple image field I am using drupal 7 and I want to upload a zip file and automatically extract it into multiple image fields on a node. The zip file contains images. Is there a easy way to do this? cause I'm not a programmer

I think your main goal is upload multiple image on a single upload and this goal you can achive via a module name 'Multiupload Imagefield Widget' https://drupal.org/project/multiupload_imagefield_widget.

This module provide a widget to select multiple images . For more info go through the module instructions.


Hook module placement I have the following file named background_image_style.module

In my Drupal 8.3.3 site, paragraphs.module is at MySite/web/modules/contrib/paragraphs/paragraphs.module.

I installed the site and all contributed modules with Composer.

composer require drupal/paragraphs
vendor\bin\drupal module:install paragraphs

Where does my hook module go? (I just copied it in where the paragraphs.module is.) Are there any other overhead steps that needs to be done (e.g. editing other files)?

I tried several locations and cleared the cache each time.

    /**
     * Implements paragraphs().
     */
    function background_image_style_preprocess_paragraph__banner(&$variables) {
      $paragraph = $variables['paragraph'];
      if (!$paragraph->field_image->isEmpty()) {
        $image = $paragraph->field_image->entity->url();
        $variables['attributes']['style'][] = 'background-image: url("' .                 $image. '");';
        $variables['attributes']['style'][] = 'background-size: cover;';
        $variables['attributes']['style'][] = 'background-position: center         center;';
      }

From Where to Put the Module Files:

  Manual import location

  If you import a module 'manually', you should place your module in that same default recommended location, HERE:

  [d8-root]/modules/HERE

  [Themes: [d8-root]/themes/HERE]

It's a good idea to keep custom and contrib modules separate, hence Drupal Project putting contributed modules into their own folder; following on from that, there's a pretty common convention to place custom modules under [d8-root]/modules/custom/. But you don't have to, you can use whatever hierarchy you like under /modules, Drupal will pick up anything it finds recursively.

After it's in place, don't forget to enable the module, or it won't do anything.


Debugging hooks that fired? I'm somewhat new to module development.

Is there a way to currently output what hooks have been run on certain nodes?

Would this be done with xdebug?

Unless you get a fatal error (or blank screen) it's pretty easy to get a list of modules that will invoked when a special hook is called:

$modules = module_implements($hook);
foreach ($modules as $key =>  $module) {
  $function = $module . '_' . $hook;
  if (!function_exists($function)) {
    unset($modules[$key]);
  }
}
// $modules is now an array containing all the modules that will be invoked by $hook.

You could use stuff like xDebug to track the flow of the Drupal, but this can be overwhelming, especially if you are new to Drupal.


apply condition to pages created by user roles if(isset($node) && $node->type == 'page') {
}

In the above code, I need add one more condition, so that it get applied on those pages which was created by users having user role "EDITOR" Please help.

if(isset($node) && $node->type == 'page') {
  if($node->uid) {
    $node_author = user_load($node->uid);
    if(is_object($node_author)) {
      if(in_array("editor",$node_author->roles)) {
        // This is the condition to match the current node author belongs to editor role.
      }
    }
  }
}


Check if user is flagged in rules I want to make a rule that check if the user of the currently viewed profile, have flagged the currently viewing users profile.

So basicly, have viewing user been flagged by the profile owner of the viewed profile.

So lets say this rule returns true, then there will be a text box when user is viewing profile "This user have flagged you!!".

I have tried all sorts of things in the Data selector of "User who to check" (the field in the buttom of image.

You can create a Rule with the event "User account page is viewed". Then, you can add the required condition as follows:

So you select the current user as the user that should be Flagged and select the visited user as the person that should have done the Flagging.


Problems creating a custom blank page with my custom module I'm trying to upgrade old Drupal 7 modules to 8 and I am struggling to figure out how to create a blank page (by this I mean, a page with zero HTML from enabled themes) for my module. I added routing to my custom controller, my controller method takes care of all the logic and returns the following array:

[
        'showVideo' => [
            '#theme' => 'videoPage',
            '#content' => $content
        ]
]

I already defined "videoPage" in mymodule.module using hook_theme:

Function mymodule_theme($existing, $type, $theme, $path){
  return array(
    'videoPage' => array(
      'variables' => array('content' => NULL),
      'file' => 'mymodule.html.twig'
    )
  );
}

"mymodule.html.twig" is a full stand-alone HTML file from the opening HTML tag to the closing tag. I don't want any other content to show up there but instead I'm getting the content in that Twig file, then followed by the HTML for the currently selected Drupal theme. Also, my {{ content.value }} calls in Twig seem to be getting ignored. And by this I mean, I can literally see {{ content.xyz }} in the markup being printed. The $content being returned by the controller is an array and I'm sure all the values are set. It almost feels like the Twig file is being called while the Controller's logic is being ignored. (this last bit has been solved by Clive's response)

Any help? Am I totally off in this approach?

You can output the html of one twig only in a symfony response:

use Symfony\Component\HttpFoundation\Response;

public function my_page_controller() {

  $build = array(
    'page' => array(
      '#theme' => 'videoPage',
      '#content' => $content,
    ),
  );
  $html = \Drupal::service('renderer')->renderRoot($build);
  $response = new Response();
  $response->setContent($html);

  return $response;
}


How to serve content type for authorized users as for anonymous? I have content type "book". It's nodes are huge and it's takes a long time to format them by input filter. Caching works only for anonymous users.

So my goal is to give authorized users the cached version without APC, Cache Router (using a shared hosting).

I tried to change actual uid in template.php like so:

function mytheme_preprocess_page(&$vars, $hook) {
    if (isset($vars['node']) && $vars['node']->type == 'book') {
        global $user;
        $user->uid = 0;
    }
}

But it didn't help.

Render the nodes with Panels, and you can set the caching across all users.

You could then either set it to a time based cache, or use my Panels Cache to get the cache cleared automatically when the nodes update.

See Learn Page manager! for an introduction to Panels and Page Manager.


Delete nodes if URL is called via Wget Command How can I delete the nodes if i am calling my URL via wget command. Because the anonymous user haven't permission to edit/delete.

Services module is great for this job. Here are the steps how you can make it work:

Download Services, Chaos tools and Libraries. Enable the REST Server module (shipped with Services), it will make you enable all dependencies as well.
Go to Structure » Services, add a new endpoint.
Choose a machine-readable name, e.g.: node_remove.
Select REST as a server.
Define a path to your endpoint, e.g.: node-remove.
Enable debug mode, it's handy while you are experimenting, Services will write useful information to the log.
Enable session authentication, this will ensure security.
After saving your endpoint, edit its resources.
Enable the delete operation in the node group and the login operation in the user group.
Go to the Server tab, select the response formatters and request parsing options that you want.

Your endpoint is ready to use. First you need to post a username and password to http://example.com/node-remove/user/login. (It's recommended to create a user with a strong password and permissions for only deleting nodes.) You will get a session ID (among others) in the response. Then you need to perform a DELETE request to http://example.com/node-remove/node/{nid}. You can write a script for these actions and execute that as a cronjob.


To show custom user fields in a view does not work for user with uid 1 I have a view that shows some custom user fields as block on the users profile page. The permission of that view is set to »Access: Permission | View published content«. That means the view should be visible for any visitor.
This works fine on any user profile but not on the  profile of the administrator with the uid 1. On his profile page the view is empty.
Is this a bug or a wanted behaviour? How to solve this?

UPDATE: I tried to solve this by changing the view's access permissions but even if I set them to »none« or »Roles | All« it does not work.

Try using "Access: Role" rather than "Access: Permission" and select all user roles (that you'd like to be able to see the view ...


How to modify field value in other nodes after node update? After node update I need to modify a field value in several connected nodes.
As I know, I cannot use hook_entity_update() since $node->save() forms infinite recursion.
How can I modify node fields after a node has been updated? (besides hook_cron)

Use hook_form_alter or hook_form_FORM_ID_alter
Add a custom validation that runs after all validation has passed
$form['actions']['submit']['#submit'][] = 'mymodule_update_referenced_nodes';

Then in that function
function mymodule_update_referenced_nodes(&$form, \Drupal\Core\Form\FormStateInterface $form_state){

  $field_other = $form_state->getValue('field_other')[0]['value'];

  $references = $node->get('field_referenced')->referencedEntities();

  foreach ($references as $referenced_node) {
    $referenced_node->field_other->value = $field_other;
    $referenced_node->save();
  }

}


How do I allow users to just click a marker on an OpenLayers map to go directly to the node? I am using the OpenLayers module and it appears that I can add a popup and a tooltip behaviour if a users clicks or hovers over a marker on a map, but I only need users to be able to click the marker to go to the node (no popups). Is there a config I am missing to do this?

Usually jumping to new page just by clicking object is not what users want, as they need to be sure first that the clicked object is correct one, this is why there is no built-in function and you do not see this much in the wild.

OpenLayers module has behaviours for this kind of actions. It seems that the core module does not have what you expect, and nobody has done it yet, so no easy configuration option :( Here is the guide how to create new behaviours from scratch. I would use Popup behavior as sample.


How to expose variable from php to js - and keep it updated? drupal_add_js works to pass variables from php to javascript, and there are plenty of examples. But I want the variable to update without a new page request.

I have a page request that kicks off some long-running code in the background (using background_batch and the Batch API), during which a variable is updated occasionally. When it changes, calling drupal_add_js again doesn't do anything. Then I tried to implement this but it doesn't seem to work either. I've use ajax with the Form API, but that is a specific request that returns to an element just once - this is going the other way (php to js ad-hoc).

Summarizing: How to push a php variable to be available in javascript at any point it time, from any Drupal code?

You have two options, depending on how responsive you need it to be, and how complex you're willing to get:

1) You can add Javascript to your page that will continually send AJAX requests to the server in the background, essentially asking for the value of that variable. You would achieve this by creating a new menu path with the sole purpose of serving the value of that variable in JSON. The JS that sits on the page could then be set up to ask for that variable every X seconds until it changes (or it could just keep doing it forever if you wanted).

2) You could write a separate Node.js application that runs on your server, which listens for updates to the variable from the background task  and then pushes a notification to the JS in your page via websockets. That's obviously a lot more complex. But potentially more performant, and the updates would be instant. See this module for an example of a Node.js chat application: https://www.drupal.org/project/nodejs


Creation + Drag and drop of groups of fields with CCK I have an image field with unlimited number of values but they relate to each-others in sets like this:

1a
1b
1c
2a
2b
3a
3b
3c
3d

My goal would be to create a text field before the first image of each set and to be able to drag and drop each set without effecting the order inside each set.

It would look like this:

Header for 3
3a
3b
3c
3d
Header for 1
1a
1b
1c
Header for 2
2a
2b

Is there a module that provides a similar functionality?
Unfortunately multi-groups doesn't cut it for me because it just pairs the text field with the image field...

Take a look at field collection module.

You could create a field collection with a text field (Number of values: 1) and an image field (Number of values: Unlimited). Then you should set your field collection field also to unlimited values so you can add as many sets you want.

Nevertheless field collection is a little buggy, but give a try first.


Migrate Private Files: FILE_EXISTS_REUSE still duplicate files I'm trying to migrate private files (file migration), the problem is even I set file_replace to 'FILE_EXISTS_REUSE' the files are still duplicated (it adds _1 or _2, and so on.). Here is my mapping:

    $this->addFieldMapping('file_replace')
         ->defaultValue('FILE_EXISTS_REUSE');
    $this->addFieldMapping('preserve_files')
       ->defaultValue(FALSE);

Please help!

This solved it for me.  The documentation at this link has been updated to show that you need to use the class prefix:

$this->addFieldMapping('preserve_files')
  ->defaultValue(1);

$this->addFieldMapping('file_replace')
  ->defaultValue(MigrateFile::FILE_EXISTS_REUSE);


How to display custom block anywhere in a div? I am creating one drupal 8 theme based on bootstrap framework, for banners I created one custom block, named as 'Homepage banner', without creating any region, how to display this on my homepage template 'page--front.html.twig'.

Install the twig tweak module
Insert the following code in your page--front.html.twig

{{ drupal_entity('block_content', 1) }}

Where "1" is the block id. You can see the block ID when you edit the custom block, it's in the URL - E.g. my-drupal-site.com/block/1


How can I add a Twig template to a programatically created custom content type? I created a module implementing a content type. How can I set a custom template file for that content type and for the teaser and full view modes? I need to use the template files in the folder of my module, not the theme the site is currently using.

These are some details about my module.

Module name: My Module
Content type name: My Content
Teaser template name: node--my-content--teaser.html.twig
Full template name: node--my-content--full.html.twig
Field template name: field--node--field-my-field--my-content.html

Nodes

  Pattern: node--[type|nodeid]--[viewmode].html.twig

  Base template: node.html.twig (base location:
  core/modules/node/templates/node.html.twig)

  Theme hook suggestions are made based on these factors, listed from
  the most specific template to the least. Drupal will use the most
  specific template it finds:

  node--nodeid--viewmode.html.twig
  node--nodeid.html.twig
  node--type--viewmode.html.twig
  node--type.html.twig
  node--viewmode.html.twig
  node.html.twig

  Note that underscores in a content type's machine name are replaced by
  hyphens.

Source: Twig Template naming conventions

In your case this is number 3.

Example:

node--article--teaser.html.twig

If you want to place the template inside the module see: Template for custom content type

In your case this would look like this:

/**
 * Implements hook_theme().
 */
function my_module_theme() {
  return [
    'node__my_content__teaser' => [
      'base hook' => 'node',
    ],
    'node__my_content__full' => [
      'base hook' => 'node',
    ],
  ];

In my experience you only need base hook. Drupal will discover the correct template name and path on its own. You have to be careful with the underscores (_) in the theme hook, they should match exactly the hyphens (-) of the template name.


How do I manage landing pages? How can I easily manage landing pages in Drupal 8? Do I need to created separate content types for landing page? Is there any other way to manage this with a single content type?
The landing pages I want to create are the following ones.

Blog landing page
Fields: banner title, body, image, blogs
Publication landing page
Fields: banner title, body, image, publications
News & events landing page
Fields: banner title, body, image, news and events landing

Generally speaking, as @Kevin aknd @kiamlaluno have noted, it's probably easiest to make one content type Landing page and use that for all landing pages on your site.  I actually did a similar thing on a site earlier this year.
You noted that you wanted to do three kinds of landing pages with different fields.
So to implement this, you could add all of the fields to the Landing page content type:

banner title
body
image
blogs
publications
news and events

Then, when you are adding content of type Landing page, just fill out the necessary fields.
Then you can make a theme template for your custom content type.  Copy the file web/core/modules/node/templates/node.html.twig and copy it to your custom theme's templates folder and rename the file node--LANDINGPAGE_MACHINE_NAME.html.twig.
For example: web/themes/contrib/MY_THEME_NAME/templates/node/node--landing-page.html.twig (Note: If the machine name is landing_page, you need to replace the _ with -.)
You can then edit this file to display the fields however you want to create the three kinds of landing pages.  You can display a field like this: {{ content.field_blogs }} where field_blogs is the machine name of your blogs field, for example.
If other users who don't know the rules might mistakenly fill out all the fields when they shouldn't (for example, if a node should not have values for both blogs and news and events), then you can add custom form validation to check for this.


Check to see if content exists; if not, create it I have two node types that are related by a node reference. Essentially, content type A is a container, and content type B is an item. For illustration sake, I'll call content A Box and content B Item. the Item has a number of taxonomy terms that are shared with Box. Again for illustration sake lets call them color and size. What I'm trying to do is set up a rule that does the following:

On Creation of an Item ( actually before the content is save) check to see if there is a Box that shares both the color and the size of the item.
If one exists, assign the new item to that box (via node reference).
If one does not exist create the box, then assign the new item to that box.

I'm new to the Rules module, and although it seems really powerful, I'm just not sure that this particular use case is possible. The part that I'm most unsure about is how to check if the box with certain terms exists.

I think doing this with Rules alone, will work if you have a very limited set of nodes. Once you pass 100 or so, then the overhead of all the object wrappers will soon force you to give PHP gigabytes of RAM instead of megabytes, and then set your servers CPU aflame.

I belive an approach that integrates Rules with Views bulk operations however, could do this neatly for you.
I have not attemped anything similar myself, but a VBO should be able to query the database for the node, and then if it exists, return it to Rules.

The code approach would be to implement hook_node_presave, query the database with an EntityFieldQuery for a Box node with the right terms, and assign the reference.


Content Access for not showing specific Content types on Add Content page I am new in Drupal. I have one simple query.

I am trying to create one Editor role for one website. Editor would be able to create, update and delete one specific content type "Documents".

I have given permission using ACCESS CONTROL and also I have checked in Permission page. It only has permission to add "Documents Content Type" but still when I login as an Editor and try to create new "Document Content", it shows all the content types. I want to hide other content types for Editor.

So basically it should show only "Document Content Type" for a user.

P.S. This is bit different question. So don't make it as duplicate question Pls.


Keep the destination argument in when user switch from user login to register? I have a link for users to click so that they can add a specific node type, and I use a link like below so that if the user isn't logged in, he/she can login and then be redirected to the node form, and if already is, directly goes to that form.

Now, if the user isn't registered yet, and clicks the register tab instead when coming to /user (or /user/login), the destination argument disappears, and when the user has filled out the form and is all set, he/she will be forwarded to the start page, and not the node form, that I wanted.

What would I have to do to keep this destination argument if the users registers in the process?

I tried Rules - nothing. And now I'm trying to use form/menu alter to either add the destination argument to the link, or create a completely new tab for this, and hide the other one.

Help!

Url example: example.org/user/login?destination=/node/add/help

I found for Drupal 7 there is no need to override the theme function, just adding a preprocess hook is enough.

/**
 * Add destination param to user tabs if set.
 * Implements HOOK_preprocess_menu_local_task()
 */
function THEME_preprocess_menu_local_task(&$variables) {
    $link = &$variables['element']['#link'];
    // check for $_GET['destination'] because drupal_get_destination() always contains at least the current page
    if ($link['tab_root'] === 'user' && !empty($_GET['destination'])) {
      $link['localized_options']['query'] = drupal_get_destination();
    }
}

Replace THEME with the name of your theme or module.


How do I configure a Kernel test? Currently I am able to run the Unit test from the below command

C:\Acquia_dev_desktop\LocalInstance\drupal_new_lab\vendor\bin>phpunit -c
 ../../core/phpunit.xml.dist ../../modules/custom/lse_demo/tests/src/Unit

PHPUnit 6.5.0 by Sebastian Bergmann and contributors.
......                                                              6 / 6
(100%)
Time: 10.62 seconds, Memory: 6.00MB
OK (6 tests, 12 assertions)

But When I tried to do the same with Kernel test I get below error

C:\Acquia_dev_desktop\LocalInstance\drupal_new_lab\vendor\bin>phpunit -c ../../core/phpunit.xml.dist ../../modules/custom/lse_demo/tests/src/Kernel
PHPUnit 6.5.0 by Sebastian Bergmann and contributors.

EEEEEE                                                              6 / 6 (100%)

Time: 11.43 seconds, Memory: 6.00MB

There were 6 errors:

1) Drupal\Tests\lse_demo\Kernel\DefaultControllerKernelTest::testDefaultController with data set #0 ('work', 'User', 'Welcome User to Work')
PHPUnit\Framework\Exception: PHP Fatal error:  Uncaught PHPUnit\Framework\Exception: Could not read "../../core/phpunit.xml.dist".

  thrown in C:\Acquia_dev_desktop\LocalInstance\drupal_new_lab\vendor\phpunit\phpunit\src\Util\Configuration.php on line 189

Fatal error: Uncaught PHPUnit\Framework\Exception: Could not read "../../core/phpunit.xml.dist".

  thrown in C:\Acquia_dev_desktop\LocalInstance\drupal_new_lab\vendor\phpunit\phpunit\src\Util\Configuration.php on line 189

PHPUnit\Framework\Exception: Could not read "../../core/phpunit.xml.dist". in C:\Acquia_dev_desktop\LocalInstance\drupal_new_lab\vendor\phpunit\phpunit\src\Util\Configuration.php on line 189

Ensure  your connection string in the phpunit.php.dist is correct. The correct format is:

mysql://username:password@localhost/databasename#table_prefix


How do I make theme suggestions for pagers? I am trying to create theme suggestions function for pagers in my *.theme. Is this possible in Drupal 8? If it is possible, what is wrong with the following code? Is suggestions_pager_alter the right way to access the hook call so I can add a theme suggestion to a page, so I can override the template. I am not worried about the functions logic.

function mytheme_suggestions_pager_alter(array &$suggestions, array $variables) {
  // Add template suggestions based on the current view mode.
   print_r(); exit;

}

mytheme_suggestions_pager_alter is the correct way to use the hook. The issue was my pager in the view footer was not working and this stop the function from being called


Custom block displayed via Contexts not being shown to anonymous users I am running a Drupal 6 site and I have created a custom block to display a banner ad. The site uses Contexts to display blocks. However I noticed that the block was not getting displayed for anonymous users for some reasons event though I have not set it that way in the reactions. It is getting displayed for user 1 though.

Anyone have any ideas regarding the cause for this scenario?

Also the current block does not have a title? I doubt that but it could be the reason for it not displaying for anonymous users.

I found the source of the problem.

I had used hook_block to create the block. I had specified BLOCK_CACHE_GLOBAL for the cache settings of the block which means the blocks were cached the same way irrespective of the page or the user.

I changed the cache setting to BLOCK_CACHE_PER_PAGE and it solved the problem. (The block hosted an openx ad which was only displayed on pages with certain taxonomy terms.)


Path for a Views 3 page Is it possible to set a Views 3 path for a page to %/% instead of, for example, factsheets/%/% ?

The preview works, but the actual view doesn't.  I'm thinking it shouldn't, but can't find anything to confirm one way or another.

I do not believe that a path such as %/% in views will work.  Have you tried it?

The path factsheet/%/%  is not intercepting other content, it is the path to the view page.  That means that views responds to any page with a factsheets followed by other path segments.  The reason for defining the view pages with % is to create a wildcard variable to be used in contextual filters (3rd column of the main view form).  These filters supplement the basic  filters defined in the first column.  Having two % filters means that you can use two contextual filters.  The top contextual filter takes the first % and the second takes the next % in the path.

The Views preview works because you are only testing the contextual filters.  The path is not being run through Drupal to determine content.


Image preview not generated on node edit page My content type has field type "Image" and using "Media selector" to upload images.

Images are uploaded properly but not previewed at the same time on node add/edit page. I can check that preview is generated with firebug.

If I go to library then again preview not displayed but after saving node it is displaying.

What could be the issue?

There should not be any blank line before opening or after closing php tags. The chances of having it with index.php, template.php,settings.php etc. files


Synchronous XMLHttpRequest on the main thread is deprecated error at the end of ajax call I'm a developer on a freelancing site (the only one actually) and I'm trying to allow anonymous users to bid on a project too. For this reason, I have the following code to check whether the username the anonymous user typed exists in the database, and show them a warning if it does. Now, everything works great, except that if the username exists in the database, I get the error at the end of the post and we can't check again because all Javascript executing is halted. What am I missing?

function tubitekuz_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'webform_client_form_97':
      $form['submitted']['kullanici_adi']['#ajax'] = array(
        'wrapper' => 'webform-client-form',
        'method' => 'replace',
        'effect' => 'fade',
        'event' => 'blur',
        'async' => 'false',
        'callback' => '_tubitekuz_check_username',
      );
      break;
    default:
      break;
  }
}

function _tubitekuz_check_username($form, &$form_state) {
  $parents = $form_state['triggering_element']['#array_parents'];
  array_pop($parents);
  $element = &drupal_array_get_nested_value($form, $parents);
  $exists = FALSE;
  $username = $form_state['values']['submitted']['kullanici_adi'];
  if (!empty($username)) {
    $exists = user_load_by_name($username);
  }
  if ($exists) {
    form_error($element, 'Kullanıcı adı kayıtlı, lütfen başka bir kullanıcı adı seçin');
    $error_selector = '.webform-client-form';
    $commands[] = ajax_command_replace($error_selector, theme('status_messages').drupal_render($form));
    return array('#type' => 'ajax', '#commands' => $commands);
  }
}

The error

  Synchronous XMLHttpRequest on the main thread is deprecated because of
  its detrimental effects to the end user's experience. For more help,
  check http://xhr.spec.whatwg.org/

I at least found a solution. What I did was add the below again to my webform's tpl file, because that was the one which had stopped working.

$(".messages").on("click", function() {
  $(this).hide();
});


How to configure chosen on Form API with an entity_automcomplete widget? How to configure chosen field on Form API with drupal 8.
I have already installed chosen and it's works in User Interface and not in form API.

This peace of code doesn't work:

          $form['tags'] = array(
        '#type' => 'entity_autocomplete',
       '#chosen' => TRUE,
        '#target_type' => 'taxonomy_term',
        '#selection_settings' => ['target_bundles' => ['tags']],
        '#title' => ('Tags'),
        '#empty_value' => ''
       ;

I guess you can't becuase you are using and autocompelte widget, but module states:

  Chosen uses the Chosen jQuery plugin to make your  elements
  more user-friendly.

So you have to refactor your form to use a select element, not autocomplete.


Best technique to debug checkout panes I just need to review/explore the array of built in checkout_panes so that I can debug it. However, the following code does not display any result.

<?php

function mymodule_commerce_checkout_pane_info_alter(&$checkout_pane) {
//Does not work
dpm ($checkout_pane);
//Does not work
drupal_set_message ($checkout_pane);
//Does not work
drupal_set_message (print_r($checkout_pane));
?>

It might be too basic but being a beginner in drupal/PHP I have already spent a day trying to resolving it. Any assistance will be highly appreciated.

You probably don't see a message because the results of the hook you're implementing are cached; you need to clear the cache to get the code to run. You'll want to clear it from within the browser so the message is put in the right session.

Perhaps the easiest method for this is to install the Admin Menu module, which gives you a direct link to flush the caches. When the page reloads after the cache clear, you should see the checkout pane details.

I'd recommend sticking with dpm() (assuming you have Devel installed), that's the best of the three methods in your code for inspecting vars.


Change order of breadcrumbs elements in hook hook_system_breadcrumb_alter I want to add another element to breadcrumb.
I have:
Home > Node Title
I want to add another link between the two elements like:
Home > Link to view > Node Title

I have tried with hook_system_breadcrumb_alter like the following:

/**
 * Implements hook_system_breadcrumb_alter().
 */
function MyModules_system_breadcrumb_alter(Breadcrumb &$breadcrumb, RouteMatchInterface $route_match, array $context) {
  if ( $route_match->getRouteName() === 'entity.node.canonical'){
   $node = $route_match->getParameter('node');
   if ($node instanceof  Drupal\node\Entity\Node && $node->getType() === 'my_node_type'){
     // Get the listing view url.
     $listing_url = Url::fromRoute('view.my_view_id.my_display_id');
     // Add the listing url to breadcrumbs.
     $breadcrumb->addLink(Link::fromTextAndUrl(t('Link to view'), $listing_url));
   }
  }
}

But i get Home > Node Title > Link to view instead of Home > Link to view > Node Title
My question is how can i change the order of the last two breadcrumbs elements?

Create a new breadcrumb instance:

$links = $breadcrumb->getLinks();
// change order of $links
$cacheability = \Drupal\Core\Cache\CacheableMetadata::createFromObject($breadcrumb);
$breadcrumb = new \Drupal\Core\Breadcrumb\Breadcrumb();
$breadcrumb->setLinks($links);
$breadcrumb->addCacheableDependency($cacheability);


Would using hash_pbkdf2() be more secure than the actual code used from Drupal 7? Drupal 7 allows a module to implement a different way to create a password hash. It is sufficient the module changes the content of the Drupal variable password_inc, and implement the required functions in the include file it provides.

If a module would use hash_pbkdf2(), would the hash would be more secure than the one generated from Drupal 7?

The actual code used to generate a password hash is the following. (The code is part of _password_crypt().)

  // Convert the base 2 logarithm into an integer.
  $count = 1 << $count_log2;

  // We rely on the hash() function being available in PHP 5.2+.
  $hash = hash($algo, $salt . $password, TRUE);
  do {
    $hash = hash($algo, $hash . $password, TRUE);
  } while (--$count);

If you take a look at user_hash_password, you can see that the hashing algorithm being used is SHA512. This is something different than the encryption algorithm though, which in its own could use a hashing algorithm.

The way Drupal 7 encrypts passwords actually is PBKDF2, using SHA512.

From Wikipedia:

  PBKDF2 applies a pseudorandom function, such as a cryptographic hash,
  cipher, or HMAC to the input password or passphrase along with a salt
  value and repeats the process many times to produce a derived key,
  which can then be used as a cryptographic key in subsequent
  operations.

Since lots of passwords can be generated in the blink of an eye by modern hardware, it's all about making an algorithm slow. This means generating rainbow tables becomes more expensive.

The problem with SHA-algorithms is that they can still be generated quite fast on GPUs. Some algorithms, like bcrypt are slow by design, which, in my opinion, means it would be a better fit.

  When the standard was written in 2000, the recommended minimum number
  of iterations was 1000, but the parameter is intended to be increased
  over time as CPU speeds increase.

In Drupal 7: assuming DRUPAL_HASH_COUNT is being used in the default encryption algorithm, 32768 iterations (1 << 15) would be used to encrypt a password. This means encrypting a password is quite slow, hence more secure (compared to just 1 iteration). You can adjust the count with the password_count_log2 variable, with a maximum value of 30 (1073741824 iterations) and a minimum value of 7 (128 iterations).

It's not worth it to change encryption algorithm; just let Drupal do its job.

Update: how it's done in D8: https://drupal.org/node/1850524


How to find out if a default image is used in content? I have an Administration View for my content. I want to filter if a default image is used or if there is an already uploaded one.

I don't find a reference for this to use it as field and/or filter in views.

I tried the relationship for Content:Image, but this reveals nothing like "has default image" or something alike.

Any ideas?

EDIT:
I now have a workaround for this. I added a field for the image as a mini-thumbnail, so a visual control if the default image is used is possible. The fields are in a table, so reverse sorting of the images reveals that all default-images come after custom images...

i added a filter criteria on photo:fid(photo is field name for image) not equal to the name of default image and it worked. i hope this will help you


Override contrib Disqus behavior settings I want to override a contrib module's library setting that is being attached to page using hook_js_settings_alter(). But, I am unable to change the setting that is being called in js.

Here is the code that is being called in Disqus module Element:

$element['#attached']['library'][] = 'disqus/disqus';
$element['#attached']['drupalSettings']['disqus'] = $disqus;

I want to override settings in $disqus that is being called in Disqus.js

Drupal.behaviors.disqus = {
  attach: function (context, settings) {
    // Load the Disqus comments.
    if (settings.disqus || false) {

I could override this element with hook_element_info_alter, but is there a way to override the above settings.disqus using other hooks.

You can also use hook_js_settings_alter Something like:

/**
 * Implements hook_js_settings_alter().
 */
function YOURMODULE_js_settings_alter(array &$settings, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
  if (isset($settings['disqus'])){
    // Change settings here
    $new_disqus_settings = [];
    $settings['disqus'] = $new_disqus_settings;
  }
}


Add class based on published state I am trying to add a body class to my site in template.php based on whether or not a node is published or not. I had a look around here and on drupal.org and pieced together some code but I am getting an error. Here is what I have tried so far:

function responsive_process_html(&$variables) {

 if ($node->status == 1){
        //$variables['#attributes']['class'][] = 'pub';
        $variables['classes_array'][] = 'published';
    }

    else {
        $variables['classes_array'][] = 'not-published';
    }
}

... but I am getting this error:

Notice: Undefined variable: node in responsive_process_html() (line 37 of /sites/all/themes/responsive/template.php).
Notice: Trying to get property of non-object in responsive_process_html() (line 37 of /sites/all/themes/responsive/template.php).

I also tried $variables['#attributes']['class'][] = 'published'; instead of $variables['classes_array'][] = 'published'; but it made no difference.

in your theme's template.php:

function mytemplate_preprocess_html(&$vars) {
  $node = menu_get_object();
  if ($node && isset($node->nid)) {
    if ($node->status) {
      $vars['classes_array'][] = 'published';
    } else {
      $vars['classes_array'][] = 'unpublished';
    }
  }
}


Unable to install lullabot/amp and sensiolabs/security-checker i have installed amp and composer manager
today i have been trying to get lullabot/amp installed, i have managed to install composer and drush on my computer but im not sure if they have been installed correctly. The image below shows that they are not installed. This is on my localhost/xampp would that make any difference. Could someone help me get this right as its a big learning curve as i have never used composer or drush since today. Any ideas on how to get this working.

Try these commands, in this order:
1. Go to the docroot and type: drush composer-json-rebuild
2. In the same place: drush composer-manager install
3. If this doesn't work, go to sites/default/files/composer and type: composer install
4. In the end you can run: drush composer-manager update


How to render user picture from page.html.twig file I am using

node.Owner

To print out things like user name, for instance to print the first name out (which is a custom field) it is simply.

{{ node.Owner.field_first.value }}

However if I try to do the same for the user picture I get an error. I have tried

{{ node.Owner.user_picture.value }}
{{ node.Owner.user_picture}}
{{ node.Owner.user_picture.0.value }}
{{ node.Owner.user_picture.content }}

None of these work ?

You can either do

{{ node.author_picture.content }}

or

{{ content.author_picture }}