It's worth noting the comment table has a 'uid' column so you could potentially query that to get the comment count for a user.

e.g:

$user_comment_count = db_select('comment', 'c')
->condition('uid', $account->uid)
->countQuery()
->execute()
->fetchField();

However, if you want to increment a field on comment insert, you could use Rules or hook_comment_insert

e.g: Rules export (Increment field_comment_count for current logged in user on comment insert)

{ "rules_increment_comment_count" : {
    "LABEL" : "increment_comment_count",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "comment" ],
    "ON" : { "comment_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "site:current-user" ], "field" : "field_comment_count" } }
    ],
    "DO" : [
      { "data_calc" : {
          "USING" : { "input_1" : [ "site:current-user:field-comment-count" ], "op" : "+", "input_2" : "1" },
          "PROVIDE" : { "result" : { "result" : "Calculation result" } }
        }
      },
      { "data_set" : {
          "data" : [ "site:current-user:field-comment-count" ],
          "value" : "[result:value]"
        }
      }
    ]
  }
}

You'll need to tweak the Rule to match your conf, but something like that should work.


You get NULL for $edit['status'] because the status hasn't been changed. The functions that calls user_save(), which invokes hook_user_presave() contain the following code.
// user_profile_form_submit()

$account_unchanged = clone $account;
entity_form_submit_build_entity('user', $account, $form, $form_state);

// Populate $edit with the properties of $account, which have been edited on
// this form by taking over all values, which appear in the form values too.
$edit = array_intersect_key((array) $account, $form_state['values']);
user_save($account_unchanged, $edit, $category);

// user_register_submit()

$account = $form['#user'];
entity_form_submit_build_entity('user', $account, $form, $form_state);

// Populate $edit with the properties of $account, which have been edited on
// this form by taking over all values, which appear in the form values too.
$edit = array_intersect_key((array) $account, $form_state['values']);
$account = user_save($account, $edit);

As the comment says, $edit contains only the account properties that have been changed, not every property. If you want to obtain the status value, you should use the following code.
$new_status = isset($edit['status']) ? $edit['status'] : $account->status;


What's the purpose of the type "block_settings" in schema.yml files?

That's basically config schema inheritance, like you have class inheritance in PHP.

Any type that you define can be used as by by someone else. And it is what you want to do when you extend the class (usually a plugin) for which it is defined.

block_settings itself is a type that extends from mapping and defines a few common keys, it is defined in core.data_types.schema.yml

block_settings:
  type: mapping
  label: 'Block settings'
  mapping:
    id:
      type: string
      label: 'ID'
    ...

(Multiple keys in there shouldn't exit and are for example block_content specific, but that's a bit complicated to fix now).

And if you'd provide a block plugin that would extend from example_configurable_text, then you can define it like this:

block.settings.my_block:
  type: block.settings.example_configurable_text
  mapping:
    another_thing:
      type: text
      label: 'Another thing'

And you automatically get everything it defines, and what it itself inherits from block_settings.


print rate_embed($node, 'NAME', RATE_FULL);

Replace NAME with the machine name of the widget; the view mode can be RATE_FULL, RATE_COMPACT, RATE_DISABLED, RATE_CLOSED, RATE_COMPACT_DISABLED.


Installing Drupal 7.22 fails at database configuration step on Win7

Thanks Clive for the suggestion.

Writing www/test_pdo.php:

<?php
try{
    $dbh = new pdo( 'mysql:host=127.0.0.1;port=3306;dbname=drupal-7.22',
                    'mydb',
                    'mypassword',
                    array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
    die(json_encode(array('outcome' => true)));
}
catch(PDOException $ex){
    die(json_encode(array('outcome' => false, 'message' => 'Unable to connect')));
}
?>

proved the connection worked for "127.0.0.1" but not for "localhost", my initial setting.

So I changed sites/default/settings.php and reloaded and that worked.


Do wildcards not work with Menu Local Task?

The problem is that your menu items are local tasks, which are menu tabs, so on a given page drupal will load all the tabs for the current page.

So on the admin/content/import-dashboard/new page it loads your tab menu items:
admin/content/import-dashboard/new
admin/content/import-dashboard/new/%

but when it goes to get the second item there is no 4th param on the current page so it gets that error.

This is why when you change it to not be a MENU_LOCAL_TASK it stops the problem.

If you have a page that has menu tabs where the last part of the path is a wildcard, how could drupal know what all the possible tabs are? It can't.

This is why when you see menu tabs they are things like node/%/view, node/%/edit, etc. so you have a finite number of tabs and each has its own definition.

As a side note, yes you can use multiple menu item types, but using MENU_LOCAL_TASK | MENU_NORMAL_ITEM doesn't really make sense.
As an example MENU_IS_LOCAL_TASK | MENU_LINKS_TO_PARENT | MENU_VISIBLE_IN_BREADCRUMB is one that would make sense.

Also, I'm not sure if this is your full hook_menu() or if admin/content/import-dashboard exists somewhere else, but usually if you're doing tabs there is a parent page (in this case admin/content/import-dashboard) and a tab that is MENU_DEFAULT_LOCAL_TASK.

There is however the ability to set in your menu item:

'tab_parent' => 'admin/content/import-dashboard/new'

This allows you to set the parent page to use for tab items.
Without this it defaults to the path of the tab item minus its last path part.


You can do it via a class that you selectively add to the pages, then using CSS add a background. Two modules stand out:

Node Class

  Node Class is a simple module that allows users to add custom CSS
  classes to any node through the node/add interface.

Context

  Context allows you to manage contextual conditions and reactions for
  different portions of your site. You can think of each context as
  representing a "section" of your site. For each context, you can
  choose the conditions that trigger this context to be active and
  choose different aspects of Drupal that should react to this active
  context.

See also:

Is it possible to add css class to the page's body tag with rules when certain conditions are met?

and

Context Block Classes


How to limit access to certain nodes to certain users only?

Depending on how much more deep you want to take the logic of your project, you might not even need custom coding.

Start with Drupal 7 minimal installation profile
Install the modules views, entity, entity reference and their dependencies.
Create the content type "order" and add the fields you need to it. Add other content types as well like "invoice" and document, these last you might want to add a "reference" field to the order content type if they are connected.
Setup the user roles "client" and "supplier" and you might want to install the "ACL" and "content access" modules as well to define who has access to what, like "only"3 the author of the node can see it, edit it and delete it.
To make it easier for the user to see the nodes they have access to, you can create a tab on their user account using views listing only the node where they have access or where they are the authors.

Notes:
You might want to test the system before going live to make sure the right person can access the right content. Also if no anonymous user is meant to use the system disable content access to the anonymous users.


The closest thing I know of to take a string db_query() value would be the Query Coder module.

Be aware of its known issues:

Known issues (taken from project page 01-29-2015):

INSERT queries must be specified in form "INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...)"
Not support "->expression()" conditions for UPDATE queries.
All tables and fields in SELECT query must be specified with aliases, in other (UPDATE, INSERT, DELETE) queries without aliases
Example:
RIGHT: "SELECT * FROM users u"
NOT RIGHT: "SELECT * FROM users"
All combining conditions in SELECT queries must be specified with aliases.
Example:
RIGHT: "SELECT COUNT() AS user_count FROM users u"
NOT RIGHT: "SELECT COUNT() FROM users u".


Theme Drupal Form API checkboxes as a grid

First, define a custom theme function with hook_theme() and assign it to the form element with #theme.

In that theme function, you can use expand_checkboxes to convert it into an array of separate checkbox elements. Then, re-structure it into an array with 3 elements each, render the checkboxes and pass it to theme_table().

Something like this, all untested.

function theme_yourmodule_preference($element) {
  $elements = element_children(expand_checkboxes($element));

  $rows = array();
  for ($i = 0; $i < count($elements); $i += 3) {
    $row = array(drupal_render($elements[$i]));
    // The following two might not always exist, check first.
    if (isset($elements[$i + 1]) {
      $row[] = drupal_render($elements[$i + 1]);
    }
    if (isset($elements[$i + 2]) {
      $row[] = drupal_render($elements[$i + 2]);
    }
    $rows[] = $row;
  }
  return theme('table', array(), $rows);
}


How to change price in shop based on location? If in US then US dollars etc

Start your search at Commerce Multicurrency and find ways to detect the customer's country from there. Here is an excerpt about it from the module's project page:

... enhances some of the multi-currency capabilities of Drupal Commerce.
Current features:

UI for fine granular definition of exchange rates.
(Every currency combination can be defined separately if needed)
Synchronization of currency exchange rates directly from the European Central Bank (ECB).
UI to specify which rates shall be synchronized and which are handled manually.
Generation of currency specific price fields inclusive generation of rule-set to handle them.
hooks for easy integration of custom currency exchange rate sources.


1) Take a look at the editors you're using on your site at /admin/config/content/formats

2) For each editor, you'll need to update the allowed tags.  Let's edit the FULL HTML format for this example, so click on the "Configure" button for "Full HTML"  (/admin/config/content/formats/manage/full_html).

3) Under "Enabled Filters", click the checkbox labelled "Limit allowed HTML tags and correct faulty HTML".  A filter settings form will appear below.  Remove the h1 tag from the field labelled "Allowed HTML Tags".

4) Save

Test that it's removed from the drop down:


Using fivestar_get_votes() to show the votes on a node

Fivestar module for Drupal 7 implements fivestar as a field. Assuming the field name is field_fivestar_awesomeness you can print it anywhere with:

$fivestar = field_view_field('node', $node, 'field_fivestar_awesomeness');
print render($fivestar);

There are some display and language options, see more in the api docs.


How do I assert for a link's href AND link text in a functional test?

Perhaps a better approach will be assert by XPath selector \Drupal\Tests\BrowserTestBase::xpath something like '//a[@href="' . $url .'"][contains(text()=\'Some text\')]' as XPath. Check this post about matching text and this about matching url.


How can I have all drupal links work on ajax based?

Maybe this module will help you: http://drupal.org/project/ajax_links_api

  Ajax links API module help you to load any content to a specified DIV
  using JQuery Ajax. This module will also load JS and CSS for
  Ajax-loaded content by using Drupal.attachBehaviors(). Links will work
  as normal if Javacript is disabled.

  In HTML5 browsers, title bar and url will change using
  window.history.replaceState() (This feature is disabled by default.
  Check ajax_links_api.js to enable).


How do I set start date with the core date field?

When you create your field, you have the option of setting a default value.  Set the Default Value to Relative Date and then ender "+1 day" into the textfield, and proceed with setting up the field.

When you create new entities with that field, it will default to the current time +1 day, which you can then change if needed.


Create a dynamic user registration form using Profiles

Bascially, we create an Ajax callback on the form element used to update the form, and we create an additional form element which is simply a container to display the the relevant profile form.

I used the Profile 2 Registration Path module to add the Profiles Forms to the User Registration form. I then use hide();  and show(); to display them if appropriate.

The Devel module was also invaluable doing this.

function rego_form_alter(&$form, &$form_state, $form_id){
    if($form_id == 'user_register_form'){
        dpm($form);

        //First, hide all the other profiles
        hide($form['profile_designer']);

        //User selects what type of profile is most appropriate
        $form['profile_main']['field_profile_type']['und']['#ajax'] = array(
            'callback' => 'rego_update_profile_type',
            'wrapper' => 'profiles_container',
        );

        //Create a container to the relevant profile
        $form['profiles_container'] = array(
            '#prefix' => '
',
            '#suffix' => '
',
            '#weight' => '500',
        );
    }
}

//Callback
function rego_update_profile_type($form, $form_state){
    // Switch based on the user input
    switch($form_state['values']['profile_main']...['tid']){
    case '82':
        $form['profiles_container'] = $form['profile_designer'];
        break;
        // --Other cases here --
    }
    //Put back the div id so that the container can be updated again
    $form['profiles_container']['#prefix'] = '
';
    $form['profiles_container']['#suffix'] = '
';

    show($form['profiles_container']);
    return $form['profiles_container'];
}


ob_start() error running Devel on Search API + Search views page

I just ran my Devel debug on blocks and that worked.


How to change page title for admin users to easly find which admin page they are

You can use shortcut bar,

  The Shortcut module provides a toolbar on the top of the page to which
  you can add links. This toolbar is site-wide, so any links added will
  be visible to all users who have permissions to see the Shortcut
  toolbar. This is useful for creating links to commonly-used pages
  within your site. You can organize these links in multiple sets of
  shortcuts.

Click on the + sign as shown below in any page you want to bookmark

You will see links next to Add Content , Find Content like below

Explained in link given above...


Creating an external authentication module

I stumbled on the exact same problem recently, and ended up using a generic user for all ones authenticated via the external system. It's the only way I see to manage this without creating a Drupal user for each external one.

Of course, it all depends about what you're trying to achieve. If you need to customize the website based on each individual user, you're out of luck with this solution. But then, if you need this level of granularity, you'd use a standard solution with automatic user creation, right ?


How to make a block showing the content entity the author of the node is linked to?

You've stumbled into the issue of Context. Blocks can be placed anywhere, and has a very limited concept of context (the only context that Blocks know of are logged in user, and parameters taken from the url).

Normally one will use CTools (the Context specialist) and Panels to solve this type of problem. You are lucky in that Views has a relationship that can solve it for you.

Construct your block as follow:

Type Content, filtered by content type Information.

Contextual filter:

Content: Nid (The node ID.), no relationship, and for WHEN THE FILTER VALUE IS NOT AVAILABLE you add Content ID from URL

Relationships:

Content: Author (Relate content to the user who created it.), and Require this relationship
Entity Reference: Referencing entity (A bridge to the Content entity that is referencing User via field_users - Your field will be differently named, mine is field_users). Set the relationship to 'author' (the first relationship added), and Require this relationship.

Fields:

I assume you are adding the node title. Make sure to set the relationship to: Content referencing Users from field_users (the 2nd relationship you added - yours will be named slightly different)

If you add any other fields make sure to set the relationship as well.

If you find that it lists any duplicates, just go to OTHER in views, and under Query Settings, set it to Distinct (I'm sure this won't be necessary though).


Setting multiple checkbox values with form_set_value

I believe you want to pass an array with all values to form_set_value() as the function is setting the value, not appending to it. I would alter your setup to build an array of values with your switch/foreach block and then pass that array in a single form_set_value call below the switch, outside of the foreach.

Update your your foreach / switch like so:

$host_values = [];
foreach($hosts as $host){
  switch($host->alias){
    case "external":
      $host_values[] = ['tid' => '758'];
      break;
    case "internal":
      $host_values[] = ['tid' => '759']
      break;
    case "local":
      $host_values[] = ['tid' => '760']
      break;
    default:
      break;
  }
}

form_set_value($form['field_proxy_host'], [LANGUAGE_NONE => $host_values], $form_state);


What is the difference between creating fields programmatically and by exporting settings?

For modules common practice is to define base fields with the first option and bundle fields with the second option. Concerning option 3 most use cases of Features are now covered by the configuration management, which you can use to synchronize fields configured in UI to a cloned site. Not only those fields created in UI , but also base fields from option 1 in case they are overridden or bundle fields installed by option 2 if they are modified in UI.


Honestly, I'd recommend creating two separate fields, one for systolic pressure and another for diastolic pressure.  Then, use CSS to organize the fields the way you want.  It actually makes more sense to do it this way since they represent two distinct values, even though they're used together conventionally to represent blood pressure.

To expand on the answer, specifically on the CSS side, here are some additional tips.

Once you've found a way to isolate the two fields with classes, I recommend displaying both of their div wrappers as display: inline-block; and, for the first field (systolic pressure) give it a rule that uses the after pseudo-class to add the '/'.

.classes .isolating .systolic-field:after {
  content: "/";
}
.classes .isolating .systolic-field {
  display: inline-block;
}
.classes .isolating .diastolic-field {
  display: inline-block;
}

If you're not familiar with CSS I can provide a more "concrete" example, but this should be sufficient.


How to get the content owned by the currently logged-in user?

This is how I have do it:

function MYHOOK_user_login(&$edit, $account) {
    global $user;
    $nid = db_query('SELECT nid FROM {node} WHERE uid = :uid', array(':uid' => $user->uid))->fetchField();
    drupal_goto('node/' . $nid);
}


How can I use one of the pre-set email texts for user registration in a custom module

I guess this should be possible via configuration API. Look for the suitable entry where the message body is saved, call it via the service to put it into a variable. Then you can do additional coding with the string variable.
More information you can find here:
Configuration override system in the docs


prompt in IE8 for secure pages produces altered layout

The message you're getting in IE 8 is due to the fact that you're viewing your site through HTTPS, but some of your site's assets / resources are still being loaded through HTTP. If you look at the site in Chrome, you'll notice an icon to the right of the address bar which indicates the same warning about insecure content.

I would recommend going through all your templates / custom modules to make sure that any JS, CSS and iFrames (hope you have none of those heh) are all being served via HTTPs and not HTTP. Once nothing is being served via regular HTTP you shouldn't get that message anymore.

Hope this helps!


Prepopulating county/state field (ajax driven field)

"So for example let's say my billing address defaults to Ireland (one can setup a default value under customer profile -> billing information)."

If I understand you correctly perhaps do not set a default value for the country in your addressfield options. I.e. do not select a country in the options illustrated below... this way the state options are generated after the user has selected their country...

Incidentally, if you could post whatever your hook_form_alter code is and where you put it... I'd find it really useful as I am also working to pre-populate addressfields with user-account details.
Thanks!


how to get webform title and category with no submissions in view or hook?

use below code as a function in your module file and call it on your custom block.

  function module_name_webformtitle(){
    $query = Drupal::service('entity.query')->get('webform');
    $query->condition('category', 'survey_name');//your survey name
    $entity_ids = $query->execute();
    $webform_id=array();
     foreach($entity_ids as $webid){
       $webform_id[]=$webid;
     }
    $webform = Webform::loadMultiple($webform_id);
     foreach($webform as $webforms){
        $webformtitle=$webforms->get('title');
    }
  }


Why is my Forena report parameter not displaying as a textbox?

Have a look at the tutorial about Forena report parameters. In the end, they are technically stored (saved) as part of the so called .frx files (which contains all of your report specification details). Here is a (partial) example of such frx-file:
<head id="frxsrc">
  <title>My Report Title</title>
  <frx:parameters>
    <frx:parm id="state" label="State" require="1"
      desc="Select a state from the list."
      data_source="sampledb/states" data_field="" type="select">
      WA
    </frx:parm>
  </frx:parameters>
</head>

So when you're creating ("writing") a report specification (eg using the WYSIWYG report writer), part of what you actually do is saving a special kind of "content" in XHTML format. And that's where the typical "text formats" get involved (just like any kind of content you'd save in Drupal).
However, because of the way Forena does certain things to process these XHTML files (report specifications that Forena massages in reports/charts that match your specifications), it's important that as part of the Forena installation/configuration, you "Prepare a text format to be used by Forena", as explained in the Forena Setup Guide. Here is the crucial part of it:

Regardless as to which Input Format you choose to use with forena, make sure these entries are turned of for the chosen text format :

Limit allowed HTML tags.
Display any HTML as plain text.
Convert line breaks into HTML.
Correct faulty and chopped off HTML.

Anybody who starts using Forena without completing (or knowing about) this crucial configuration step, will typically run in this first-time configuration error ... Same happened to me when I first tried to use Forena some years ago.


My subtheme css is overriden by the parent theme. How to I reverse this?

I'm encountering the same issue.  If I disable the css aggregation I can see that the reason is that my sub-theme's css stylesheet is being @imported before the one(s) from the base theme, which means, of course, that the base theme's styles are overriding mine anywhere where I use the same selectors.  Which is crazy.  How is this not a problem for more people?  Is there something we're missing here?

Edit: sure, I can use !important, which is what I'm doing as a workaround (and presumably the OP @Nigel Waters could do the same?), but doesn't this rather defeat the purpose to some degree?


how to update quantity of products in the cart via javascript?

Create new simple module like my_updater_card
add hook_menu
add php function to update the card
call this function from ajax

<?php
/**
 * Implements hook_menu().
 * see hook_menu()
 * see menu_example
 */
function my_updater_card_menu()
{
    $items['my_updater/card/%'] = array(
        'page callback'         => 'my_updater',
        'page arguments'        => array(2),
        'access arguments'      => array('put your permission here'),
    );
    return $items;
}

function my_updater($newTotal){
    //check if this request come from ajax => if not => ignore it
    //here put your php code to update the card
    //then return results true/false to ajax caller
}
?>

Ajax

        $.ajax({
               url: 'my_updater/card/[new total here]',
               type: "GET",
               success: function (data) {
                 //do total refresh here
               }
        });


You would create a new node.tpl.php by copying the existing one from your theme or from the node module (part of core).  Rename your copy node--mycontenttype.tpl.php and place it in your theme directory (along side your other .tpl files).

Install devel and use dpm() to explore the $content variable.  Hide the XML field and extract it's file id (fid) and pass it to file_load.  This should return an object containing your file path, again use dpm() to explore this array and get your file.

https://api.drupal.org/api/drupal/includes%21file.inc/function/file_load/7

Embed your .swf directly into your new node.tpl.php and pass the XML to it as you would any other Flash argument.


Permissions / Roles / Taxonomy / Workbench -- combination?

http://tutr.tv/t4991?list=4948 is a video from Drupal Con London where they talk about the Workbench Modules and will answer most of your questions/concerns.

If you have Workbench Moderation you can have users submit content for review.  Then a content moderator will publish the content or return it as a draft for changes.

Workbench Access will limit users to what content a user can create/edit.  You just need to create a role, assign the role to a Workbench Access Section of the site, and then when they create a new account you can assign them to the correct role.

I have this on my site and have created a rule to email me whenever someone logs in for the first time so I can assign them a role.


I deleted the garland theme and re-added it. After this everything worked properly. I don't know why this worked!


I'm not sure jQuery is really necessary here.

If I've understood you right you could have your link pointing to a path with a menu callback which requests your token via SOAP, and then simply forwards the user on to a URL containing that token as a parameter

function MYMODULE_menu() {
  $items['goto-other-site'] = array(
    'title' => 'Forwarder',
    'type' => MENU_CALLBACK,
    'page callback' => 'MYMODULE_forwarder',
    'access arguments' => array('some permission')
  );

  return $items;
}

function MYMODULE_forwarder() {
  $token = MYMODULE_function_to_generate_token();

  if (!$token) {
    return 'An error occurred.';
  }

  // Add a query string containing the token.
  $options = array(
    'query' => array(
      'auth_token' => $token
    )
  );

  $url = 'http://other-site.com/';
  drupal_goto($url, $options);
}

Apologies if I've got the wrong end of the stick here.

UPDATE

Just a bit more to address your comments:

You can use hook_menu() to place each link in a specific menu in the system by using the menu_name key like so:

function MYMODULE_menu() {
  $items['goto-other-site'] = array(
    'title' => 'Forwarder',
    'type' => MENU_CALLBACK,
    'page callback' => 'MYMODULE_forwarder',
    'access arguments' => array('some permission'),
    'menu_name' => 'main-menu',
    'weight' => -10
  );

  return $items;
}

The weight key describes where in relation to other menu items this link should sit in the menu (a lower number means earlier in the list). When you add a menu link in this manner it will be automatically added to the correct menu so you don't need to add a custom link through the UI (you can delete the one you've already made).

Have a quick read of the Module developers guide to get familiar with that side of things, in this case you're only going to need a .info and .module file.

Hope that helps


What consequences does "references in call_user_func_array are deprectated" have on form api?

No expert, but here's my punt:

  Before PHP 5.4, referenced variables in param_arr are passed to the function by reference, regardless of whether the function expects the respective parameter to be passed by reference. This form of call-time pass by reference ... has been removed in PHP 5.4

means

function myfunction($a, $b) {
  $a++;
  $b++;
  print "myfunction($a, $b)\n";
}

$apples = 10;
$bananas = 20;

// PHP < 5.4: $b is passed by reference, not honouring the function signature
call_user_func_array('myfunction', array($apples, &$bananas));
print("apples: $apples, bananas: $bananas\n");
// PHP < 5.4: $apples = 10, $bananas = 21
// PHP >= 5.4: $apples = 10, $bananas = 20

and

  Furthermore, this does not apply to internal functions, for which the function signature is honored.

presumably means (though it seems a bit unnecessary?):

$angle = 1.5;

// Despite passing by reference, there's no chance of $angle changing as the
// function signature's honored for internal functions.
$res = call_user_func('sin', array(&$angle));

Letharion wrote:

  it sounds to me like anything that builds a form and then relies on getting back a modified form_state will break on 5.4

It seems to me like this should be fine, in this case at least: we're passing
a reference exactly where it's expected by the function signature (I presume this is still the right way to pass by reference where that matches the signature). However if I am right, then any modules with typos in their form hooks like this function MYMODULE_form_alter($form, $form_state, $form_id) will work exactly as expected under PHP < 5.4, but 'suddenly' mess up on 5.4.

@Letharion: in another answer you mention you have 5.4 running: I would've thought something would've exploded by now if it wasn't passing $form_state by reference? But IIUC if the following works as expected in 5.4, then the code you reference should be ok:

function myfunction(&$a) {
  $a++;
  print "myfunction($a)\n";
}

$a = 10;

call_user_func_array('myfunction', array(&$a));
print "a: $a\n";
// We expect a to be 11 the second time for all versions of PHP.

My 2 pennies


How to change the variation title in the add to cart block in Drupal Commerce 1?

OK. I got it working. Perhaps not quite as simple as I'd hoped, but this function will do the trick ...

function commerce_price_attribute_form_commerce_cart_add_to_cart_form_alter(&$form, $form_state) {
    if (isset($form['attributes'])) {
        $entity = entity_load_single($form_state['context']['entity_type'], $form_state['context']['entity_id']);
        foreach (element_children($form['attributes']) as $field) {
            foreach (field_get_items($form_state['context']['entity_type'], $entity, 'field_product') as $product) {
                $product = commerce_product_load($product['product_id']);
                $status = entity_metadata_wrapper('commerce_product', $product)->status->value();
                if ($status) {
                    $items = field_get_items('commerce_product', $product, $field);
                    if (is_array($items)) {
                        $attribute = reset($items);
                        $attribute = taxonomy_term_load($attribute['tid']);
                        $items = field_get_items('commerce_product', $product, 'commerce_price');
                        $item = reset($items);
                        $price = commerce_currency_format($item['amount'], $item['currency_code'], $product);
                        $form['attributes'][$field]['#options'][$attribute->tid] = $attribute->name . ' - ' . $price;
                    }
                }
            }
        }
    }
}

Note that the $status value checks whether the variation is disabled and skips over it if it is - without that, disabled products were still showing in the list of options.


Retrospective fix to hook_update_n() in current release

You can reset the status of the hook_update_n from below query
update system set schema_version=0 where name='modulename(hook)';

Then you can run update.php so this hook_update_n() will work again with your latest changes.

Also you can see this link for schema_version values system_schema() why we have to set schema_version '0' instead of '-1'.

you can use following drush module for roll back the update version in the system table. Called "uroll" for update rollback.

https://github.com/danshumaker/drush-uroll

Usage: drush uroll --module=mycustommodule --version=5

This combined with a database backup reload script allows you to rinse and repeat when writing update functions


Where do you set/change the SKU for a new/existing product? - Drupal 7 Commerce

You can change the product SKU on the product edit form.

e.g:

admin/commerce/products/1/edit

Because products are referenced on line-items etc.. by their ID value, it's actually OK to change SKU for existing products if needed.


Views: Can I create views based on taxonomies that link to other, context-specific taxonomy-based views?

One solution is to create a view showing taxonomy terms.

Display 1

Create a page display with a path "documents"

Add a relationship "Taxonomy term: Content using <state vocab>." Require this relationship.

Under Other > Query Settings select Distinct

Add fields

Taxonomy term: Term ID
Taxonomy term: Name

Exclude term ID from display

Rewrite the results of Name > Rewrite the output of this field:
[name]

Add a filter Content: Type (= <your document content type>)

Display 2

Create a new page display with a path "documents/%"

Remove the Relationship for the state for "This page (override)" and add a relationship for your Department taxonomy. Require this relationship.

Add a contextual filter for Content: <state field> and display contents of "No results found" when filter value is not in the URL.

Edit the rewrite value of your name field, make sure to select "This page (override)": [name]

Display 3

Create a third page display with a path "documents/%/%"

Keep the state relationship from the view's defaults, but add a relationship using "This page (override)" for your Department taxonomy. Require this relationship.

Add a contextual filter, override for this display, for Content: State and then add one for Content: Department.

Override your fields for this display, removing the Term ID and Term Name, and add a field for Content: Title.

If I have explained this well enough, display 1 should give you a list of states that link to display 2 using the contextual filter to give a list of departments from that state, linking to display 3 showing a list of your document node titles from that state department.


Allow editing of only a single field of a node in Panels or a block

Try the Field Permissions module:

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

If you allow your users access to the group edit form, they will only see the fields that you have selected to be editable using Field Permissions.

Use that in conjunction with the form block module as you've suggested and you should get the effect that you're looking for.


Inform user with account creation email, for existing users to

I'd be really interested in this idea too.  I'm making a website to contain and extend an existing registry and it would be great to set the whole thing up with all the members' details and then just send out a mass email containing each user's username and generated password when everything's put together...

I haven't tested it yet, but it could potentially be done:

Set up your users, ensuring 'Notify User' is unchecked and Status is 'Blocked'.  If you already have active users, block them (make sure no email goes out, check admin/config/people/accounts)
When you're ready to notify the users, go to admin/people and check all the blocked users, then user Bulk Options to Activate them (if there's a huge amount of users you might want to do a group at a time to save the server a bit...)
Individual emails should be sent out containing a 'one-time login', see admin/config/people/accounts and scroll down to E-mails and choose 'Account Activation' for the email which goes out.

I will give it a shot and let you know if it worked.


Organic Groups (OG): Make public group posts visible to everyone (outside the group)

You control the visibility of a post through the Group_Access field.

Create a content type with Group and Group_Access fields (or add those fields to a built-in content type). Then when users create posts of this content type, they can make the content part of the group and set its Group Access to either "Public - accessible to all site users" or "Private - accessible only to group members."

Any "Public" content will be visible to anyone on the site, not just group members.


Form API: fomatting the date select lists?

In date_parts_element() there's the line

$hours_format  = strpos(strtolower($element['#date_format']), 'a') ? 'g': 'G';

This is deciding on whether to be 24 hour on the presence of the AM/PM specifier. If you change the format to d-F-Y g:i a it should work I think.

If you don't want to display the AM/PM specifier, but fix it at a particular value, you can do something like this

  ...
  // Add a new process function to this date_select to hardcode am/pm.
  $info = element_info('date_select');
  $process = $info['#process'];
  $process[]= 'MYMODULE_date_select_process_am_only';

  $form['scheduled_for'] = array(
    '#type' => 'date_select',
    '#title' => t('Scheduled for'),
    '#date_label_position' => 'within',
    '#date_format' => 'd-F-Y g:i a',
    '#date_increment' => 15,
    '#date_year_range' => '-0:+3',
    '#default_value' => time(),
    '#process' => $process,
  );
  ...

/**
 * #process callback for a date_select element that removes the AM/PM specifier
 * and hardcodes its value to AM.
 */
function MYMODULE_date_select_process_am_only($element) {
  $element['ampm']['#type'] = 'value';
  $element['ampm']['#value'] = 'am';

  return $element;
}

It's untested but works in my head (: If you wanted to do the same thing on a number of different forms, there's a more elegant way (let me know if you're interested).


Use an exposed filter as contextual filter on another view

Please follow below steps to achieve functionality that you are looking for.

Disable AJAX feature for view.
In the block view add a contextual filter and select type as Provide default value >> Type as php code.
In the php code read the exposed filter value using $_GET[]
Return the value you got from $_GET to contextual filter.

In that way you can able to pass exposed filter value to the contextual filter.


How can I prevent height/width attributes on images run through the theme system?

History
In Drupal 6, populating width/height attributes caused a filesystem lookup (bad for back-end performance) for every image. This was fixed in #908282: Remove unnecessary I/O from theme_image() by removing the height/width attributes altogether in Drupal 7.

Images without height/width attributes are bad for front-end performance so work was done in Populate HTML image tags with dimension attributes (like D6 imagefield) without re-introducing I/O to add them back.

Answer
So you really want your images to have width/height but obviously not if they get distorted. The update functions for 7.9 were supposed to fix this, did you run update.php after upgrading to 7.9?

If you ran update.php then this might be a bug.


How do I correctly setup caching for my custom block showing content depending on the current node?

This is full working code with comments.

namespace Drupal\module_name\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\Cache;

/**
 * Provides a Node cached block that display node's ID.
 *
 * @Block(
 *   id = "node_cached_block",
 *   admin_label = @Translation("Node Cached")
 * )
 */
class NodeCachedBlock extends BlockBase {
  public function build() {
    $build = array();
    //if node is found from routeMatch create a markup with node ID's.
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
      $build['node_id'] = array(
        '#markup' => '<p>' . $node->id() . '<p>',
      );
    }
    return $build;
  }

  public function getCacheTags() {
    //With this when your node change your block will rebuild
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
      //if there is node add its cachetag
      return Cache::mergeTags(parent::getCacheTags(), array('node:' . $node->id()));
    } else {
      //Return default tags instead.
      return parent::getCacheTags();
    }
  }

  public function getCacheContexts() {
    //if you depends on \Drupal::routeMatch()
    //you must set context of this block with 'route' context tag.
    //Every new route this block will rebuild
    return Cache::mergeContexts(parent::getCacheContexts(), array('route'));
  }
}

I tested it; it works.

Just put the code in a file named NodeCachedBlock.php in your module folder, change its namespace {module_name}, clear the cache and use it.


Get Template Variables in my Custom Module

In Drupal 7 getting global module specific settings or module-site configuration settings is done via:

variable_set

  Sets a persistent variable.

variable_get

  Returns a persistent variable.

variable_del

  Unsets a persistent variable.

This is to be used for global settings which means it is used site-wide. In your use-case it seems appropriate to use.

For your custom form you will get the variable when you build the form, and set the variable in the form's submit handler. If you are using system_settings_form, then the process is even easier as all you have to do is to make sure that your form element for the title is named exactly the same as your persistent variable.  For an example please refer to: How to add a custom admin settings form to accept variable values in Drupal

To print the variable in your template you can either get the variable using variable_get in a preprocess function and set a preprocess variable for it which you then use, or you can just get the variable directly within the template. How do you know which method to use? If the template file is rendered because of a theme function, then there will be a preprocess function for it. But don't break your head to much over this one. Because getting a variable using variable_get is such a small operation, you might as well just do it directly in the template file.


How can I create an entity reference field to list a subset of roles?

Two parts to check here.

Is it possible to reference user role (a config entity)
Is there a way to restrict the available roles in the field level.

reg #1, yes! the out-of-box Drupal core allows creating an entity reference field with the target entity as a user role.

For #2, there is no easy way as the only way to restrict the available option(in core) is via views, but unfortunately, we can create views of the content entities. However, we can add a reference handler with config (as below) to restrict the available roles.

<?php

namespace Drupal\mymodule\Plugin\EntityReferenceSelection;

use Drupal\Core\Entity\Plugin\EntityReferenceSelection\DefaultSelection;
use Drupal\Core\Form\FormStateInterface;

/**
 * Provide configuration to select specific roles to reference.
 *
 * @EntityReferenceSelection(
 *   id = "default:user_role",
 *   label = @Translation("Role selection"),
 *   entity_types = {"user_role"},
 *   group = "default",
 *   weight = 1
 * )
 */
class RoleSelection extends DefaultSelection {

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $configuration = $this->getConfiguration();
    $entity_type_id = $configuration['target_type'];
    $storage = $this->entityTypeManager->getStorage($entity_type_id);

    $options = array_map(function ($entity) {
      /** @var \Drupal\Core\Entity\EntityInterface $entity */
      return $entity->label();
    }, $storage->loadMultiple());

    $form['target_roles'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Allowed roles'),
      '#options' => $options,
      '#default_value' => isset($configuration['target_roles']) ? (array) $configuration['target_roles'] : [],
      '#multiple' => TRUE,
    ];
    return $form;
  }
    /**
   * {@inheritDoc}
   */
  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
    $configuration = $this->getConfiguration();
    $target_type = $configuration['target_type'] ?: [];
    $entity_type = $this->entityTypeManager->getDefinition($target_type);
    $query = parent::buildEntityQuery($match, $match_operator);

    // Add condition, if set of roles selected.
    if (isset( $configuration['target_roles'])) {
      $query->condition($entity_type->getKey('id'), $configuration['target_roles'], 'IN');
    }
    return $query;
  }

}

Here is the field settings page:

and here is the final output:


I would advise node References and Entity Views Attachment

Create 2 content types: 1) Zoo - 2) Animals
Animals has a "Node reference" to a Zoo
Create 2 views: 1) Zoo - 2) Animals -  Attach entity contents by relating them and contextual filters on nid

This way you can create Zoo pages [node] with all the animals in the zoo
On the animal pages [node], you can show which zoo(s) the animal belongs

You can also create pretty overview [views] pages


How to assign user ranks based on their userpoints?

Your question seems like a perfect usecase for the Goals module (disclosure: I'm its maintainer). It can be used in combination with the userpoints module, though you'd use that combination by granting user points "after a goal is completed".

Here is a possible configuration for your specific case:

Define 3 goals like so:

Junior Member
Senior Member
Premier Member

To achieve goal "Junior Member", define the Task(s) to be completed. E.g.:

Publish 1 (or some other amount of) articles.
Post 1 (or some other amount of) comments.

To achieve goal "Senior Member", define the Task(s) to be completed. E.g. publish 10 articles and post 20 comments.
To achieve goal "Premier Member", define the Task(s) to be completed. E.g. publish 25 articles and post 50 comments.
Write the appropriate rules, using the Rules module, to track process on completing the various tasks. Basically you'd only need 2 (extremely basic) rules, which would be triggered like so:

After publishing an article.
After posting a comment.

Note that these very 2 rules can be re-used to measure progress on each of the 3 rules. If you want, you could expand these rules (with an extra rules action) to also assign userpoints, to implement your userpoints design you have in mind.

Refer to my answer to "How to implement gamification in a Drupal site and award incentives?" for way more details about the Goals module.

Note: Using Goals only requires typical administration tasks (configuration), though it does come with various hooks also for custom module development (if you want to).


Still some users working/posting issue. How they able to work on it?

They have set up a working web server, installed Drupal core files and a database, and configured a vhost for it. Once you've got your web server working you'll be able to work on it too. That should be your focus; check your web server error logs and fix everything that it says is wrong.

  is there any alternative link to download d8.

There might be, but why would you want to get it from somewhere other than the official Drupal repository? You wouldn't be able to trust that it was up-to-date or that integrity had been maintained with the official release (without manually checking, obviously, but that seems pointless).


How to output child links based on the current page

Just wanted to follow-up. I came back to this question and found the following: https://stackoverflow.com/questions/2716787/how-to-get-all-the-menu-items-below-a-certain-parent-in-drupal which is exactly what I needed.

The code, copied from the above-mentioned link and modified to fit my needs (mainly to use the current path to build the menu tree from, rather than using a hard-coded value:

$parent = menu_link_get_preferred($_GET['q']);
$parameters = array(
  'active_trail' => array($parent['plid']),
  'only_active_trail' => FALSE,
  'min_depth' => $parent['depth']+1,
  'max_depth' => $parent['depth']+1,
  'conditions' => array('plid' => $parent['mlid']),
);

$children = menu_build_tree($parent['menu_name'], $parameters);

return '
' . drupal_render(menu_tree_output($children)) . '
';


Accessing a selected value instead of key in drupal 8

Assuming that code is in a submit/validate method, you have the original form array available, so you can grab the options straight from the element definition:

$key = $form_state->getValue('foo');
$val = $form['foo']['#options'][$key];


I ended up using Views Bulk Operations to generate the page content and then I added some javascript and css to hide certain things and to also add some extra fields, etc.

It was a total hack, but it got me through on a time crunch.


Transfer Value of Field to Another Field under Content Type Manage Fields

No, this is not easily possible through the Drupal interface. You will need to execute a custom SQL query to move your data from one field to another.

The following two queries will copy all field data from field_image to field_screenshot for each entity where field_screenshot is empty.

INSERT INTO field_data_field_screenshot
SELECT a.*
FROM field_data_field_image a
LEFT JOIN field_data_field_screenshot b ON a.entity_id = b.entity_id
AND a.entity_type = b.entity_type
WHERE b.entity_id IS NULL

and

INSERT INTO field_revision_field_screenshot
SELECT a.*
FROM field_revision_field_image a
LEFT JOIN field_revision_field_screenshot b ON a.entity_id = b.entity_id
AND a.entity_type = b.entity_type
WHERE b.entity_id IS NULL

After running this you can then delete the first field.

If field_screenshot alreadly has data that you want to overwrite you will need to  delete it first using these queries. Make sure this is what you want to do first because this WILL delete your data

TRUNCATE TABLE field_data_field_screenshot
TRUNCATE TABLE field_revision_field_screenshot


How do I loop over result rows and return calculated values?

This is because $results[$static['entityform_id']]['sum'] already contains the sum result from previous loop result.
Thus it adds 55 for every row iteration.
Try adding the current array index to $results inside foreach loop.


Scheduler Module crontab job does not publish content

If you use Content Access module, see that issue :
https://www.drupal.org/node/2865787

Enzo


How to generate a list of all valid URLs served by my site

There exists a number of website checking tools (aka. robots or spiders) that will crawl a given website and generate a number of reports, including a report of all URLs found on that site by recursively crawling the site from some starting point (crawl foundation page).

Below are links to three such tools that I've used for this purpose:

WebCheck: http://arthurdejong.org/webcheck/
Link Sleuth: http://home.snafu.de/tilman/xenulink.html
DRKSpider: http://www.drk.com.ar/spider.php

Note that these will only report URLs that are reachable from the crawl foundation page. If your site consists of sub-sites that are not reachable from each other, you need to set up more than one crawl foundation.


Create a view that displays only the fields from the most recent user node

Add a contextual filter for user
Set pager to "none" and "number of items to display" to "1".
Set a sort criteria to sort by date, descending.


Apart from the solution mentioned in the link included in your question, here are a few other things you may want to try:

Temporary change the configuration of the file system used by Drupal, to use a relative path to the temp folder (eg ..\temp) instead of a full path (eg C:\path\to\your\webroot\temp).
In your question it says "... during the update of some modules...", but nowhere you explained HOW you're performing this update. Are you using the update tool within Drupal? Are you using Drush? Are you performing this update using FTP or something like that? Whichever method you use, try to use any of the other typical approaches for updating modules. While doing so, you may run into some other unexpected problem/message, which may actually give you a clue about what your real problem is. E.g. some problem with a tmp-like folder to just unpack the new version of the module.
Try to disable all your modules first, then re-enable one of them again, and apply all updates, if any, related to that module you just enabled. If for this first module the error doesn't come back, you've reduced the list of modules that cause your proble with one. If the error does come back, disable that module again (to be investigated in more detail afterwards). Repeat for each of your other modules. This approach should help you to find/identify the problem module (and either leave that disabled, or start in depth debugging of that module).


i guess your using the quicktabs block. if so you can configure here admin/structure/blocks


Conceptually the business logic you want to complete is possible using Drupal. Finding a way to make this scale to a very large website -- I leave as a project for you.

Start by looking at Saved Searches and Views Saved Search or Views Save. These modules let you save a search with a simple name for later re-use. Some of these modules allow per-user saved searches.

You could then create a Queue using the Queue API in Drupal to periodically process the resultsets of these searches. Or even use the Relation module to store heuristics on these resultsets.

Create a cron task using hook_cron or Rules Scheduler to periodically process the resultsets and have Rules to send off emails about new changes in the saved searches. Functions like views_get_results (if you use views_saved_searches) can help you to get these results.

So in general yes it's possible with Drupal -- scaling all this to a very large amount of  users is either an infrastructure problem or something (i think) "Drupal" shouldn't do in the long run ...


How to disable 'promote to front page' and 'sticky' options?

There are 3 places, where those options can be seen:

on admin/structure/types/manage/article, for the "Article" content type

on node/2/edit, for the node with ID equal to 2

on admin/content, between the "Update options"

If you need to remove the options from those setting/administrative pages, then you need to alter the following form builders:

node_type_form()
node_form()
node_admin_nodes()

node_admin_nodes() is the form builder for the node administration overview in admin/content, which includes the "Update options" field that allows the users with the right permission to promote/demote a node from the front page, and to make a node sticky. The field lists all the node operations implemented by modules; in the list of the operations obtained with $operations = module_invoke_all('node_operations'), those operations are represented from $operations['promote'], $operations['demote'], $operations['sticky'], and $operations['unsticky'].


How to get RSS feeds from other sites and display their links in a block?

Drupal 6, Views-6.x-2.12 has built-in Aggregator type you can configure. Make sure you have contents in your aggregator from a valid RSS Feed.


create a field that display value from an other one?

I'm not sure this is suited to your needs but maybe the entity reference module might be able to help you :

  Provides a field type that can reference arbitrary entities:

  A generic entity reference field Four widgets:
  Two implemented on top of the Options module (Select and Radios/Checkboxes),
  Two autocomplete
  widgets (one with one text field per entry, one tag-style with
  comma-separated entries in the same text field)
  Two formatters:
  A
  "Label" formatter, with optional link that displays the label of the
  referenced entity (the node title, the user name, etc.)
  A "Rendered
  entity" formatter, that renders the references entity using a
  configurable view mode Integration with Views (for both forward and
  backward references)
           Integration with Entity Metadata (and as a
  consequence with Search API and the like) Integration with Devel
  generate Integration with Feeds and Migrate (>= 2.3) for painless data
  import This modules depends on Entity API and CTools.


Redirect to profile2 page after adding user based on roles?

Here's how to fix the problem I was having and a little more context on how to do it.

First you need the Rules module. http://drupal.org/project/rules

Go to the rules configuration page, usually located at example.com/admin/config/workflow/rules

Add a new rule
Add condition

User has role(s)
Parameters should be   User: [site:current-user], Roles: roles for condition
in my case
Parameter: User: [site:current-user], Roles: developer, site administrator

add an action

Page redirect to new user profile
Parameter: URL: user/[account:uid]/edit/'profilename'
replace 'profilename' with whatever your profile2 profile is called

Before I was using the default 'account' parameter, changing it to the User: [site:current-user] fixed my problem.


How do I add an image for each menu column?

It's pretty easy to do that with CSS

#column-1{
  padding-top:20px; /* Space for image */
  background: transparent url('../images/bg-col-1.png') no-repeat left top;
}


Is putting content in the codebase or the database better for performance?

Quick answer is that the DB should be slower. In reality the only way to know for sure is to profile the PHP code and get a cache grind of it. One being rendered by panels and the other by core blocks is the main reason most likely in this case.


How to add page "Contact us"/"Terms of usage" using a link in the footer but page's content to be in the main content(middle region)?

Do not know the version your using., search for 'overlay' in modules there are many.

In Drupal 7. Grab the following for direction

http://drupal.org/project/admin_path

http://drupal.org/project/context_overlay


hook_form_alter Save $form['account']['field_first_name'] into $form['profile']['field_first_name']

Got it! In my hook_form_alter function I added $form['#submit'][]='my_submit';

Then I created the my_submit() function.

function my_submit($form, &$form_state) {
  if (count($form_state['input']) > 0) {
    form_state_values_clean($form_state);
    $form_state['values']['profile']['field_first_name'] = $form_state['values']['field_first_name'];
    $form_state['values']['profile']['field_last_name'] = $form_state['values']['field_last_name'];
    $form_state['values']['profile']['field_groups'] = $form_state['values']['field_groups'];

    unset($form_state['values']['field_first_name']);
    unset($form_state['values']['field_last_name']);
    unset($form_state['values']['field_groups']);
  }
}

The important parts of the function above to notice are form_state_values_clean($form_state); then I access the values through $form_state['values'] array.

Hope this helps someone else looking to do the same functionality.


Why is Search API only searching node titles?

This is probably due to a misconfiguration in your search_api view. I'm assuming you're using an exposed filter and you'll need to be sure that your Keyword Search filter is configured to also search the body field. Edit the settings for the exposed filter and make sure body is selected in the Searched fields field.

It could be helpful to configure a search_index view mode for your nodes and configure search_api to index that view mode, then you can set your exposed filter to just search on that one "field". I find that it helps to keep things running smoothly and consistently across content types that don't necessarily share fields.

Also, make sure your content is actually indexed, sometimes it's just queued and hasn't actually been indexed yet. You can do that from your index's "View" tab.


Create a X discount for every Nth product from the same category

Depending on how you've constructed your product data model, the Per-quantity category discount (% off) offer type supplied by the Commerce Discount Extra module should just work. It lets you specify how many products of which product category must be present on an order before the next one is discounted by any percentage (e.g. buy 2, get 1 free - 100% off). It's repeatable, meaning you can apply the discount any number of times on the same order so long as the right quantity is present, and you have some rudimentary sorting options - e.g. discount the cheapest or most expensive first.

If that solves it for ya, mark this answer as accepted. If you need a little more detail, feel free to add a comment and I'll help if I can. : )


Cannot block access to nodes with hook_node_access_records

Blog post needs to be updated. I remember having discussion with him about it.

hook_node_access is a deny access; grants are if a user has any matching grant, they have access.

you can use the alter hook to remove undesirable grants, but doing custom access requires a lot of testing and thinking. Also, read the https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_access/7 node_access documentation/code


Here's the solution:

<div class="searchblock">
<?php
print drupal_get_form('search_form');
?>
</div>

<?php
$keys = arg(2);
print search_data($keys, $type = 'node');
?>
</div>


It can't be that hard to understand. There's a syntax error:

ÁREA DE CLIENTES <img height="14" width="14" src="/sites/default/files/pictures/clipart/key.png"

 tag is not closed. That's breaking your whole page HTML structure/well formedness.


How do I deploy/manage similar sites from an unique profile, without dumps?

Features can help bypassing the UUID problem. It's still buggy, which prevents us from fully automating the process, but we can at least shift and maintain configuration manually.

Features still creates modules, it exports the configuration into the config/install directory of the given features module. This will be picked up when you install the feature, and you can continue to update your site config (similarly to what the old drush features-revert did) as your features export changes.

You can also import configuration directly via drush, make sure to use the --partial flag, to avoid overriding configuration not in the config folder. Using --source you can also define a custom configuration folder location, so you can do something like drush cim --partial --source=docroot/modules/features/myfeature/config/install.


Drupal 7, passing URL arguments page not found

Try editing your .htaccess file and uncomment the following line:

RewriteBase /


Remove the cache for a particular Twig file

You need a cache context and a cache tag of the user:

$variables['username'] = [
  '#markup' => \Drupal::currentUser()->getUsername(),
  '#cache' => [
    'contexts' => [
      'user',
    ],
    'tags' => [
      'user:' . \Drupal::currentUser()->id(),
    ],
  ],
];

You can add this directly in a preprocess hook, but then the rendered output will vary for each user. For large numbers of users you might want to put this in a lazy builder callback, which will then match the auto-placeholder conditions and can be lazy-loaded through BigPipe without affecting page load performance.

See https://www.drupal.org/docs/8/api/render-api/auto-placeholdering


node_object_prepare causes profile page for non-admin users

I solved this by ripping the guts out of the node_object_prepare function, pasting it into the module and editing it appropriately so it served my purpose.


Why isn't my new module listed in the list of modules?

The first things I would check:

Permissions settings of the files (chmod - chown)
Remove a module to see if it has any effect


It seems you can achieve that using the Rules module.

  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.


Why does webform module uses $node->webform as a property?

because webform is not integrated to drupal entity concept

check entity form module that is integrated with drupal entity
https://drupal.org/project/entityform


Drupal Services 3.x - Custom error output

You most certainly can.

If you open up the docs folder in the services module you can see the function hook_rest_server_execute_errors_alter(&$error_alter_array, $controller, $arguments) in the file services.alter.api.php

<?php
/**
 * Allows alteration of error data before the status code or message are returned.
 *
 * @param array $error_alter_array
 *   An associative array with the following keys:
 *     - 'code': the HTTP status code.
 *     - 'header_message': the message returned as part of the error response
 *       (for instance, "404 Not found").
 *     - 'body_data': data that was passed to the thrown exception.
 * @param array $controller
 *   The current controller definition.
 * @param array $arguments
 *   Arguments passed to the current controller.
 *
 * @see RESTServer->handleException()
*/
function hook_rest_server_execute_errors_alter(&$error_alter_array, $controller, $arguments) {

}

Example output would be:

Array (
  [code] => 401
  [header_message] => 401 Unauthorized : Missing required argument username
  [body_data] => Missing required argument username
)

So you could alter it like,

function MYMODULENAME_rest_server_execute_errors_alter(&$error_alter_array, $controller, $arguments) {
 $error_alter_array['code'] = 500;
 $error_alter_array['header_message'] = '500 Come on man, send that username';
 $error_alter_array['body_data'] = 'Come on man, send that username';
}

Note: You do not need to return anything because it is alter by reference and two, make sure you clear cache after adding this function to a module.


Commerce - Hide Add-to-Cart form from Anonymous users

From the link : http://www.drupalcommerce.org/node/2528 with an condition for anonymous user added.

  It's taken me a while but I've finally cracked it! I've used
  hook_form_FORM_ID_alter() (that took me some learning and meant I had
  to create my own, admittedly trivial, module!). So in my module I've
  got the following which sets #access for the submit form to false
  which stops it being rendered (see
  http://api.drupal.org/api/drupal/developer%21topics%21forms_api_referenc...).

  In the future, I'll be able to extend this to disable the button on
  certain conditions (say when there's no stock but I want to show what
  combinations are possible). It would also presumably be an easy way of
  changing, say, the text for the button, such as "Buy" instead of "Add
  to cart".

  function mymodule_form_commerce_cart_add_to_cart_form_alter (&$form, &$form_state, $form_id) {
global $user;
    if ($user->uid == 0) {
    // Disable the Add to Cart submit button

  $form['submit'] = array('#access' => FALSE);
        }
    }


Pass contrib module tokens to custom event in rules

When the Rule gets invoked, you can send any number of parameters along with it. Just make sure they match the expected data type.

rules_invoke_event('stripe_subscription_event', $acting_user, $plan, $stripe_subscription_event);

This will trigger the Rule and send the variables along. It is up to you call this function and obtain these values somehow.

Since your Rules description is A user subscribed, I suppose you should the submit function of that event to invoke the Rule. You might be able to grab the values from the $form_states['values'] array. I have no idea what the Stripe subscription module does, so I am not sure how you should obtain these values.

I don't think you can use tokens. Those are specifically for rendering content and I have never seen them used in code. (You might obtain the values by copying some of the logic though.)


Private files get Access Denied for any non-admin role but only on server

The issue is due to the File Entity module. This was still enabled on our site even though it has been deprecated. Once it is uninstalled; private files work as expected.


It is possible to do it without coding from the admin area.(Disclaimer: a bit hacky).

Go to the "admin/config/content/formats" area and disable all the filter formats except "Plain Text".

Go to your content type display settings tab and change the format in the dropdown to "Default" and save the settings.

If you view your node now, you will be able to see its raw content form without all the sanitation.


How can I debug entity queries in Drupal 8?

For Drupal 8, there is the Devel module and the Web Profiler module. The latter module, once enabled, installs a toolbar at the bottom of the page for users with the appropriate permissions. The database button within this toolbar takes you to a inspection page that shows all database queries executed during the last request.

If you're able to trigger the entity query through any browser request, you should be able to inspect the list of DB queries for the specific entity query you're looking to debug.


Theming a menu - removing a whitespace between the last  and

Because it sounds like your question is really about how to manipulate the main menu markup in Omega, I guess I'll focus on that. That said however, the "whitespace" issue from the post that you reference is quit strange, as I'm not sure I understand how a newline between an closing li and ul tag would influence any visible alignment behavior. I'm also not sure that Omega even adds any such newlines to the menu output by default. Still, it sounds like you've isolated this as a cause already.

If you are using the main menu that's automatically inserted within the page by Omega (as opposed to displaying your main menu via a menu block or similar), then I believe the most specific theme hook that applies is 'links__system_main_menu'. Check out the omega/omega/templates/region--menu.tpl.php theme file to see how this is ultimately called.

It's important to note however that 'links__system_main_menu' is not necessarily a hook that you'll find an existing theme function for, it's just a suggested pattern. See this post for more on that. Chances are the theme function that's actually getting used currently is theme_links(), or in the case of Omega (which already has an override setup) omega_links().

So if you want to target an override that's specific to just the main menu you could use the code from omega_links() as a template for your own override called MYTHEMENAME_links__system_main_menu(). Then within this new function you could adjust the output to tweak the way "whitespace" is added before and after any ul and li tags as you deem necessary.


Restrict pagination using entity field query

It's very easy. Just use

$pager=theme('pager', array('quantity' => 6));


How are SQL queries properly handled within a module?

Drupal essentially has three groups of functions to query the database:

Functions to make static queries
Functions to make dynamic queries
Functions to make queries about entity fields

db_query() and db_query_range() are part of the first group, while db_select() is part of the second group; finally the EntityFieldQuery class is what you use for queries involving the values of entity fields.

To make clear which functions you should use, keep in mind that dynamic queries are those queries that are dynamically built at run-time, such as in the following code.

$table = $load_current ? _field_sql_storage_tablename($field) : _field_sql_storage_revision_tablename($field);

$query = db_select($table, 't')
  ->fields('t')
  ->condition('entity_type', $entity_type)
  ->condition($load_current ? 'entity_id' : 'revision_id', $ids, 'IN')
  ->condition('language', field_available_languages($entity_type, $field), 'IN')
  ->orderBy('delta');

Since the table name changes at runtime, using that code is preferable to concatenate strings to build the query.

Dynamic queries are also those that needs to be altered by other modules, such as the following one.

if ($nids) {
  $query = db_select('book', 'b', array('fetch' => PDO::FETCH_ASSOC));
  $query->join('node', 'n', 'b.nid = n.nid');
  $query->join('menu_links', 'ml', 'b.mlid = ml.mlid');
  $query->addField('n', 'type', 'type');
  $query->addField('n', 'title', 'title');
  $query->fields('b');
  $query->fields('ml');
  $query->condition('n.nid', $nids, 'IN');
  $query->condition('n.status', 1);
  $query->orderBy('ml.weight');
  $query->orderBy('ml.link_title');
  $query->addTag('node_access');
  $result2 = $query->execute();
  foreach ($result2 as $link) {
    $link['href'] = $link['link_path'];
    $link['options'] = unserialize($link['options']);
    $all_books[$link['bid']] = $link;
  }
}

$query->addTag('node_access') allows other modules to alter the query to return only the nodes to which the currently logged-in user has access.

In the other cases, it is preferable to use a static query, which are faster. The only case you should not use static queries is when the query involves the value of entity fields; in which case, you should use the EntityFieldQuery class, which avoids you need to know any details about how entity fields are implemented (e.g. which database classes contain the field values).

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_news_types', 'value', 'spotlight', '=')
  ->fieldCondition('field_photo', 'fid', 'NULL', '!=')
  ->fieldCondition('field_faculty_tag', 'tid', $value)
  ->fieldCondition('field_news_publishdate', 'value', $year . '%', 'like')
  ->fieldOrderBy('field_photo', 'fid', 'DESC')
  ->range(0, 10)
  ->addMetaData('account', user_load(1)); // Run the query as user 1.


not found in Multi language site with only session detection

The problem was resolved: When we create a new content type, the "Multilingual support" in "Publishing options" should be set to "Enabled, with translation."


is it possible to hack a module by mymodule?

No, it's not possible in the manner you are describing. However, Drupal provides many _alter() hooks that allow various things to be altered as necessary, so that you don't have to hack anything.

However, without specifics on what you want to do, I cannot suggest any specific methods.


Can't get form_state['values'] from a form on a custom checkout pane

The function "commerce_checkout_complete_registration_pane_checkout_form" needed to have the $form variable passed as a reference, &$form.


I cannot log in, and I am said I have 5 failed logins

The quick solution is to login in your database
mysql -u <username> -p<password> or drush sql-cli

and execute this query

truncate flood;

Thats it and you'll able to login again.


How to insert social share buttons in drupal 7 using Bootstrap Social Sharing Buttons?

This module implements networks by harcoding in the module's code. Because it is not much clean way how to implement modules for this use-case and this module is not widely used, I recommend you to use somethink different.

If you dont't want to include third party scripts to your site (they can spy your users and slows down page) you can use this module: https://www.drupal.org/project/service_links It is also widely used, so should be better developed and maintained in the future.


Override theme_date_popup in your theme or custom module.
See the following tutorial how to do it.


I would suggest you use Display Suite. This module allows you to define a layout for the entry form and/or the display of any content type. If you want to use Views to create a list of nodes, you can use the layout you created to display each of the nodes in the View by selecting Unformatted list of Full posts in the Display format dropdown lists in the Views wizard.

There are several excellent video tutorials for Display Suite, but I'd recommend the ones its author created.


views-view-field.tpl.php - How to print multiple values?

You can do it in the template itself quite simply, something like:

<?php foreach ($row->field_my_field as $data): ?>

  <?php if ($data['raw']['value'] == 'o'): ?>
    // Output nothing, or placeholder, whatever
  <?php else: ?>
    <?php print $data['rendered']['#markup']; ?>
  <?php endif; ?>

<?php endforeach; ?>

This is a custom template for that particular field, and so should only be used with it (which can be done via preprocess). You might also need to be careful about the name of the field changing if the field's changed in the View.

The nicest approach I can think of is probably using hook_field_attach_view_alter():

function MYMODULE_field_attach_view_alter(&$output, $context) {

  $field_name = 'field_test';
  $to_hide = array('o');

  if (isset($output[$field_name]['#field_name'])) {
    if ($field_name == $output[$field_name]['#field_name']) {
      foreach ($output[$field_name]['#items'] as $delta => $item) {
        if (in_array($item['value'], $to_hide)) {
          unset($output[$field_name][$delta]);
        }
      }
    }
  }
}

That will work for Views and a normal entity view. AFAIK you can use $context to detect whether you're in a View or not, but I can't remember what you'd check for exactly. (And if you later find you do want to display the field like this outside of Views, it's painless to change.)

HTH


Why is Twig not outputting this correctly?

It's unsafe to use the |raw filter. Put HTML markup in a #markup element instead:

$variables['foo'] = [
  '#markup' => ' AA <strong> BB </strong> CC ',
];

Then outputting this variable in Twig should work:

{{ foo }}


How do I display a link icon in custom modules?

You can convert markup with image tags and convert it into URL with image like below:

use Drupal\Core\Render\Markup;

$imgsrc = Markup::create("<img src ='$base_url/scp/sites/default/files/images/corr_icon.gif'>");
$correct_link = Url::fromUserInput('/answer/'.base64_encode($data->ans_refno).'by'.base64_encode($data->q_id));
'isanswer' => \Drupal::l($imgsrc, $correct_link),


As I mentioned in IRC, the following work-around should resolve that particular issue:

Login to the server via ssh.
Become the 'aegir' user (sudo -u aegir -s -H)
Create a file call /var/aegir/.drushrc.php with the following contents:

 <?php
 $options['strict'] = 0;

That said, this appears to be a bug, though not one that has been reported previously. If anyone else stumbles across this issue, please file a bug report at https://www.drupal.org/node/add/project-issue/provision.


Unlike Wordpress, Drupal doesn't care on the hostname. Unless you statically mentioned the domain in any custom modules/themes, this will be a straight forward change.

Change the domain name using a local host file.
Change the trusted hosts configuration (for D8, in settings.php)
Try accessing the site after the drupal clear cache, using drush.

If you are experiencing any issues, try searching for domain.com using grep and replace. Better to refactor the code without the domain hardcoded.

Edit: The links hard coded in WYSIWYG editors like ckeditor can create issues. You may have to update programatically or manually.

Edit2: You can use pathlogic module (not tested, d8 version is usable). to reformat the URLs in the content.


Drupal 8 create a template override for a view block within a custom module

To get the same variables as a block template add it as base hook:

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return [
    'block__views_block__MYVIEW_block_1' => [
      'render element' => 'elements',
      'base hook' => 'block',
    ],
  ];
}

Now you can place the twig template in mymodule/templates/, path and filename are discovered automatically.


I believe you need to add the data as an array to an associative array with the 'data' key, and the attributes with the attribute name as the key. For instance, your code would look like:

$rows = array();
foreach ($result as $item) {
  $rows[] = array(
    'data' => array($item->title, $item->housestaff_needed),
    'id' => 'staff-' . $item->projectID,
  );
}
$theme = theme('table', array('header' => $header, 'rows' => $rows));
return $theme;

I think this will add an id to each <tr>. If you want to add attributes to each individual <td>, you would use a similar structure for $item->title and $item->housestaff_needed. That is, it would become:

$rows = array();
foreach ($result as $item) {
  $rows[] = array(
    'data' => array(
      array(
        'data' => $item->title,
        'id' => 'SOME_ID',
      ),
      array(
        'data' => $item->housestaff_needed,
        'id' => 'SOME_OTHER_ID'
      ),
    ),
    'id' => 'staff-' . $item->projectID,
  );
}
$theme = theme('table', array('header' => $header, 'rows' => $rows));
return $theme;

At least, that's how it works in d6, I beleive, so here's hoping it still works in d7.


How can I write into a Flag's custom field programmatically?

I fix it with this code.
You should save the output of the function

$flag_service->flag($flag, $entity);   //Wrong method

in a variable like it

$id_flagged_entity = $flag_service->getFlagging($flag, $entity);

and set the title at this entity

$id_flagged_entity->set("field_my_custom_field", $link_name);
$id_flagged_entity->save();


If you want to get simple form elements to include webform element enhancements you have to 'initialize' the composite's sub-elements using \Drupal\webform\Element\WebformCompositeBase::initializeCompositeElements


Have you looked at Views Data Export. I've wired in a view to export on button click. You just build or modify a FAPI form to contain a button and give it the url of the view you want to output as csv.

In your case you'd pass the selected arguments into the view. You could use FAPI and Javascript to properly build the url and button action.


Can A View Load All Data, And Filter (Hide) With CSS?

A module might be able to help you with this
https://drupal.org/project/mixitup_views (drupal 7 + 8)
Loads all items and might be close to what you need
https://www.drupal.org/project/isotope (drupal 7 + 8) A highly customizable module that is probably harder to implement as well
Some other alternative modules
https://www.drupal.org/project/views_semantic_tabs (drupal 8) might be a good fit
https://drupal.org/project/shuffle (drupal 8)
Not sure if it loads all results at once but it offers the filtering you described
https://drupal.org/project/views_quicksand (drupal 7)
does not load all results at once by has the filtering effect that you need so it might be a starting point
NOTE: all or almost all above module use JS libraries that you have to pay for if you implement them in commercial products
A custom alternative
Create a view that displays all results
and use global text area to rewrite all the elements to be part of a container div
and add classes to the container based on the categories you want filterable
Then use this code https://codepen.io/terf/post/jquery-filter-divs
in your custom module or theme changing box class with your container's class name


How to change documents to another category painlessly

Try Node Convert, it allows you to change one content type to another:

  Node Convert adds a menu tab "Convert" on the node view page, i.e.
  node/1/convert, which gives the ability to convert the node from its
  current node type to another node type. The module provides the means
  to transfer all the field values of the current node type into fields
  on the destination node type, or discard them.

Then you can use Views Bulk Operations to do it in batches.


page-new.tpl.php shows page not found in browser title

This will set the title in the actual browser window:

function MYTHEME_preprocess_page(&$variables) {
  drupal_set_title(t('Custom title'));
}


How to create a tick list which one role can alter for 'lesser' roles to see?

From the interface that you have outlined, I could see that the 'Flag' module might be really nice for the administrator and user to interact with this kind of list.  In a list of nodes, flags would allow in place editing, changing the status, without going into each individual node.

You could configure the names of flags, status, and transition.  It would also be possible to assign permissions as to who has permission to change flags between states, and to allow users to change some of the flags themselves.

http://drupal.org/project/flag

To restrict what is seen by the users in the lists, perhaps you could build two similar views blocks: one showing all of the nodes (for administrator), and the other filtered only to show those with flag set to 'show' (for normal users).

The options in each view can be configured to selectively shown each block only to the appropriate role, and then both blocks could be embedded at the appropriate place.

Please note, that is not really enforcing permission to view the hidden nodes, and that a user could find them if they really try hard. It's just being selective about what is shown in the lists.

I was not able to quickly spot an existing module in drupal.org which would set node access by flag status.  You may have some luck with some further searching.

However  you can use 'Rules' to take actions on flag changes.  I think you might be able to pull something together by setting up a series of rules which then assign individual node permissions using 'content access' or another node access module of your choice when the show/hide flag changes state.

Otherwise you could use node_api and write your module to enforce your particular access rules  based on flag status.


Moving from Custom MySQL-Based Blog to Drupal

You can create nodes from external databases using the Feeds SQL module (requires Feeds). You should create a content type for the fields you want to import, and use the Feeds UI to select the external database table(s), add a query, and map the output to the fields in your content type.

Here are a couple of settings that you need:

Preparation: add your new source database to settings.php:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'drupal_database',
      'username' => 'drupal',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'database_to_migrate' =>
  array (
    'default' =>
    array (
      'database' => 'database_to_migrate',
      'username' => 'migrateusername',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
)

Now: go to the Feeds UI, and start configuring:

1. Basic - attach to - your new content type
   Import on submission - checked

2. Fetcher - click "Change" -> select "SQL fetcher", save

3. SQL Fetcher - click "Change" - select your source database

4. Parser - click "Change" -> select "SQL Parser", save

5. SQL parser - click "Change" -> Enter your query, select your database, save
   Verify that your query performed as expected, results are displayed.

6. Processor - select "Node Processor" for nodes

7. Node Processor - Settings: Here, you can choose the content type (again),
   the author associated with the new node, format, expiration, and other parameters.

8. Node Processor - mapping: Here, you have to map the fields from the sql query
   to the fields in your content type. After you save, you can map the next field

Since you only have a couple of users/authors, you could create accounts for them manually. In your SQL query, you can select the users as well as the content/title/etc., and the new articles will then be associated with the appropriate authors.

This has worked well for me with a limited number of nodes (<1000). For large-number of nodes, I ran into time-out issues, and had to add a limit to the SQL query. Eventually, I just created a drush script to add the nodes from the command line (I had to add >50,000 nodes).

Edited to add: I used this with Drupal 7. Please read the documentation for the modules for updated information: https://drupal.org/project/feeds, https://drupal.org/project/feeds_sql


I want to save and view the node content in the same page without page refresh using content types

Here I have some material for you that will help you to save node form through ajax without refreshing the page at https://www.drupal.org/node/752056 . Here is also another link that will clear your idea about ajax enabled form at https://www.drupal.org/node/264429 .
The solution of second part of your question that shows the node value is so simple. Just make a block views containing your required field from your selected content type and then place that block into your current admin theme at desired region. Don't forget to apply restriction to only show to specific content type.


Drush php-script | Drupal functions such as node_load() are not being found

I finally figured out what was missing.

In my case I had to install the mysql-client-core-5.5 package with sudo apt-get install mysql-client-core-5.5.


Exclude certain taxonomies from url reachbility

Use hook_menu_alter to change the access control for taxonomy/term/%


Term reference with radio buttons + bootstrap tooltip

Part 1

You can theme a field, using theme suggestions:

  field--[type|name[--content-type]|content-type].tpl.php base template:

  field.tpl.php

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

  field--field-name--content-type.tpl.php
  field--content-type.tpl.php
  field--field-name.tpl.php field--field-type.tpl.php

  Note that underscores in a Field's machine name are replaced by hyphens. Also
  remember to include "field-" in custom field names, e.g: field--field-phone.tpl.php.

Get a copy of the base field theme from modules/field/theme/field.tpl.php and copy to your theme's folder, rename and modify as required.

Part 2

A better options is to use the Fences Module which allows for greater control over theming your fields.

  Fences is a an easy-to-use tool to specify an HTML element for each
  field. This element choice will propagate everywhere the field is
  used, such as teasers, RSS feeds and Views. You don't have to keep
  re-configuring the same HTML element over and over again every time
  you display the field.

All of the field tempaltes are in /sites/all/modules/fences/templates and correspond to the type of wrapper you have applied to your field.

Like part 1, copy the field you need into your theme's folder, rename and modify as required.


Is there any way to sort by Image Quality?

The only way that I see is calculate image quality when it's saving and use it later.
How to do it:

Extend your file entity via module File entity
Add special field to store value for image quality.
Save value of quality into this field each time when file is saving. For example via hook_entity_presave
Sort by this field in your views

How to calculate image quality? Here is good example
but you can use your own approach to do it.

P.S. Yes it looks a little tricky but I don't think that it's possible to do it easier. But if it's possible I'll be happy to hear it.


It sounds like you need a view of views. Try the module Views Field View.

I don't know if this is doable. But this is what I will investigate:

In your primary view you must create a month only field, and page on that. Then in your secondary view (which will become a field of the first view, and to which you pass the month as context) you return the dates for the passed in context of the month. You will then end up with a multi-value date field in the first view. You might have to do some rewriting of output  (Views PHP?) to get the dates as text or integer fields.

And if you get it right, remember to employ views caching as Views Field View adds a lot of database queries.


Restrict taxonomy terms when users edit content?

Taxonomy Access Control will let you set up the permissions at the term level.

  Access control for user roles based on taxonomy categories
  (vocabulary, terms).

  Automatically controls access to nodes (based on their taxonomy
  terms).
  Configuration page for each user role.
  Three node access permission types: View, Update, Delete.
  Two term access types: View tag, Add tag.


How to move every node to its own subdomain with Drupal?

A couple years later... I have a similar requirement.

The Subdomain Field module works well for me. https://drupal.org/project/subdomain_field

Has clear installation instructions: edit your settings.php, update your virtual host, add a wildcard DNS record. Then simply install the module and add a "Subdomain Field" field type to any content types that you want.

Now when I edit /node/2 and change the subdomain, I have subdomain.example.com displaying the contents of node 2. Perfect!

Note that it requires the Entity API module, but that is currently not listed as a "requirement"


Limit Webform Submission to one per quarter per user

ok so here is how to do that.. you need to create a module and set Drupal cron to run once a day on your hosting provider
then you need your webform to have email unique then do this ....

/**
 * Implements hook_cron().
 */
function YOURMODULE_cron() {
  $current_month = date('m');
  // Get first month of quarter
  $new_month = (3 * floor(($current_month - 1 ) / 3)) + 1;
  $new_month = substr('0' . $new_month, -2);
  $first_quarter_day_date = date('Y') . '-' . $new_month . '-01';
  $today = date('Y-m-d');
  // So this is the first day of the quarter.
  if ($first_quarter_day_date == $today) {
    // Use cache to make sure this runs once.
    $cid = 'clear_out_webform_date';
    $cached = \Drupal::cache()->get($cid);
    $run = TRUE;
    if (!empty($cached)) {
      if (!empty($cached->data['date'])) {
        if ($cached->data['date'] == $today) {
          $run = FALSE;
        }
      }
    }

    if ($run == TRUE) {
      // change this to your webform id
      $webform_id = 'contact';

      // Export all submissions to file.
      $webform = \Drupal\webform\Entity\Webform::load($webform_id);
      $submission_exporter = \Drupal::service('webform_submission.exporter');
      $export_options = $submission_exporter->getDefaultExportOptions();
      $export_options['delimiter'] = ';';
      $export_options['multiple_delimiter'] = ',';
      $submission_exporter->setWebform($webform);
      $submission_exporter->setExporter($export_options);
      $submission_exporter->generate();
      $file_path = $submission_exporter->getExportFilePath();
      // rename the file to something good.
      $filename = $today.'-export.csv';
      $uri = 'public://' . $filename;
      $fileContent = file_get_contents($file_path);
      $destination = $uri;
      // Save the file to be a file entity.
      $file = file_save_data(
        $fileContent,
        $destination,
        FILE_EXISTS_RENAME
      );
      if (is_object($file)) {
        // Probably email your self a reminder here.
        // ^^ file is now an entity so you can do something like.
        // load a know entity and append the file to a document field.
        // or just download it as in the public file dir.

        // Delete previous quarter submissions.
        $query = \Drupal::entityQuery('webform_submission')
          ->condition('webform_id', $webform_id);
        $result = $query->execute();
        if (!empty($result)) {
          $webform_submission_storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
          $submissions = $webform_submission_storage->loadMultiple($result);
          foreach ($submissions as $submission) {
            $submission->delete();
          }
        }
      }
      // set the cache to today so it wont run again.
      \Drupal::cache()->set($cid, ['date' => $today]);
    }
  }
}

have fun and good luck.


Let users create / list their own restaurant menu

Not totally sure what you're looking for. I'm going to assume that you're looking for a particular form to create a restaurant menu from the backend.

Drupal allows you to create this functionality OOTB (out of the box):

Fields (formerly cck pre Drupal 7)
User Roles
User Permissions

You're probably going to need to output this in a pretty fashion so your best bet are some standard contrib modules:

Views
Fields Collections

Nonethless, these modules are standard fare for every Drupal project (except maybe Fields Collections).

Oh i googled and there are possibly similar questions out there on SO:

https://stackoverflow.com/questions/5204936/restaurant-menu-drupal-7
https://stackoverflow.com/questions/4935899/best-drupal-gui-for-displaying-a-tiered-restaurant-menu
https://stackoverflow.com/questions/1835562/drupal-content-type-restaurant-design


Commerce - Views - Taxonomy - Add to cart issue

Instead of rendering fields including the 'add to cart' form as a field, try rendering the full node using a particular view mode which includes the 'add to cart' form. See http://drupal.org/node/1399434#comment-5450456


Upload one image but save/export to multiple formats

If you are on Drupapl 7 then in Admin You would see Image Style. Once you are there you can define different presets such as thumbnail, large, medium etc. There are three predefined presets available. But you can add your own with the dimensions of your choice. Once you set that you can use that where ever you display in the image.

In views or fields display management with in the content type.

For advanced filters you should look into the imagecache actions


How to noindex comment/reply in Drupal 7

You can use any of this code in robots.txt:

User-agent: *
Disallow: /*comment

This will neglect every URL that contains comment.

You can also use the following, to neglect every URL containing /comment.

User-agent: *
Disallow: /comment/reply

User-agent: *
Disallow: /comment

After you do this, check whether it is working or not by using the Google Robots.txt checker.


How to let the admin select multiple users

You can use Views and Views Bulk Operations modules.

You create a new view of users and you specify which bulk actions you allow to be performed.