How to patch module files with netbeans 7.4? Trying to apply patch https://drupal.org/files/webform_preview-435232_1.patch
to webform 7.x-3.19 via Netbeans tool - apply dif-patch. Downloaded this patch and put into drupal root directory. When applying patch to module files see the following: "The patch cannot be applied in the selected context". Module files are in Netbeans project and all paths are properly set. The code to which patch changes are applied exists in the target file, so what else problems can be?

Thanks!

If you duplicate the file in Netbeans that gets patched (this is important that you do this on the file, NOT the project) then right click on it under Tools -> Apply Diff Patch then select your patch file. It should then say everything went as planned and allow you a summary.

You will need to repeat this for every file in the patch, or you can just apply it using Git or one of the other methods listed.


Fix 404 error when adding conditional action to Rule? Subsequent to what I saw in the question 'Don't calculate shipping for specific item', I tried to create a rule with a conditional action (screen capture below), but it causes 404 error:

The export for the rule looks like so:

{ "rules_test_please_delete_" : {
  "LABEL" : "Test (please delete)",
  "PLUGIN" : "reaction rule",
  "OWNER" : "rules",
  "REQUIRES" : [ "rules_conditional", "rules" ],
  "ON" : { "node_delete--page" : { "bundle" : "page" } },
  "DO" : [ { "CONDITIONAL" : [] } ]
}
}

How can I fix the 404 error?

Related resources:

Conditional Rules bug report
Rules feature request

Not sure (yet) what is causing your 404 error, but at this point I'm not convinced it is a bug ...

I imported your exported rule in my own site to experiment with it, this is what happened:

The import worked fine (of course), so I started from the very same Rule as your exported rule.
I then used the Rules UI to also add such "If", and then just show a Bingo-message on the site.
If I would want to add another "if", the URL that would be used for that would have relative path "/admin/config/workflow/rules/reaction/manage/rules_attempt_to_recreate_a_404_error/add/3/if".

Here is the proof of my experiment (an exported Rule, which includes some additional logic within that Conditional Rules Action, and for which I changed the label and machine name also, though only after I imported the rule):

{ "rules_attempt_to_recreate_a_404_error" : {
    "LABEL" : "Attempt to recreate a 404 error",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "node_delete--page" : { "bundle" : "page" } },
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "node:promote" ], "value" : "1" } },
            "DO" : [
              { "drupal_message" : { "message" : "Bingo, this one seems to work ... using \u0022Conditional Rules\u0022 ..." } }
            ]
          }
        ]
      }
    ]
  }
}

The scenario described above was completed in a Drupal 7.5x site, using these versions of related modules:

Rules: 7.x-2.9
Conditional Rules: 7.x-1.0-beta2

I suggest you try to import "my" rule here in your site, and see if you get any other messages while trying to perform that import.

To further pinpoint your issue, have a look at the typical Drupal logging information, you may find there some other indication about what's happening in your site around the time the 404 error occurs.

Notes:

I'm not sure if it could be an explanation for your issue (what it is that causes it), but I noticed that your scenario uses https://, while my scenario was performed using  http:// ... Debugging is the art of taking away all possible causes for an issue, so you may want to try in a site using http:// instead of https:// ... FYI: I tried a similar scenario using  https://, and did not encounter any problem or 404 error.
As an alternative to using the Conditional Rules module, you can also create corresponding Rules Components, with similar Rules Actions to be performed. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".


Devel : what kind of information devel_boot, devel_shutdown and php tweak describes? I have a problem on my website about slow query and many 324 errors.
I tried to resolve them but as i'm new in Drupal i have a lot of difficulties to understand some stuff.

(The website site i'm making actually have 102 modules install, 9 differents roles and a lot of permission on fields, node etc. We don't have a dedicated server so it's very slow and not optimize)

So i tried to do my best and i'm actually working with devel to see if i can do something maybe.

I read this about devel_shutdown on drupal.org but as a beginner i'm not really sure to understand the meaning and the purpose of this function.
So i would like to know more about some function used by devel like:

devel_boot
php peak
devel_shutdown

(devel_shudown = memory_allocated per user? and php peak = memory allocated by the server?)

As you see in my picture, i have a devel_shutdown greater than 41mo (sometimes more than 51mo). For people who worked on Drupal since many years do you think it's normal for a drupal site or do i have to be worried about that?

Thanks,

devel_boot is the memory in use during hook_boot. It is the amount of memory Drupal is using just getting bootstrapped and ready
to run module and theme code.
php peak is the maximum amount of memory in use during your page request. It is provided by the PHP function
memory_get_peak_usage. This is probably the most important metric to consider.
devel_shutdown is the memory in use at the last possible moment it can be measured with code in a request. It is registered
via drupal_register_shutdown_function() which registers functions to be called once all other PHP code has finished executing.

Memory is important to monitor, but it doesn't seem like you are having issues with memory use. I can see from your screenshot that you are using 42MB of memory - that is nothing to be concerned about in most cases.

I would be more concerned about your slow cache queries (highlighted red in your screenshot). Try and figure out why they are taking so long to run.

There are a lot of resources on the web and drupal.org on improving performance. The biggest wins will come from caching and improving SQL performance - then you can start honing in on code profiling to figure out where your time is best spent.

Some resources that may help:

Performance articles on drupal.org
Tuning mysql
Presentation at Drupalcon London

Best of luck!


Ordering fields in template.php file I am trying to theme the user s profile edit form. I Have added a class to the form and the look changed. However i am still struggling to find out how to order the fields in the way i want directly in the template.php file.
Here is my code :

if ($form_id == 'user_profile_form') {
//dsm($form);
//kpr($form);
$form['#prefix'] = '

 Modifer vos informations

';
    $form['#suffix'] = '

';

    $form['field_civilite']['#prefix'] = '

Informations personnelles du membre

';

$form['field_nom'][und][0][value]['#attributes']['class'] = array("nui-input");
$form['field_prenom'][und][0][value]['#attributes']['class'] = array("nui-input");
$form['field_personne_morale'][und][0][value]['#attributes']['class'] = array("nui-input");

$form['locale']['#prefix'] = '

Preferences compte

';

$form['account']['current_pass']['#attributes']['class'] = array("nui-input");
$form['account']['mail']['#attributes']['class'] = array("nui-input");
//$form['field_civilite']['#suffix'] = '';
$form['field_pays_users'][und]['#attributes']['class'] = array("select");
$form['field_profession'][und]['#attributes']['class'] = array("select");
$form['field_conditions_enregistrement'][und][0][value]['#attributes']['class'] = array("dislaynone");
$form['field_conditions_enregistrement']['#prefix'] ='
';
$form['field_conditions_enregistrement']['#suffix'] = '
';

$form['actions']['submit']['#attributes']['class'][] = 'nui-button green';
$form['actions']['cancel']['#attributes']['class'][] = 'nui-button red';

}

Is there a way to override UI that manages the fields display for drupal users ?

Firstly, why template.php for reordering the fields of an entity edit form? You should put this logic in a module and not a theme, look up hook_fomr_alter and hook_form_FORM_ID_alter.

Secondly, if the profile is the default user profile in D7 or you have created one using profile2, you can go to the manage fields section of the entity and reorder the fields just by dragging them. That should change the order on both view page and edit page of the entity, no?

Can you try it out and see if it works! You might not need to write code at all!


How to override some text in the login form located in a block put on a panel? I create a subtheme base on bartik theme.

Then I create a panel, and put the user login block to the panel.

I want to change some text in the default user login from.

I find the theme suggestion about how to override block: block--[region|[module|--delta]].tpl.php

So I try to create block--user--login.tpl.php, And try to type whatever word to this file:

111

when I visit the login form, still default, not changed.

I try to clear cache, can not work too.

EDIT:

I paste the follow picture for better explain.

the 111 is a login form block in page, the right form is a login form block in a panel.

this is my block--user--login.tpl.php file

This sounds like a job for hook_form_alter() and it can be used from either a custom module (eg, MODULENAME_form_alter()) or in this case probably more easily from your theme, eg, something along these lines inside your template.php file:

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

  switch ($form_id) {

    case 'user_login_block':

      // drupal_set_message('<pre>' . print_r($form, TRUE) . '</pre>');  // uncomment to see what you have to work with

      $form['name']['#title']='Enter UserID here'; // originally "Username or e-mail"
      $form['pass']['#title']='Enter Secret here'; // originally "Password"

      break;

    // other form ids go here

  }

}

The above (after clearing caches) will turn this:

into this:

If you need to change other text in the form, you can uncomment the drupal_set_message() and look in the form to see what you have to work with and change it appropriately.

ADDITION:

If you want to get rid of both of the links, eg, the Create new account and Request new password you can either do:

unset($form['links']);

or set the access to them to FALSE, eg:

$form['links']['#access']=FALSE;

Lots more information about this can be found in the Drupal Form API Reference.  I would look into the #weight key for changing the position/ordering of elements in the form.


Displaying data from database I am studying how to create a custom module in Drupal7, so far I have created a simple module that will accept subscribers by registering.

These are the fields I have for my database, and has finished the function that will accept user input.

Table: simple_subscribe

sid , firstname, lastname, email

I then proceeded to create the function that will display all of the subscribers
so far this is what I got

function subscription_view_form() {
  $result = db_query("SELECT * from subscribe");

  $record = $result->fetchAll();
  echo '<pre>';
  print_r($record);
  echo '</pre>';
}

I am using print_r($record); to display the information, but all it displays is the objects on top of the website, before the navigation

Array
(
    [0] => stdClass Object
        (
            [sid] => 1
            [firstname] => John
            [lastname] => Doe
            [email] => johndoe@gmale.com
        )

    [1] => stdClass Object
        (
            [sid] => 2
            [firstname] => Test
            [lastname] => Beta
            [email] => betatester@delta.com
        )

)

edit

I am using the hook_menu() to display a form on /subscriptions but I can't output the subscribers inside the content area, I also wanted to list it in a table, I only did the print_r($records) to test if it is fetching the data. I wanted to know how to output it properly inside the content area not above it?

function subscription_menu() {
  $items[ 'subscriptions' ] = array(
    'title' => 'View the Subscribers',
    'description' => 'Subscription form available for subscribers',
    'page callback' => 'drupal_get_form',
    'page arguments' => array( 'subscription_view_form' ),
    'access arguments' => array( 'access content' ),
    'file' => 'subscription.pages.inc'
  );

  return $items;

I really think you should dive into Drupal's Examples Module to look at how a lot of the hooks and so forth you are (mis)using actually work.

But, quickly:

function subscription_menu() {

  $items=array();

  $items[ 'subscriptions' ] = array(
    'title' => 'View the Subscribers',
    'description' => 'Subscription form available for subscribers',
    'page callback' => 'subscription_records',
    'access arguments' => array( 'access content' ),
    'file' => 'subscription.pages.inc'
  );

  return $items;

}

and

function subscription_records() {

  $result = db_query('SELECT * FROM {subscribe}');
  $records = $result->fetchAll();

  $content = '<pre>' . print_r($records, TRUE) . '</pre>';

  return $content;

}

clean up most of the glaring misunderstandings.

However, you will still need to look into Render Arrays and Dynamic Queries to really clean up your code, as well as the Drupal Theming Guide with special attention to theme_table() to create the page you seem to be after.  And, of course, if you need user input, the Form API Reference is a must. But, once again, all of these are explained and demonstrated in the Examples Module.


How to import Nodes and Node Location data using Feeds module? I would like to use Feeds to import Node Location data together with Nodes themselves.

Each node of a selected content type is or is not assigned to a location.

How to do this ?

Yes, definitely go with feeds except I would go with location module instead of geofield personally as it has direct support from the location_feeds module for mapping in all the relevant details. Its possible that you may need to do two seperate feeds (one for importing the node information and one for the location information) but you can make sure they "come together" by using the same GUID field from your feed on each one. The easiest way is to try :) Set up a dummy file first with only 10 imports.


Disable publish and unpublish options in VBO on the main content view for one role We have a situation where a user that has a role without permissions to administer nodes is able to bypass that restriction and use the VBO widget to mass-publish or -unpublish nodes on the system content view at /admin/content.

My thought was to unset the publish and unpublish values from the select box definition, but after debugging with hook_form_alter, I discovered I could not see the element in the form definition.

I next tried to look at the view object with hook_view_pre_view, but I don't see it there either?

How can I selective alter the VBO widget? We don't want to get rid of it altogether, but we can't have people without permissions publishing and unpublishing nodes.

Edit: I found this question, but it only explains how to delete those operations altogether, for everyone, which is not what we want. We only want them gone for people who don't have permission to publish or unpublish.

Views Bulk Operations (VBO) contains a sub module called ACTIONS PERMISSIONS:

  A module called actions_permissions is included in the package. This
  module generates a permission for each action, and VBO honors those
  permissions before showing or executing the corresponding actions.
  This is useful if you want to provide your VBO to several groups of
  users with different privileges: the same view will accommodate those
  different groups, showing to each the actions that they are permitted
  to see.


What is the correct thing to do when reusing code from an old, abandoned project? I've recently reused the source code from an old project - Anonymous Publishing that seems to have been abandoned around 2008 as a Drupal 5 development version.  There has never been an official release of Anonymous Publishing

I'm interested in the functionality Anonymous Publishing offers for my some of my own Drupal 7 sites, and have started work to convert it to Drupal 7.  The conversion project is currently in my sandbox.  However, the entire idea for this module and about 80 % of the code in the sandbox is from the original author (Ronny López).

I plan to develop this to the point when it is fully debugged and tested, and ready to be placed under drupal.org/projects as an "official" contributed module.

I wonder: What is the "right" thing to (do according to protocol on Drupal.org)? I believe my options are:

To request to become the official maintainer of the abandoned module, and to release my Drupal 7 port as a "continuation" of the abandoned module.
To release my project as a "new" module, with just an acknowledgement pointing back to the previous project.

My question is: What is generally considered the correct thing to do in a case like this?

Request to become the new maintainer, and push your changes as the continuation of the old project.

That is the correct thing to do.


How do i use a renderable array to create a list with children render arrays I have a function which returns a facebook wall feed. The data comes back fine but the point i'm having an issue with is combining the list children with the list array.

I start out by defining the list without children.

   $row = array(
    'item_list' => array(
      '#theme' => 'item_list',
      '#attributes' => array(
        'class' => array('wall-post-list')
      ),
    )
  );

After that i jump in to a foreach loop which i'll omit for clarity since it's large.
First i create a container which will be inside the li of the list and then stuff that container with children like i did with 'account_link' which will be rendered as #markup FAPI elements.

     $list_items[$interation]['data'] = array(
      '#theme' => 'container',
      '#attributes' => array(
        'id' => array($post['id']),
        'class' => array('wall-post-content', $post['type']),
      ),
      'account_link' => array(
        '#markup' => l('','http://facebook.com/' . $post['from']['id'], array(
          'attributes' => array(
            'class' => array('picture'),
            'target' => '_blank',
          ),
          'html' => TRUE,
        ))
      ),
    );

So after building up what this list item is going to have in it I take the $list_items and stuff them into $row['#items']. And now this is where my issue is. The array looks perfect almost to perfect... And when it renders to the page i get

Array

Is there some issue with my approach? or does theme_item_list not render out the children of a li and if so how can I get this to render recursively through the whole array?

Full function code here http://pastebin.com/dr3b4CTX

Correction: seems i was using #theme rather than #type in this situation.

I think what you are expecting is logical. But from the definition of theme_item_list() you can see that it expects value of the data key to be just HTML and hence prints it as it is. I could be wrong here and there is probably a hook_preprocess_* somewhere that pre-renders each item of the list.

Either way, an approach that should work is rendering your item before adding it to the list by calling drupal_render() yourself.

// .. your code .. //
$container_elem = array('#type' => 'container' ... );
$render = drupal_render($container_elem);
$row['item_list']['#items'][] = $render;
// .. your code .. //


Have Select Dropdown of Taxonomy but allow user to enter new term Is there a way to have my Taxonomy Terms in Dropdown but also allow the user to enter a new term (Like autocomplete widget does) if they don't see their term in the select list?

So essentially I would have a backup to allow the user to create one.

My use-case is I have a bunch of businesses, when someone adds a new one, if they don't see their business type, they can just add a new one.

Install the Select or Other module

You can use the Select or Other module to add a dropdown with an Other option.

Selecting Other prompts the user to enter the new value in a separate field.

Your question asked to add the new business type directly; this module adds it to a separate field (however, an admin can later add the business type as a taxonomy term if you wish).

Advantages of this approach

You get admin approval of user input.  This way a bad user can't enter something like Sex sex sex which then appears as a business type on your site.
You have control over how long the list gets instead of letting users add an unlimited number of terms.

Coding it yourself

You can also code this yourself pretty easily using the States API instead of installing the Select or Other module.

Add a new text field, field_businesstype_other, to store the Other values for field_businesstype.

Create a taxonomy term named Other in your "business type" vocabulary.

Then, in hook_form_alter(), add something like this:

  $form['field_businesstype_other']['#states'] = array(
    'visible' => array(
      'select[name="field_businesstype"]' => array(
        array('value' => '123'),
      ),
    ),
  );

Replace 123 with the term ID of the Other term you created.


Customizing the Tag page shown by default in Drupal 7 I made a field in one of my content types as Tags. On the site, they are shown as follows:-

mytag_1, mytag_2, mytag_3.. When I click on either of them, they show me all the pages which are tagged with the clicked tag. How is it doing is beyond me, as I didn't even enable the view.

This is the URL it uses:-
www.mysite.com/tags/mytag_1

Now, my question is how can I customise it. Now it uses node.tpl.php and shows all the pages. I wanna change the layout but don't know how to, as I don't know how these pages are generated.

I also tried making pages as node--tags.tpl.php but to no avail.

Any help?

The ideal way to customize the tags pages(www.mysite.com/tags/mytag_1) is to enable the view "Taxonomy term" and then customize it the way you need it. As you might already know Views provides much more flexibility and easy to customize.

If you do not want to use Views and only want to update the template then refer to the link


How can I create a hook into an external module I want to be able to alter a function inside another module like a hook, but I'm not sure if that's what it's called. I want to alter a function inside another module from my module without changing the external modules code.

This is in version 7.x.

Thanks
Frank N.

PHP offers no mechanism to do that.

If the external function isn't a hook (i.e. it doesn't use module_invoke() or drupal_alter() to gather data from other modules) then the only thing you can do is patch the function in the external file.


How can you filter out other languages Taxonomy Terms from an exposed filter? I am working on a View for a content type which has a Taxonomy Term field.  The vocabulary is setup with the Translation mode 'Translate'.  The terms have all been translated so that the terms explicitly set Language (currently English and Spanish).  The View has an exposed filter for this field and its showing both languages terms.  How can I configure Drupal to only show the taxonomy terms for the current users language?

Relevant installed modules: Internationalization (i18n), Views translation (i18nviews), Taxonomy translation

I've read a lot of forums about how to get more languages terms to show, just not how to filter them out when you don't want to show them all.

It's a long time ago but I leave my comment here for anyone who came across this from Google.
If you have installed "i18nviews" module, then you need to enable Multilingual select (i18n_select) module as well and your list will be filtered out based on the selected language.


Group ID Filter in Block? I want to show teasers of content posted to an OG group.  I want public and private groups, so the user must have view access to that group to see the content. I have a Group (named "Group") and a content type ("Topic") that users can post to the group.

I create a block in views and place it bellow content, then when the group is displayed the block is displayed.  Currently the block will show ALL content, I do not know how to show content for CURRENT GID. The GID is different then the NID (example nid = 3, gid = 1).

I installed Pathauto and gave the rule to group/[node:nid].
I then created a block and want the block to show all Group Content.  I set it only to display on group and group/* This is associated with og_members block & og_nodes block won't display content but unfortunately the individual did not mention his views filter (or contextual filter).
I can get all content to show up in this block, but I do not know how to filter the current nodes group id from the block.

Updating views to views 3 Beta 3 created 2 new OG views, OG Nodes was one of them and it fixed the issue.

Note:  Adding blocks to "Content" would ignore weight (order) of the blocks, I had to create a content-top and content-bottom area in page.tpl.php!


Can regions be printed within a node template? Can regions be printed within a node template, or are regions strictly confined to page templates?

You can print regions inside any template, but they aren't available out of the box in the node.tpl.php template. To make them available, you'll create a new variable for use in your node.tpl.php template that'll contain all the region content.

Creating new template variables is done by using a preprocess function. In your theme's template.php file, create a function that looks like this:

function mytheme_preprocess_node(&$variables) {
}

Replacing mytheme with your theme's short name. Now, in order for Drupal to recognize this new preprocess function, you need to rebuild your site's theme registry. This is as straightforward as going to Configuration → Development → Performance and pressing the "Clear all caches" button at the top.

Now, the way preprocess functions work is that $variables contains an array that corresponds to your template's available variables. For example, in node.tpl.php, $submitted contains the author byline. In the preprocess function above, it's found in $variables['submitted'].

To mimick what you have in page.tpl.php, where you have an array called $page that contains all the regions, you'd want to populate $variables['page'].

The problem is that $page in node.tpl.php is already populated with a true/false value that lets you know whether you're looking at the node by itself or in a listing.

So to avoid that name collision, populate $region instead:

function mytheme_preprocess_node(&$variables) {

  // Get a list of all the regions for this theme
  foreach (system_region_list($GLOBALS['theme']) as $region_key => $region_name) {

    // Get the content for each region and add it to the $region variable
    if ($blocks = block_get_blocks_by_region($region_key)) {
      $variables['region'][$region_key] = $blocks;
    }
    else {
      $variables['region'][$region_key] = array();
    }
  }
}

Then, in your theme's node.tpl.php template, you can render any region by doing the following:

<?php print render($region['sidebar_first']); ?>

Where sidebar_first is the name of the region you want to render.


Using Drupal to authenticate user on a remote web site I have a custom php web site on which I need to authenticate users based on their credentials in a Drupal site.  I am not very experienced with Drupal but am (mostly) finding my way.  It is a Drupal 7 site.

I have found that I need the Services, Rest Server and Libraries module and they are all installed.  I am using this tutorial for setting up Drupal:
https://www.drupal.org/node/2424977

and this code for my remote site:
Using drupal login system for another platform

I am stuck on the tutorial where I am trying to get a user token from the Drupal site.  I have set up an endpoint ("rest", and when I go to it in a browser I get:
"Services Endpoint "remotetest" has been setup successfully."
However in the Firefox RESTClient when I try to post to https://sub.domain.org/rest/user/login.json I get:

Status Code: 404 Not found : Could not find resource user.
Cache-Control: no-cache, must-revalidate
Connection: Keep-Alive
Content-Length: 0
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 Nov 2017 18:55:24 GMT
Expires: Sun, 19 Nov 1978 05:00:00 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.18 (Ubuntu)
X-Content-Type-Options: nosniff

I have tried a few things like enabling Drupal permissions for the Services module for anonymous users (all items except manage Services) but don't know what else to do. I have also tried the login directly (why would I need a token?) but I get an error "The requested URL returned error: 404 Not found : Could not find resource user." It seems like steps are missing in the tutorial.

Suggestions?

The tutorial does not indicate that you must enable the user resource in the rest service you set up.  Doing so allows it to work.


How to make slideshows work on mobile devices browsers? I created a view formatted slideshow using Views Slideshow
and another formatted flexslider using Flex Slider.

But the two blocks show no content when displaying the page from a mobile device.

What's wrong (with flexslider as it support mobile) or how to make the slideshow work for mobile using one of the two modules listed?

Download the FlexSlider library from https://github.com/woothemes/FlexSlider

Put the folder in a libraries directory sites/all/libraries and also

Try installing the FlexSlider Views Slideshow module which integration with Views Slideshow and FlexSlider

  This is the FlexSlider Views Slideshow module which used to be
  included in FlexSlider by default.

This tutorial shows you how to create a responsive slideshow using the Views Slideshow module and jQuery FlexSlider.


Track error on file permission? I get this error when running Status Report:

  CTools CSS Cache  Unable to create

  The CTools CSS cache directory, ctools/css could not be created due to a misconfigured files directory. Please ensure that the files directory is correctly configured and that the webserver has permission to create directories.

Where should I look for this folder?

That should be in the base of your site's file directory. Navigate to /admin/config/media/file-system to see where it is configured.


How to Auto Publish nodes based on set interval? I have nodes being generated from a Feeds import on a periodic basis, however when they are imported I would like them to be queued to be published on an hourly basis (or x minutes)

I have looked at Scheduler and also Publish Queue. But those modules require input. I want this done automatically, so that as soon as nodes are created via feeds they are put into a queue to be published over a set interval of time.

How can I make this happen? Maybe I can just code this myself if there is no option out there. Something along those lines might work:

Get oldest node unpublished node
Publish node
Run this code once every cron run

Any suggestions?

The Rules module is your friend. But if that's too much overhead and you don't need the flexibility, I would suggest coding it on your own.

Also see this question for executing rules on cron.


How to install drush 8 properly on Debian 8? Finding hundreds of articles and documents about how to install drush and none of it explains where exactly and how properly I got a bit lost.

I've got a Debian 8 system with a root user, NGinx and a ssh user.
Now I'd like to go with drush 8 to be ready for Drupal 8 soon.
But I don't feel like installing git on my server - is this common practice? I usually think the fewer software the better?

So - any chance of installing drush without having git?

Next thing that all instructions seem to forget:
As which user do I need to install drush and composer? (I did it now as the ssh user with the result that root can't use drush).

And eventually: Which directory would be correct to have drush installed? /usr/bin/ ? With a symlink? Or directly there?
Does the NGinx user (www-data) need to be able to use drush? (I guess yes for drush pm-update?)

Very lost here - hope someone can shed some light.

(Updated to fix links and clarify Drush 8 vs 9.)

Debian still (as of February 8th 2018) comes with Drush 5.10 which is completely unacceptable.

There is no reason to use Git to download Drush. Either

If you want the old Drush 8 (that works for Drupal 8.3 and older, including Drupal 7) download a single PHAR file using the the straight forward instructions on http://docs.drush.org/en/8.x/install/ or
If you want the current Drush 9, install a site-local Drush (with Composer) and Drush Launcher (as a PHAR file) as described on http://docs.drush.org/en/master/install/


Taxonomy term reference field only from top level terms of a vocabulary I have a multilevel taxonomy term vocabulary

Degrees and
i. Specializations

I'd like to use it in two content types. In one case only the top level terms should appear for users, while in other case users can choose only from the 2nd level (this one can be solved by Hierarchical Select module).

Is there any extension of taxonomy form elements that can limit the level that  users can choose from?

If you replace your taxonomy term reference field with an Entity reference field you will be able to use the Reference field option limit module to restrict the available options for dependant fields. If you need to apply further restrictions you can also generate your options lists via special entity reference views.

Note however that by switching the field type to entity reference you will no longer be able to use taxonomy term specific fields and filters for those fields in views.


How do I fetch a vote given on a node and programmatically apply this vote to the author of the node? I am using the voting api, fivestar and rules modules to try to fetch the vote a user gave to a node (article) and apply that same vote/value to a fivestar field of the author of that node. How can I accomplish this?

{ "rules_cast_a_vote_when_the_author_casts_a_vote_on_their_article" : {
"LABEL" : "Cast a vote when the author casts a vote on their article",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "cast", "fivestar", "vote" ],
"REQUIRES" : [ "rules", "rules_conditional", "voting_rules" ],
"ON" : { "voting_rules_insert_node" : [] },
"IF" : [
  { "entity_is_of_bundle" : {
      "entity" : [ "node" ],
      "type" : "node",
      "bundle" : { "value" : { "article" : "article" } }
    }
  },
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_my_fivestar_rating" } },
  { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_the_editor" } }
],
"DO" : [
  { "entity_fetch" : {
      "USING" : { "type" : "user", "id" : [ "node:field-the-editor:uid" ] },
      "PROVIDE" : { "entity_fetched" : { "editor_uid_fetched" : "Fetched editor uid" } }
    }
  },
  { "CONDITIONAL" : [
      {
        "IF" : { "entity_has_field" : {
            "entity" : [ "editor-uid-fetched" ],
            "field" : "field_my_fivestar_rating"
          }
        },
        "DO" : [
          { "drupal_message" : { "message" : "When conditional is TRUE: [editor-uid-fetched:name]\u0027s ID has been fetched and is: [editor-uid-fetched:uid]" } },
          { "data_set" : {
              "data" : [ "editor-uid-fetched:field-my-fivestar-rating" ],
              "value" : [ "node:field-my-fivestar-rating" ]
            }
          }
        ]
      }
    ]
  },
  { "drupal_message" : { "message" : "vote:value [vote:value]\u003Cbr\u003E\r\nnode author fetched ID: [node-author-fetched:uid]\u003Cbr\u003E\r\nnode author fetched name: [node-author-fetched:name]\u003Cbr\u003E\r\neditor rating now: [editor-uid-fetched:field_cr_rating]\u003Cbr\u003E\r\neditor rating value now: [editor-uid-fetched:field_cr_rating:value]\u003Cbr\u003E\r\neditor rating now (hyphens): [editor-uid-fetched:field-cr-rating]\u003Cbr\u003E\r\neditor rating value now (hyphens): [editor-uid-fetched:field-cr-rating:value]\u003Cbr\u003E\r\n\r\n" } }
]

}
}

I undesrtand that your question is about a 'code' solution, this one is not but it works, you'll need rules conditional module, and voting rules module , it adds an action: 'a node has been rated', then fecth node-author-by-id, make shure both have the same field (user-bundle and contentype), set user-author-rating-field-value with your node-rating-field-value, or import rule, please edit your field-rating machine name and dependencies as needed. i hope it helps.

    { "rules_set_node_five_star_rate_to_node_author" : {
    "LABEL" : "set node five-star rate to node author",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "RATING_MODULE_MACHINE_NAME" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_YOUR_FIVE_STAR_FIELD" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : { "type" : "user", "id" : [ "node:author:uid" ] },
          "PROVIDE" : { "entity_fetched" : { "entity_fetched_author_by_id" : "author_by_id" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "entity_has_field" : {
                "entity" : [ "entity-fetched-author-by-id" ],
                "field" : "field_YOUR_FIVE_STAR_FIELD"
              }
            },
            "DO" : [
              { "data_set" : {
                  "data" : [ "entity-fetched-author-by-id:field_YOUR_FIVE_STAR_FIELD" ],
                  "value" : [ "node:field_YOUR_FIVE_STAR_FIELD" ]
                }
              }
            ]
          }
        ]
      }
    ]
  }
}


Add configuration options for Views block under Structure > Blocks > configure I'm building a module that defines several blocks and provides custom options for those blocks via hook_block_configure(). Two of these blocks were built from scratch using hook_block_info() and their configuration options defined in hook_block_configure() display as intended. In other words, if you navigate to Structure > Blocks and click configure for either of these two blocks, the custom configuration options are displayed as intended.

The third block is a Views block, defined by hook_views_api() and hook_views_default_views(), and the hook_block_configure() hook doesn't trigger at all for this block. Navigating to Structure > Blocks and clicking on configure for this block just shows the default block configuration options.

What I would like to know is how to add custom configuration options for this Views block or a similar solution. Is there any way to register this block so that it will also listen in on the hook_block_configure() hook? Or is there maybe a different hook that would allow me to accomplish my goal? My Google-fu has yielded nothing.

To "add fields to the block configure pages for these two blocks" (as in your question), you should look at the Bean module as a possible alternative to answer this question. Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

PS: this is a D7 module, integrated in core in D8 ...


Can't load my template file My human.tpl.php file is located in /tpl folder. Im trying to use hook_theme from the module:

    function human_theme($existing, $type, $theme, $path){
    return array(
        $item['human'] = array(
            'template' => 'human',
            'path' => drupal_get_path('module', 'human').'/tpl',
            'type' => 'theme',
            'variables' => array(),
        ),
    );
    return $item;
}

Why is this not working? I have some basic html code in my template file for testing purposes so it should show me something, but I get nothing back. If more information is needed, please let me know and I will add. Full code of a .module file can be found here.

You have two returns (the second will never be hit). You have declared your array twice. It should be this:

function human_theme($existing, $type, $theme, $path){
  return array(
    'human' => array(
      'template' => 'human',
      'path' => drupal_get_path('module', 'human').'/tpl',
      'type' => 'theme',
      'variables' => array(),
    ),
  );
}


How to create a Hook_Schema for Fieldset Form? i have a form i would like to have the values submitted into a table in mysql database using hook_schema in a .install file. problem is i have no idea how to properly write it out being new to php  and all. i basically have a custom form with over 50 total field divided up into 3 different fieldsets displayed to user depending on checkbosed clicked. what is the best way to write a hook_schema to upload the submission values from my form into my database?

is your schema already defined for a table in MySQL somewhere, did you already make it in like phpmyadmin? ... if so, the Schema module will show you the exact PHP needed for hook_schema

I recommend:

make a table in your drupal database using something like Navicat, phpmyadmin, mysql admin ... whatever. The table columns are your form field inputs and at least additionally a primary key.
install Schema module and goto admin/structure/schema/inspect. Copy + Paste + Profit

// in yourmodule.install
function yourmodule_schema() {
  // ... paste the $schema['your_table'] textarea stuff Schema page auto-generated for you.
  return $schema;
}


How do I avoid checking for updates for a specific module? In a current project I have had to patch the life out of a few modules (node hierarchy, workbench access and a few more). These modules are now absolutely perfect for the project's needs and are very unlikely to break with future updates to core.

That being said, when the app is handed over the clients will have full (user 1) access to the system and will therefore be warned when these modules have available updates. And they will update them, no matter how many times I beg them not to (oh how easy life would be without clients!).

Is there a way (perhaps in the modules' .info files) to persuade the update manager not to check for updates for these modules?

EDIT

I'm aware of the project status url key that's available for the .info file so I guess I could set that to a non-existent URL but I'd much rather do this in a clean way if possible.

You need to implement hook_update_projects_alter().

  Alter the list of projects before fetching data and comparing versions.

  Most modules will never need to implement this hook. It is for advanced interaction with the update status module: mere mortals need not apply. The primary use-case for this hook is to add projects to the list, for example, to provide update status data on disabled modules and themes. A contributed module might want to hide projects from the list, for example, if there is a site-specific module that doesn't have any official releases, that module could remove itself from this list to avoid "No available releases found" warnings on the available updates report. In rare cases, a module might want to alter
  the data associated with a project already in the list.


How to track user node views and quiz results I am searching for the easiest way to track wether particular user has read particular group of nodes (training material) and did the quizes that are related to those nodes. In success case I would like to grant user some points and a badge and for the site administrator to have a list of all the training material with "read"/"not read" results per user. I know that there could be various ways to do this, but I am not sure, which one would be the easiest one.

using Goals + Rules (but I can't find how exactly can I track wether user has visited particular node).
using Activity module?
using Heartbeat module?

None of these looks like it is possible to do such thing without coding, or I am missing something?

thanks!

I'd use the Goals module (disclosure: I'm its maintainer) to "track wether user has visited particular node" (as in your question). No need for custom coding. Read on for details how to do so ...

Configure a goal

Navigate to the relative path admin/config/goals/manage and use the link "Add a goal" to define just 1 goal, with a description (say):

View some node, only 1 time.

Configure a task

To achieve the above goal, define the Task(s) to be completed. Even though there could be multiple tasks to be completed for a single goal, in your case you just need 1. It's simply View a node (assume we use a machine name like view_a_node).

Track progress while performing tasks

To track the progress made by a single user to complete this task, you only have to write an appropriate rule, using the Rules module, to record relevant events happening in your site, which are related to the completion of the task to reach the goal.

For the goal/task described above, you'd only need 1 (extremely basic) rule, which would look like so:

Rules Event: Content is viewed.
Rules Events:

Check user has role "authenticated" (how else would you know which user it is ...).
Check the node id of the node being viewed (eg: node=123).

Rules Action: Record a task for Goals (obviously, the task to be recorded is "View a node"). This is where part of the Goals magic happens, such as verifying the requirements in the optional task configuration options for a task (only once an hour, etc).

Here is a rule which you could probably use for this (if you have a "task" defined with the exact machine name view_a_node, just use the Rules UI to import it in your own site to get you going, if not adapt that machine name prior to starting such import):

{ "rules_record_task_view_a_node" : {
    "LABEL" : "Record task view_a_node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "goals" ],
    "REQUIRES" : [ "rules", "goals" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "article" : "article" } } } },
      { "data_is" : { "data" : [ "node:nid" ], "value" : "123" } }
    ],
    "DO" : [
      { "goals_task_record" : {
          "task_name" : "view_a_node",
          "user_to_save_for" : "[site:current-user]",
          "task_id" : "Node ID of viewed node = [node:nid]"
        }
      }
    ]
  }
}

The above gets you started for a single node like node/123. To enhance it to also verify node/124, node/125 and node/126 (it doesn't matter in which order they are viewed ...), this is how to do so:

Add 3 similar tasks to be tracked (for the 3 other nodes), with a machine name that includes the relevant node id.
Duplicate the above rule for each of the other nodes (only difference is the node id in the Rules Condition and the machine name of the Task in the Rules Action). As an alternative, use the Conditional Rules module to consolidate those 4 rules in a single rule.


How to detect order type (recurring or not) in order confirmation and shipping confirmation email templates? When order is placed an emails is sent to the user generated with template commerce-order-receipt--default.html.twig
When order is shipped another email is sent to the user, now generated with template file commerce-shipment-notification.html.twig
How to detect from those 2 files if it's a first order (generated by user action) or it was recurring order (generated automatically, by cron)?
I need a way to display different content inside those emails based on this criteria.

Found the way - I can check variable order_entity.bundle for order type and it's value can be "default" or "recurring".
However order receipt email is sent only once, when order is placed and not when recurring order is created, so it's not used for recurring order types at all. I guess that's normal.


Multiple date fields I have a customized Calendar view. When I created the view using the template, it allowed me to select one field to be used as the date.
Is it possible to have multiple date fields, for example Due date, Start date, and Review Date? The node should show on the calendar for each date.

I was able to accomplish this adding or statements to my calendar's existing contextual filter. I added each date field as an "or" statement and now it shows each date on the calendar.


Problem installing Devel module onto site I went to drupal.org, copied the link for the Devel module, went to my site, New Module (under extensions) paste the link into the "Install from a URL" and when I hit Install it gives me the following error message: "Failed to fetch file due to error "cURL error 77: SSL: can't load CA certificate file /Applications/DevDesktop/common/cert/cacert.pem (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)"
Unable to retrieve Drupal project from https://ftp.drupal.org/files/projects/devel-8.x-1.0-rc1.tar.gz."

How can I fix this?

Download this file http://curl.haxx.se/ca/cacert.pem save it on the desktop.

Then Copy( or move) into the  C:\Program Files (x86)\DevDesktop\common\cert\


Programmatically render a view as HTML I am using a custom function. In a button click i want to display view page. Here i want to render my view programatically in html format. How can i do that?

This is my jquery code:

$('.view-all-content').click(function () {

  $.post("/callajax", {
    'action': 'get_data_from_view',

  }, function (data) {

    console.log(data)

    // if (data == "gg") {
    //    console.log("suc")
    // }

    $(".view-all-content-result").html(data);

  });

});

In my function.php

function get_data_from_view() {

  $view = \Drupal::service('renderer')->render(views_embed_view('article_list', 'page_5'));

  // Other code ...

  echo $view;
}

Try this

\Drupal::service('renderer')->render(views_embed_view('VIEWSID', 'DISPLAYID'));


How can we configure the Master slave concept in Drupal 7? I have one large scale website and hosted on AWS. I want to enable Master-Slave concept on it. How can it be possible to configure the same?

Yes, Drupal supports master/slave style database replication.
Note: master/slave replication configuration is done at the database server level. Drupal simply utilizes the replicated databases by using the slave server when one database isn't available, or for specific 'slave' marked queries ( see db_query "target" option ).
See the fully commented default.settings.php for Drupal configuration details.

For each database, you may optionally specify multiple "target"
databases. A target database allows Drupal to try to send certain
queries to a different database if it can but fall back to the default
connection if not. That is useful for master/slave replication, as
Drupal may try to connect to a slave server when appropriate and if
one is not available will simply fall back to the single master
server.
The general format for the $databases array is as follows:

$databases['default']['default'] = $info_array;
$databases['default']['slave'][] = $info_array;
$databases['default']['slave'][] = $info_array;
$databases['extra']['default'] = $info_array;


Anyone have any luck exposing Ubercart's "enter your VAT" part of the form? I am using http://drupal.org/project/uc_vat and http://drupal.org/project/uc_vat_number and am able to enter different VAT rates, but a the moment it seems that it simply applies whatever is the last item in the list as VAT. I need to find where in the interface (I may be being blind as well as ignorant) it will allow me to enable the part of the form where the user can select that they have a VAT number to enter to avoid paying VAT. I am pretty sure it is part of the interface, I just don't know where to find it.

If I find it, I will post and/or close the question. Many thanks for any and all support!

This module is dependant on the billable address module being enabled. I did not need the billable module and thus is did not show (javascript dependancy).


How custom a form with twig I make a form programmatically, and I am looking how a web designer can change render.

 public function buildForm(array $form, FormStateInterface $form_state)
{

    $form['metier'] = array(
        '#type' => 'search',
        '#title' => $this->t('Métier'),
        '#default_value' => '',
        '#placeholder'=>'Rechercher une personne par son métier',
        '#attributes' => array('title' => $this->t('Rechercher une personne par son métier')),
    );

    $form['position'] = array(
        '#type' => 'search',
        '#title' => $this->t('Où'),
        '#placeholder'=>'Où',
        '#attributes' => array('title' => $this->t('Où')),
    );

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

    return $form;

}

If the path of my form is /test the suggestion template form--test.html.twig doens't work.

I would like give access to a template for webdesigner can custom the render.

I can do something like that :

  $form['metier'] = array(
        '#type' => 'search',
        '#title' => $this->t('Métier'),
        '#default_value' => '',
        '#placeholder'=>'Rechercher une personne par son métier',
        '#attributes' => array('title' => $this->t('Rechercher une personne par son métier')),
        '#prefix'=>'
',
        '#suffix'=>'
'
    );

But it's hard coded.

So I am looking for a way to return a brut table and let the web designer make his template.

The best way for the designer ll be :

form--test.html.twig

{{ form.metier }}

{{ form.position }}

{{ form.submit }}

I don't know if I am right, I have try to return my variable $form to a template like that :

return array(
    '#theme' => 'form_test',
    '#form' => $form,
  );

All work I can access to my fields with

  {{ form.metier }}
  {{ form.position }}
  {{ form.submit }}

But the submit button doesn't work because the hidden fields are not display like the form_token and he is not in my variable $form.

You need to implement hook_theme() in your .module file to define a new theme implementation, set the #theme key in your form to the name of your implementation and create a twig template with this same name, but replacing hyphens with underscores:

example.module

function example_theme() {
  return [
    'my_awesome_form' => [
      'render element' => 'form',
    ],
  ];

Form/MyAwesomeForm.php

class MyAwesomeForm extends FormBase {
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);

    $form['#theme'] = 'my_awesome_form';
    [...]

templates/my-awesome-form.html.twig

<form{{ attributes }}>
  {{ form.form_build_id }}
  {{ form.form_token }}
  {{ form.form_id }}

      {{ form.name }}

      {{ form.type }}

  [...]

In this example form.name and form.type are your form fields, the array keys that you used to create the form, and I used bootstrap markup to show them in two columns.

Hope this helps.

Regards.

PS: This is a copy of my post at https://www.drupal.org/node/2788835#comment-11785706. I cloned it here because I'm not allowed to post comments.


CKeditor + Media: insert image tag rather than link to image I want to insert an image into node body content using Ckeditor and Media. Everything seems to work except all I get is a link to the image file but I would like it to insert an image tag. When I click Ckeditor's Add Media button and choose an image I get an option Current format is and I can choose from Default, Preview and Teaser. While the first two return nothing, Teaser at least inserts a link to the image file.

How can I get it to insert an image tag instead of a link?

I am using Drupal 7.22 with Media 7.x-2.0-unstable7, Wysiwyg 7.x-2.2 and the latest Ckeditor.

Insert Module will do that, it will place the image in body field. Support for all major WYSIWYG editors, including tinyMCE, CKeditor.

  Insert is a utility that makes inserting images and links to files
  into text areas or WYSIWYGs much easier. It adds a simple
  JavaScript-based button to FileField and ImageField widgets. When used
  with ImageField and ImageCache, images may be inserted into text areas
  with a specific ImageCache preset.


Is it possible to select all results in Views bulk actions form? By all results I mean even those that are not displayed on the current page(if there is paging).

The simple bulk action support in Drupal 8 core does not currently support this feature.


Should I use Drupal or a Mediawiki to create a site like Wikihow? I have some basic experience in using Drupal 7 and I am currently  starting a new project where I want to create a wiki site with the same functionalities of  Wikihow.com. I have done some research and most wiki sites seem to be built on a wiki open source software such as Mediawiki.

Because I have some experience in Drupal and really like it, I would like some advice on whether to build a Wiki in Drupal (perhaps using the Drupal Commons Distribution), or use a wiki platform instead?

You have the source code for Drupal, as well as for Mediawiki (that's the nature of scripting languages such as PHP). This means, both platforms allow endless customization and you can implement your requirements using any of those systems. A decision between Drupal and Mediawiki is therefore not a technical decision, but a business decision: which platform will get the job done with lower costs?

If your are working on your own, you have to weigh "getting it done using something you know" against "risk using a new system but allowing you to become proficient in it". There are also other factors that come into play, like time constraints and the pricing scheme.

A correct answer to your question cannot favor one or the other platform. It can only give you suggestions on what factors to take into account so that you can decide for yourself. My list is not exhaustive.


View contextual filter not working inside Panels I have a view with a contextual filter of type "Raw value from URL".  This block view works fine in the page footer. But when added inside Panels & Page Manager, the view stops working. Hence it seems that Panels is somehow blocking the view from being able to access the URL.

As a test, I have the view in Panels and in the footer on the same page, and the footer view displays fine, but the Panels view does not, giving me a "Page not found" error.

I read I need a "context" in Panels to pass information to a view.  I also read that view contextual filters that use URLs don't need contexts in Panels, so I'm finding conflicting information.

Every time I try to create a Panels context, I get an error, mostly since I have no idea what to enter into the form fields.

The view looks for a value in the URL, such as /puppies/10, where 10 is the node of the puppy. Then the view will only show information for that puppy.

Most of the information out there is for Panels on Drupal 7, and there seems to be enough of a difference that I can't figure it out for Drupal 8.

I had the same problem and figured it out. Enter /your/path/{parameter} for your page path and the Page Context link will change to a Page parameter link. You can use any word for {parameter}, it is just a variable name. You specify the type of the parameter under Page parameter. It would have saved everyone an enormous amount of time, if this was included in the instructions underneath the path field.


Link to node in View with TWIG I have a set of nodes, some of which are just a title, while others have body and other content.

I'm trying to create a view, which lists the node titles. If the body of the node contains content, the title should link to the node, but if the node body is empty, it should just display the title as plain text.

I think I can achieve this by rewriting the title field in the view with TWIG.

I've got it working so it detects the body and displays a link, but I'm not sure what to put for "url" in the link.

{% if body|render|trim is not empty %}
{{ title }}
{% else %}
{{ title }}
{% endif %}

How can the TWIG code get the url of the node to link to?

In the view fields search for "Link to content", add the field, exclude this from presentation and move it to the top, and now you can use:

{% if body|render|trim is not empty %}
  {{ view_node }}
{% else %}
  {{ title }}
{% endif %}


How to display a list of products in same taxonomy as current product? I want to display a list of other products from the currently-viewed product's taxonomy/taxonomies on the product page. It would ideally be a text-only list, and would be limited to five or ten products. I'd rather not go the route of node/entity reference fields, as I have hundreds of products. Yes, it would be more accurate to do it that way, but displaying products based on their taxonomy would be accurate enough for my purposes.

Can anyone tell me how to set up something like this? Perhaps with Views?

Thanks!

After a bit more digging, I came across a wonderful solution: http://scito.ch/content/show-related-nodes-block-based-taxonomy-terms-views-3-and-drupal-7

Create view (block)
Add fields (title, a small image, date, whatever
you like). Or teasers, what works as well.
“Arguments” is from now on called “Contextual filters”, so go there.
Add the filters: “Content: Has taxonomy term ID (with depth)” and “Content: Has taxonomy term ID depth modifier”
Configuration on this filter: → When the filter value is NOT in the URL: → Provide default value → Type: Taxonomy Term ID from URL →
under that, check the box “Load default filter from node page,
that’s good for related taxonomy blocks.” → now check the boxes of
the taxonomies you want involved here
Now you need to add the second filter in order to exclude the current node from the list. Click [+] button of the contextual
filters section.
Select Content: Nid
Set the ‘when argument is not present’ to ‘Provide default argument’
Set the ‘Default argument type’ to ‘Content ID from URL’
Go to “MORE” , and check the “Exclude” box.
Move the filter “Content: Nid” to the top position.
Add a block to your view and embed the block on your node pages
Save your view


How can I remove username from title on profile page? I am trying to remove the user name from the users profile page. I tried to remove the div using CSS, but it is the same div as for all other nodes, so this means all other titles disappear. I only want to remove the user name on the profile page. I am using the module Real Name, so this is the last place where the user name is visible. I have only found tips for drupal7 dated years back when googling. Any ideas on how this could be done?

I discovered now that "Page Title" is in a block in Drupal 8. I set this block to not show on /user/*, which worked great.


Is it possible to theme node add form in drupal 7 I am using zen drupal-7 sub theme. I have created a content type named edison. I need to change the node add form for the user. I've tried adding page--node--add--edison.tpl.php in template.php. I used the following code:

if (isset($variables['node'])) {
  $variables['theme_hook_suggestions'][] = 'page__node__' . str_replace('_', '--', $variables['node']->type);
}

When the $variables['theme_hook_suggestions'] variable is printed, it looks like this:

Array (
  [0] => page__node
  [1] => page__node__add
  [2] => page__node__add__edison
  [3] => page__node__edison
)

The custom .tpl is not overriding the page.tpl.php.

The $variables['theme_hook_suggestions'][] only suggests theme for the node itself not the form to add content!

You have to let us know how exactly do you want to display your form. Some times a few CSS codes may be enough.

Anyway to theme the node add content you can use hook_form_alter to add some attributes to the form elements, add CSS classes or ... . You can also use Firebug to get the fields ID or class names then use CSS to theme them.

The following code

function THEME_form_alter(&$form, $form_state, $form_id) {
      print $form_id;
}

gives you the ID of the form. Find the ID of the node add form and do the changes. like

function THEME_form_alter(&$form, $form_state, $form_id) {
      if($form_id == "NODE_ADD_FORM")
            ////
}


drupal_add_js to Search module I'm trying to add some custom JS to the search module in Drupal 6. I've added all of my custom JS through template.php via THEME_preprocess_node()

How can I add JS to the search module (without hacking the search module) via template.php in my theme?

Use THEME_preprocess_search_block_form to add drupal_add_js calls for the required javascript.


Sort nodes based on the amount of tags that match a specific node tags Is there anyway to sort the nodes on a views display using the amount of matching tags of a specif node? I would like to have a views display that shows me all the nodes that most match with a given node.

For example: I have one node with three terms associated with it and I'll pass this node to a views as an argument. The views should display first the nodes that have this same three terms, after that it should display the nodes which match with two of the three terms, after that the nodes that match one of the three terms and after that the nodes that doesn't match any of the three terms.

I couldn't find something that could solve this problem for me. If there isn't any implemented solution I'd like to know if it's feasible to implement this on Drupal 7.

Check out Similar by Terms module. This Drupal module attempts to provide context for content items by displaying a block with links to other similar content. Similarity is based on the taxonomy terms assigned to content. Blocks are available based on similarity within each of the defined vocabularies for a site as well as a block for similarity within all vocabularies. There are two methods of sorting. 1) Based on the most number of matching terms. 2) Based on lest used terms.

Or you could use the Relevant Content module. This module provides two ways of referencing relevant content. Both of these methods provide configuration to filter for specific content types and vocabularies, limit the maximum size of the result and provide some header text. The result on both cases are a list of nodes which the module considers most relevant based on the categorization of the current page. This is achieved by finding other nodes which are of one of the allowed types and have the most number of terms in common.


How to use #states with a container element? I come from read this Using the Drupal 7 Form API states system to create conditions between form elements and I'm able to use the #states with an input element like the title (textfield element), the problem is that if I try to use a container element the #states doesn't works.

This code works:

$form['field_courriels_des_autres']['#states']['disabled']['input[name="title"]']['filled'] = TRUE;

This code doesn' works:

$form['field_preciser']['#states']['enabled']['select[name="field_salle"]']['value'] = 'other';

I think that the problem is that the field_salle is a container.

As it's been mentioned, the #states property doesn't work for fieldsets, containers.
You need some JS here, e.g:

The form

$form['promo_code_trigger'] = [
  '#type' => 'container',
  '#attributes' => ['id' => ['promo-code-add-el']],
  'data' => [
    '#markup' => t('Add promotional code'),
  ]
];

$form['promo_code_wrapper'] = [
  '#type' => 'container',
  '#attributes' => [
    'id' => ['promo-code-add-el-triggered'],
    'class' => ['hidden'],
  ],
];

JS

$("#promo-code-add-el").on("click", function (e) {
  $('#' + e.target.id + "-triggered").toggleClass('hidden');
  $('#' + e.target.id).toggleClass('active');
});


Theme Ubercart product node and form in Drupal 8 I've been trying to do a "simple task" with Drupal 8. Using Ubercart 4.x, I want to totally change the product (add to cart) page.

For that I've created a twig file called node--product.html.twig and I've fully customized it. But the form is not there.

In order to have the form I've added this to my .theme file:

function theme_preprocess_node__product(&$variables) {
  // Creates a AddToCartForm for the given product (with node->id());
  $form_object = new \Drupal\uc_product\Form\AddToCartForm($variables['node']->id());
  $variables['product_form'] = \Drupal::formBuilder()->getForm($form_object, $variables['node']);
}

And now the form is accessible via the product_form variable in the node--product.html.twig file.

But that's where my issue start, I only find two ways of handling the form, either I do this:

{{ form }}

But then I have the form with the "normal" design, or I create it myself by doing something like this:

<form id="{{ product_form['#form_id'] }}" method="{{ product_form['#method'] }}" action="{{ product_form['#action'] }}">
  (...)
</form>

This way works since I can now customize the attributes, but I don't have access to their ID (I'm getting the values from the node--product node and not the form).

So my question is:
How can I handle this in order for me to fully customize the product node?

This might work:

public function MYFUNCTION() {
  $myform = \Drupal::formBuilder()->getForm('Drupal\[mymodule]\Form\[myformclass]');
  // If you want modify the form:
  $myform['field']['#value'] = 'From my controller';

  $build = [
    '#theme' => 'mytemplate'
    '#form' => $myform,
  ];
}

In twig:

{{ form }}


Auto create nodes from external RSS source The scenario I am trying to fulfil is the automatic creation of Drupal nodes from an RSS list.

At the initial execution of cron, the module, custom/contributed, should parse some remote RSS and for each entry in the RSS a Drupal node with matching title, body etc is created.

The next hour when cron fires, any matching content previously created is ignored. Only when there is a new entry in the RSS should new node(s) be created.

Is there an existing module for doing what I have described above?
OR,
Can anyone direct me on how best to implement such a service?

Thanks.

The feeds module can 'Import or aggregate RSS/Atom feeds'.
https://www.drupal.org/project/feeds

You can set how often it imports and map to fields.

Here's a guide on how to create/edit importers:
https://www.drupal.org/node/638804


How can I assign the Commerce Product SKU as the Path Alias? We would like to automatically assign the Path Alias for each new Product as /products/sku.

How can we do this, either from the URL Alias admin UI or via Rule or programmatically?

Pathauto should give you enough flexibility to do that.

Once your "product" content type has a commerce_product_reference field linked to it (let's call it "field_product"), all fields attached to your "product variation type" should be available as tokens like this:

[node:field-product:product-id] or if you created a specific field to store the value [node:field-product:field-sku].

You probably know it but patterns can be configured from here : admin/config/search/path/patterns.


Views contextual filter navigation links? Assuming a view with a contextual filter based on a field "category" that is a select list with a limited number of values: what is the best approach to dynamically generate a simple list of links (based on available values) at the top of the view to allow a user to navigate the categories? I want to expose the values as links and keep the clean url structure that contextual filters create. See screen below for reference.

In the past, I've hacked together a basic hard-coded solution using hook_views_pre_render and the l() function, but I'm wondering what the best practice would be.

Take a look at the quicktabs module. It should let you define "tabs" for these filters.

  The Quick Tabs module allows you to create blocks of tabbed content,
  specifically views, blocks, nodes* and other quicktabs*. You can
  create a block on your site containing multiple tabs with
  corresponding content. Clicking on the tabs makes the corresponding
  content display instantly, using jQuery.

Additionaly, there is this in-depth blog post not written by me showing filtering/sorting a complex view + filters page using quicktabs. The left side of this view page has "tabbed" items like what you want in your example. CSS tweaks will make the tabs "look" how you want.


Add line item quantity in block-commerce-cart-cart "title" I'm making the cart-content div hidden as the default (in the sidebar shopping cart block), only the title will be visible, when the user hovers on the block-commerce-cart-cart the cart-contents div will be visible to them. How do I show the user how many items the got it their cart when only the block-commerce-cart-cart is visible, which means adding the line item quantity into the header. Can anyone please help?

Here's a quick way using hook_block_view_alter():

function MYMODULE_block_view_alter(&$data, $block) {
  if ($block->module == 'commerce_cart' && $block->delta == 'cart') {
    global $user;
    if ($order = commerce_cart_order_load($user->uid)) {
      // Count the number of product line items on the order.
      $wrapper = entity_metadata_wrapper('commerce_order', $order);
      $quantity = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());

      // If there are more than 0 product line items on the order...
      if ($quantity > 0) {
        // Use the dynamic menu item title.
        $data['subject'] = format_plural($quantity, 'Shopping cart (1 item)', 'Shopping cart (@count items)');
      }
    }

  }
}

The above borrows code from commerce_cart_menu_item_title() to get the cart quantity, so if that's the string you want to output you can just call that function directly and not bother with re-implementing the code, in which case it would be as simple as:

function MYMODULE_block_view_alter(&$data, $block) {
  if ($block->module == 'commerce_cart' && $block->delta == 'cart') {
    $data['subject'] = commerce_cart_menu_item_title();
  }
}

The default return from commerce_cart_menu_item_title() will be at least 'Shopping Cart' (if the cart is empty) so this method should be pretty bulletproof.

Make sure you set the title of the block as an empty string on the block admin page (so the altered subject is used instead of a custom title) and that should work fine, e.g.:


Moving a Drupal website from one server to another, an error needs to be fixed I set my test Drupal 7 website on my Macbook in a XAMPP environment, and I've now moved the site to another computer with  Windows xp, using the following steps:

Export the database use the phpmyadmin to a .sql file.
Import the database in the XP computer using the sql file.
Copy all the  website's files in the htdoc directory to the new server's same directory
Alter some parameters in settings.php associated with database.

OK, I did it. Everything goes well, except one thing. The Configuration Menu for the Administrator doesn't work. When I click the Configuration menu, nothing happens after waiting for a long time, only a blank page appears.

And I don't know what had happened, or how to solve it.

Try disabling the update module, the quickest/easiest way would be via Drush using drush dis update.

If you cannot use drush follow this: http://drupal.org/node/157632
"phpMyAdmin

To disable a module via phpMyAdmin you must login to phpMyAdmin. Then you must locate the database where Drupal is installed. Once you have done so look for the "system" table. Click and open it. Click to browse the table. Find the record for the module that is causing the problems and select the edit function. Set the status to "0" and save."


Get all fields connected to an entity I am trying to figure out the structure of a fieldable entity.
I can see the main table in to install file, however it has various fields attached to it. How can I get an grand overview of the structure programmatically?

You can get an entity type or bundle's field structure with field_info_instances(). e.g.

// Get metadata for all fields attached to the article content type.
$instances = field_info_instances('node', 'article');


Get a file URL from a custom entity referenced on a user profile I have an entity called CV which is used to store uploaded CVs. The entity is created and referenced on the user profile using inline entity form. I need to get the fid for the cv so I can do this:

$uri = file_load($fid)->uri;
$file_name = file_load($fid)->filename;
$path = file_create_url($uri);

I've tried to use entity_metadata_wrapper, but I'm not sure how to actually access the correct field. This is an example of what I've been trying:

$wrapper = entity_metadata_wrapper('candidate_cv', $cv);
$cv_file = $wrapper->field_candidate_cv->value();

Which returns this error:

EntityMetadataWrapperException: Unknown data property field_candidate_cv.

Update:
I have managed to get the title of the entity using this:

$cv_wrapper = entity_metadata_wrapper('user', $user);
$cv_upload = array();
foreach ($cv_wrapper->field_cv->value() as $index => $feature) {
    $cv_upload[] = $feature->title;
}
echo title[0];

But I can't get to the fid of the file field which is field_candidate_cv.

$cv_wrapper = entity_metadata_wrapper('user', $user);
   $cv_upload = array();
   foreach ($cv_wrapper->field_cv->value() as $index => $feature) {
        $cv_upload[] = $feature->field_candidate_cv;
    }
    $fid = $cv_upload[0]['fid'];

$fid prints nothing.

However, in this $fid prints Array:

 $fid = $cv_upload[0];

Solution:

$cv_wrapper = entity_metadata_wrapper('user', $user);
$cv_upload = array();
foreach ($cv_wrapper->field_cv->value() as $feature) {
    $cv_upload[] = $feature->field_candidate_cv;
}
$fid = $cv_upload[0]['und'][0]['fid'];

Printed the array of $cv_upload using:

drupal_set_message('<pre>'. print_r($cv_upload, TRUE) .'</pre>');


How to backup just a node? I need to backup just a node. Usually I get this by searching the info of the node in the database but I'm just wondering if the backup and migrate module could help to do it?

You could export it with Node export module.

  This module allows users to export nodes and then import it into another Drupal installation, or on the same site.

  Using this module you can save yourself a lot of time setting up new websites that have similar nodes to websites you've already made, migrating nodes to new Drupal versions, or between development/staging/production sites.


block-[region].tpl.php is not working? I just created the Blocks and Regions in drupal 6. Now I want to align these regions (by using DIV id's etc..), so I created a block-[region].tpl.php file and write HTML and PHP scripts. Unfortunately these scripts are not showing in that regions, only the block contents are showing.

By the article, template files are searched in the following order:

block-[module]-[delta].tpl.php
block-[module].tpl.php
block-[region].tpl.php
block.tpl.php

But the contents in the files are not displaying. How I figure-out this problem ?

My best guess is that you haven't copied across the standard block.tpl.php file into your theme. This is required (for a reason that escapes me) for overriding node and block templates.

There's a bit of a discussion about it in the comments on the link you posted.


How to add a 'read more' theme link to a custom view mode? In Drupal 7 the Teaser view mode automatically comes with a 'read more' theme link. I need to retain the Teaser view mode and then create another called 'Snippet', which is basically the same as Teaser but has a lot less content in the trimmed area.

I created a custom module and added the view mode...

/**
* Implements hook_entity_info_alter().
*/
function mymodule_entity_info_alter(&$entity_info) {
    // Add a custom view mode
    $entity_info['node']['view modes']['snippet'] = array(
        'label' => t('Snippet'),
        'custom settings' => TRUE,
    );
}

But it doesn't activate the 'read more' link like Teaser does. Can anyone point me in the right direction with this please?

I took a look here

https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_build_content/7

and here

https://drupal.org/node/1844292

and came up with this

function YOURMODULE_node_view_alter(&$build) {
    if ($build['#view_mode'] == 'YOURVIEWMODE') {
        $node=$build['#node'];
        $links=array();
        // Read more for teas ext
        $node_title_stripped = strip_tags($node->title);
        $links['node-readmore'] = array(
            'title' => t('Read more about @title', array('@title' => $node_title_stripped)),
            'href' => 'node/' . $node->nid,
            'html' => TRUE,
            'attributes' => array('rel' => 'tag', 'title' => $node_title_stripped)
        );
        // Assign links
        $build['links']['node']['#links']=$links;
    }
}


Drupal Array to string conversion hook I am trying to change the links of the Language Switcher module. I am using the following code, but it doesn't work.

function mytheme_links__language_block(&$variables) {
  // Change variables
  return $variables;
}

When it gets executed, I get the following error:

  Notice: Array to string conversion in Drupal\Core\Render\Markup::create() (line 38 of core/lib/Drupal/Component/Render/MarkupTrait.php).

What is wrong? How could I return altered variables?

The problem is solved by just using another hook

function mytheme_preprocess_links__language_block(&$variables)
{
    $variables['links']['en']['link']['#title'] = "ENG";
}

Thanks


how to pass variables from one module to another module? I wanted to use apachesolr module along with a field module that is custom written.

The field module gives the input to 'apachesolr' module instead of the normal search bar. The output is passed through the field module. The output is printed as the field output.

Will module_invoke() be helpful in these cases?

I want to pass variables from one module to another module like the input and output.

As alternative, you can use also drupal_static() if the value you pass from a module to the other doesn't need to be saved past the page request. When both the modules pass to drupal_static() the same value for the first parameter, they get the same static value.

In the case you use drupal_static(), you must be sure the module that is setting the static variable is executed before the module that reads that value.


Display Suite label below field, instead of above or inline Pretty straightforward question. Is there a way to get the label for a field to appear below the field? The only options within display suite are inline and above.

theoretically you should create a custom field template file overriding the default one.

If you're using Display Suite Extra

1) On DS field settings select "Drupal default" as field template

2) Override the field template following the standard drupal suggestions (see below)

Unfortunately this will not work due to a bug: http://drupal.org/node/1885480

Instead if you're not using Display suite, you'll be able to override the field template without any problem.

Override a field template is quite easy:

1) copy the "field.tpl.php" from /modules/field/theme directory and paste it on your theme directory.

2) rename the file following the rules documented on this page: http://drupal.org/node/1089656

3) change the field-???.tpl.php content moving the label below the field content like:

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><?php print render($item); ?>

    <?php endforeach; ?>

  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>


How to add a description to an image field? I have a content type which has a field of the image field type.

When editing this field I see that I can:

Enable Alt field

and also can:

Enable Title field

Is there any way to Add a Description field to be shown under each image.

To do that you'd need to add another column to the field type, which there's no native support for currently.

You're not alone in wanting this functionality (I'd definitely like it) and there is a patch that adds a hook_field_schema_alter() function to the field module, which you can use to add extra columns. I haven't tried it but the comments and tests on the above link seem to suggest it does work.

Bear in mind if you go down that route you'll also have to implement a few other alter hooks (hook_field_widget_form_alter() for example) so it's not a quick-fix.

If you're not up for patching core you might just want to use the Field Collection module to accomplish something similar. You can add a collection item containing an image widget and textarea widget to basically achieve the same effect (although there is some very slight impact on performance).


Module and functions goes missing intermittently Looking for ideas as to why a custom module might "go missing" intermittently.

It has been put into production, serves thousands of page views and works well most of the time.  Every now and then it just "seems" to go missing.

Symptoms are:

Fieldable panels pane plugins (declared by the same module) can't
make callbacks to functions within the module, getting "undefined function" errors.
Template files which call functions from the module get the same errors above.
The module declares a hook_menu URL which starts returning 404s.
Form callbacks functions in the module get "not found or invalid
function name in drupal_retrieve_form()"

All of this is intermittent, runs fine for a week, or maybe a couple of hours, then it starts happening.  I clear the caches, sometimes once or twice and it comes back to normal.  There are no errors in the logs that I can see, nothing in watchdog that stands out.

How is it possible for a module and its functions to randomly go missing?

I may have tracked this down to memcache, though it's such a strange error I can't be sure.  Sometimes a group of nodes we put into cache was over the memcache 1mb default limit.

So instead of caching the nodes, I ran them through the theme layer first and reduced the required caching space by about 80%.

This didn't exhibit on my local host as I don't have memcache installed, rather relying on Drupals database caching.  Running some queries like this helped identify the potential problem:

SELECT cid, LENGTH(data) AS Cache_Size FROM cache ORDER BY Cache_Size;


Need help clearing the schema cache I am checking of a particular field type in the schema using:

drupal_get_schema('MY_FIELD');

I see in the database the field type is int, but when I check after:

$schema[$table]['fields']['MY_FIELD']['type']

is giving me always 'datetime'.

I assume is a cache issue: I am using:

cache_clear_all('schema', 'cache');

but still no luck.

There are a few different cache entries for the schema, schema:, schema:runtime, schema:runtime:1, and so on.

To clear the lot, try using a wildcard:

cache_clear_all('schema', 'cache', TRUE);


How to redirect /user to /user/login My client wants the only login url to be /user/login
So I need to redirect /user to /user/login

any idea how to accomplish this?

You can use rules module to create a redirect when anonymous user view the /user page.

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.

You can follow below step:

Go to Administration -> Configuration -> Workflow -> Rules
Click on Add new rule link in top of page
Fill the name and select Drupal is initializing from React on Event drop down in the form and save the form.
click on Add Condition link in the page and select User has role(s) from the "Condition to add" drop-down and select anonymous user as user role and save the form.
Click on Add condition link and select "Data comparison" from the "Condition to add" drop-down and set site:current-page:path as "Data selector" and click on continue button and set 'user' in the value field and save the form.
Click on Add Action link and select Page redirect event and set user/login in the value field and save the form.


drupal_static and XHProf I'm using D6 but stole drupal_static() from D7 for a high demand site I'm currently working on.

I'm currently optimising some of the slower pages with XHProf which has been fine, but I'm getting a strange result with drupal_static().

It doesn't matter whether I use:

$registry = &drupal_static(__FUNCTION__, array());

Or the fast static method:

static $registry;
if (!isset($registry)) {
  $registry = &drupal_static(__FUNCTION__, array());
}

The number of calls to drupal_static() is given as the same in XHProf.

Am I missing something?

You should use either static declaration or drupal_static(), but not both for the same variable. The issue here is that the reference is lost because references are not stored statically.

From https://www.drupal.org/node/619666#comment-2211696

  So unfortunately this is not possible (declarations of static variables don't accept expressions):

static $implementations = &drupal_static(__FUNCTION__, array());

  An this neither (it'll lose the reference):

static $implementations;
if (!isset($implementations)) {
  $implementations = &drupal_static(__FUNCTION__, array());
}

  But this is:

static $cache = array();
if (!isset($cache['implementations'])) {
  $cache['implementations'] = &drupal_static(__FUNCTION__, array());
}
$implementations = &$cache['implementations'];

So you should do this:

static $cache;
if (!isset($cache)) {
  $cache['registry'] = &drupal_static(__FUNCTION__, array());
}
$registry = &$cache['registry'];


Where does drush look for the path of the mysql socket (on MAMP)? After upgrading from drush 6.5.0 to 8.0.1-dev through brew, the drush terminal command returns the popular

  'PDOException: SQLSTATE[HY000] [2002]' error.

The only way to make it work is to add the unix_socket line to my Drupal settings.php files for all my projects:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'site',
      'username' => 'user',
      'password' => 'pass',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
      'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',
    ),
  ),
);

Even if I use /var/mysql/mysql.sock, it will work, because I have a symlink up:

lrwxr-xr-x  1 root  wheel    39B Mar 11  2015 /var/mysql/mysql.sock -> /Applications/MAMP/tmp/mysql/mysql.sock

But that is exactly the thing I don't understand. And I would like to configure it at one point so I don't have to edit all the current and upcoming project's settings.php files.

So my question is: Where does drush look for the path of the mysql socket (on MAMP)?

If it's through the php.ini, it should be correct too (/Applications/MAMP/bin/php/php5.6.10/conf/php.ini):

mysql.default_socket = /Applications/MAMP/tmp/mysql/mysql.sock

Currently, my .bash_profile contains no alias or export related to this issue because it worked fine with my previous drush installation.

First of all, check which php and php.ini file is used by drush:

$ drush status --full
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database hostname               :  localhost
 Database username               :  root
 Database name                   :  drupal7
 Drupal bootstrap                :  Successful
 Drupal user                     :
 PHP executable                  :  /usr/local/opt/php56/bin/php
 PHP configuration               :  /usr/local/etc/php/5.6/php.ini

Then edit its default MySQL socket name for local db connects:

pdo_mysql.default_socket=/path/to/mysql.sock

as by default it points to /tmp/mysql.sock unless PHP was configured with different (--with-mysql-sock).

Check by:

$ php -i | grep ^pdo_mysql.default_socket
pdo_mysql.default_socket => /tmp/mysql.sock => /tmp/mysql.sock

So probably that's why /var/mysql/mysql.sock didn't work, as it was looking for /tmp/mysql.sock instead.

Then the symbolic link should work as expected.

If drush is using wrong instance of PHP, then add it into PATH (as you did) or specify with --php=</path/to/file>, so the right php.ini would be loaded.

Alternatively specify unix_socket in your settings file (as you already did).


How to connect database in UnitTestCase subclass? I know there are mockups, data providers, bla bla bla.
I don't care now, I just want to connect to my dev site db and use nodes, terms for unit tests.

How can I do it? In D7 it was very simple in plain PHPUnit, what about D8?

I've tried bootstrap D8, but failed.

See https://www.drupal.org/phpunit for better documentation.

There are 4 test base classes:

UnitTestBase, pure unit tests where everything but your code has to be mocked and only supports classes
KernelTestBase, which provide a basic in-memory drupal environment. Much faster than browser tests but more tedious to set up, you have to explicitly install tables you need and depend on all modules you need explicitly
BrowserTestBase, the replacement for WebTestBase, better apis (uses mink and so on) but just as slow.
JavaScriptTestBase, phantomjs based JS tests, even slower but can actually execute JS.


Exposed Form: Send only selected filters I have a view with several exposed filtears. The filters are of different types: checkboxes, taxonomy autocomplete and some jquery slider (I use Better Exposed Filters module).

The view shows all nodes of type A. Node type A has 15 field, each of which has a respective exposed filter within the view. Not all fields are mandatory which is why some nodes don't have value for all fields.

My problem is this (just an example to demonstrate):

Field A1 is called 'Location' (taxonomy) -- this is a mandatory field
Field A2 is called 'Retail purchasing power' (jquery slider with
min/max values) -- this field is not mandatory

Now, a user selects in the exposed filter for 'Location' let's say 'Florida'. The view will show all nodes with Florida that also have a value for 'Retail purchasing power', but not the nodes without a value for this field.

I can see that this is the expected behaviour but in my view I have a lot of filters and there are many nodes that don't have values for some fields. Some users only search for the 'location' and don't care too much about the other filters.Tthey don't see all location because they are filterd out.

Does somebody know a way to only send the filter values that have actively been selected by the user? The min/max values form the jquery sliders should only be considered when they are used.

I can confirm that on page load the option jQuery UI slider of the Better Exposed Filters module does apply the minimum value set in options.

The minimum value is displayed in the slider, so it's a visible cue that it will be displayed.

If you delete the number in the slider and then apply other filters, the slider filter will not be applied!

But the minimum value will still be visible in the slider on page reload (if you're not using Ajax in Views).

I couldn't find any similar issues so I created a new one: jQuery UI slider Exposed filter always applied

Add your test results/observations there.


What is the variable for the human readable name of the node type? In my node.tpl I have added <?php print $type; ?>. This gives me the machine name of the node type e.g. blog_entry. What do I use to get the human readable form e.g. Blog entry?

Edit (Here is my current code)

<?php if ($display_submitted): ?>

<?php print $type; ?>

<?php print $name; ?>

<?php print $date; ?>

<?php print $comment_count; ?>

  <?php endif; ?>

You can use the node_type_load() function to load up the node type object, and then extract the name:

$type_obj = node_type_load($type);
$name = $type_obj->name;

You can integrate with your current code like so:

<?php
  $type_obj = node_type_load($type);
  $human_readable_type = $type_obj->name;
?>

<?php if ($display_submitted): ?>

      <?php print $human_readable_type; ?>

    <?php print $name; ?>

    <?php print $date; ?>

    <?php print $comment_count; ?>

<?php endif; ?>


How to make a multi-site instance aware of shared module directory? My team inherited a Drupal 7 multi-site installation that was originally built with a custom installation profile and Drush make. I have all these sites running correctly in our environment now and want to bring an additional Drupal 7 standalone instance we support under this new multi-site configuration. I copied the database and created a corresponding subdirectory in the sites tree along with the proper edits to the sites.php file. The site does appear correctly when tested in a browser but the modules visible to the other instances are not seen by this site. Those modules are located under the profiles tree. I don't expect to need to use the install profile again and am inclined to copy the profiles/myprofile/modules directory contents to sites/all/modules to address this situation but am concerned about potential database dependencies. What is the best way to clean this up and have all multi-site instances aware of the same common modules?

Quick way...Run

variable_set('install_profile', 'name_of_custom_install_profile');
drupal_flush_all_caches();

from somewhere in the new site.

That'll trick your new site into thinking it was installed with the custom profile, and it should start checking that folder for contrib modules.