hybridauth redirection to an emailed link after success login

How did you try to add the 'destination' query? It should be something like this:

$query_array = array('param1' => 'value1', 'destination' => 'original_path');
$options = array(
  'query' => query_array,
);
drupal_goto('link_to_hybridauth_login_page', $options);

Basically, it's important that the destination is passed as part of the $options['query'].

If that doesn't work, try and add your own hook_user_login(), to pick up the 'destination' (or whatever parameter you want to use for the original URL, and redirect the user accordingly). Like:

if (isset($_GET['destination'])) {
  drupal_goto($_GET['destination']);
}

You can see an example implementation of hook_user_login in the user_homepage module code: http://cgit.drupalcode.org/user_homepage/tree/user_homepage.module?id=6803e00

Hope this helps with your problem.

EDIT: The hook_user_login() is meant to be something additional to the hook_init() logic you were trying, but not to replace it. Thought I'd just clarify that =).

EDIT 2: Ok, So if I'm getting the problem right, you need to get not only the 'node/xxx/edit' part of the URL, which you have already sorted (right?) but you need to also get all the params of the incoming URL.

Basically, you need to use drupal_get_query_parameters() for that. So you could assemble the $options array like this:

  $current_query_params = drupal_get_query_parameters();
  // Pick up URL and treat params as you need, and prepare query array with
  // the 'destination' desired, assembled with data from $current_query_params.
  $new_query_array = array();
  $options = array(
    'query' => $new_query_array,
  );

Hope I'm getting it right now. The linked drupal code from user_homepage uses these functions for a very similar scenario. Look at user_homepage_build_homepage_path_from_request() and user_homepage_user_login() functions.


Merge production site's content into staging through database tables

try the migrate or feeds modules. I recently used the migrate module with great success, though it does require you to write your own classes.


The issue is the following:

When you go to www.example.com/movies/star-trek-great/20130702 Drupal sees that this is a path alias to node/#, and it displays that node.  It won't use Views at all.

When you go to www.example.com/movies/Star Trek is Great/20130712, this does not map to any URL, but rather to the View sitting at www.example.com/movies with an contextual filter of Star Trek is Great (and 20130712 most probably).

You may have some other issues to work out as well:

Pathauto is taking out the is (and other small words by default) so there will be a bit of a hard time mapping star-trek-great to Star Trek is Great.

Also, what happens if you have a title of Star Trek is Great!!! that maps to star-trek-great as well?


How can I remove the asterisk for required fields programatically?

This can be removed from the theme.  I'm using a Bootstrap subtheme, so in my case I copied form-element-label-html.twig from the bootstrap templates directory into my subtheme's templates directory, then changed the following line:

  {%- if required -%}
    *
  {%- endif -%}

To:

  {%- if required -%}
    {# * #}
  {%- endif -%}

Clear caches and it's done.


How to serve content type for authorized users as for anonymous?

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

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

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


Create a reference all available block content

Like I said, I'm new to Drupal 8 so not familiar with new rule and features. After a bit digging here is what I found out.

Entity Reference field allows to reference block instances (config) or custom blocks (content).

Before I was set my field to Content > Custom block, now I switch it to Configuration > Block then you have to Place the block that you want to reference to, even if it is in disabled. After that, you can have your Entity Reference field pick that up otherwise it won't show.

You can have a look at here for more detail.


I haven't seen that message myself yet, but just came across a suggestion how to avoid that message. I suppose you're using the entityreference module? At least for what I know the message seems to come from there – so hopefully this hint helps you:

  To avoid some status messages like 'Do something on load', you should uncheck "Test behavior" in "Additional behaviors" section.

As far as I know the author is relating to the entityreference settings – here's the source: "how to render a node field of a referenced node on the node form". I hope it helps somehow.


Reference (include) php file in content summary

If you have a custom module for your site, put the file in that module directory, add it to the mymodule.info file,

file[] = external.inc

and put the include statement in the mymodule.module file. Use the model here if you are unfamiliar.

Make the code a function, named for instance mymodule_standard_summary(), and then use:

<?php
print mymodule_standard_summary();
?>

in the summary of your nodes. This should get you started.

EDIT:

Rather than trying to embed your code in the page like this:

<?php
  // Embedded code
  print $result;
?>

instead you should set it up in a function in your file like this:

function mymodule_standard_summary() {
  // Your code
  return $result;
}

I hope this makes it a little clearer.


Do not want  HTML tag when using footer region

did the validator know you where using an HTML5 site?
http://www.w3schools.com/tags/tag_footer.asp

... anyways you can always edit page.tpl.php or html.tpl.php for your theme to change global page markup like this to however you want.


How to disable redirection to the node after node form submission

Thank you for the comment 4k4. Unfortunately, I didn't have enough time to find a proper solution so I just changed the redirection URL to the same content where the form is exposed.

function THEME_node_form_submit($form, FormStateInterface $form_state)  {
    $node_id = 1;
    $form_state->setRedirect('entity.node.canonical', array('node' => $node_id));
}

I'll try to find a more appropriate solution if I'll have some extra time before deadline :)


As declared in https://www.drupal.org/node/649298#comment-7710069 there won't be any such support in Features module itself. In the same issue, there is also relevant answer in https://www.drupal.org/node/649298#comment-10219951:

  You can instead add a hook_update_N function to a custom module and delete the field with code (see field_delete_field).

This should be used in my_feature.install file. Note that if you go this way, you will probably need to add something like

function my_feature_features_export_files($module_name, $export) {
  if ($module_name == 'my_feature') {
    return array('my_feature.install' => array('file_path' => 'sites/all/modules/my_feature/my_feature.install'));
  }
}

to you my_feature.module file. This ensures that my_feature.install file is added to feature on any further export.


Change submit button to be ajax using jQuery on forget password does not work

I found a solution I want to share with you
I use

jQuery(form).ajaxSubmit();

an remove this

jQuery("#user-pass").submit(function() {
                              alert('Handler for .submit() called.');
                              return false;
                            });

and it solve the problem I hope it can help you


Got it. I returned the answer with ajax_deliver :

function mij_add_aide_list_proposition($nodes){
    // Magic stuff goes here (construction of $nodeList)
    $build['content'][]=array(
      '#prefix'=>'',
      '#suffix'=>'',
      '#markup'=>$nodeList,
    );

  //$test=drupal_render($build);
  ajax_deliver($build);
}

If someone finds another way, I'm open to any change !


How do I get all the users in an organic group with specific role programatically?

It's just a simple sql query, no joins needed:

ie. select uid from og_users_roles where rid=3 and gid=835;

  $members = array();
  $current_members = db_select('og_users_roles', 'ogur');
  $current_members->fields('ogur', array('uid'));
  $current_members->condition('ogur.rid', $rid);
  $current_members->condition('ogur.gid', $gid);

  $result = $current_members->execute();
  while ($res = $result->fetchAssoc()) { $members[] = $res['uid'];}

  // Remove duplicate items.
  $members = array_keys(array_flip($members));


You couldn't implement a single hook in the module twice.

Instead you can define a custom helper function like _MODULE_include_menu() in the .inc file and then use it in the main .module like:

function MODULE_menu() {
  $items = array();
  $items += _MODULE_include_menu();
  return $items;
}


What is the Aegir make_working_copy SCM option mean?

The 'Drush make option' field in the Aegir user interface (when creating a new platform based on a makefile) simply determines whether or not the --working-copy option is passed to Drush make.

The --working-copy option for Drush make "preserves VCS directories, like .git, for projects downloaded using such methods." (source: Drush.org)

Passing the --working-copy option leaves the .git directories intact (as if you had done a manual git clone) and hence allows you to pull in updates, etc.
However, this is not the recommended way of updating modules in Aegir, so the 'Normal - Discards SCM files' option is preferred.

The aegir_make_working_copy module provided this functionality for Aegir 1.x, before it was merged into Aegir core 2.x.


Views List tag filtering, add a tag to a view for filtering purposes

Open (edit) your view
Click on edit view name/description

Add to/change tags under View tag and click Apply


How can I make a curl type http request after a node submission?

There's no pre-configured action for making a back-end request like that, so you will need to write some code. It's not going to be terribly hard to accomplish, though. Drupal has a function called drupal_http_request() to hit the external URL. You'll execute that function within a hook_nodeapi() implementation, which runs at various times in the node creation process.

Drupal 6:

<?php
/**
 * Implements hook_nodeapi().
 */
function MODULENAME_nodeapi(&$node, $op) {
  // In D6, this hook is executed at various points in the node creation/render process.
  // We only want to run code during the node's "insert" operation.
  if ($op == 'insert') {
    // Only run for RSS nodes.
    if ($node->type == 'rss') {
      // Make a back-end HTTP request to an external resource.
      $url = 'http://my-url.com';
      $response = drupal_http_request($url);
    }
  }
}
?>


Missing formatter options for field from a custom table defined in hook_views_data()

You are comparing a standard Views field with an entity field. Only entity fields have field formatters. Create a custom entity instead of a custom table if you want to use this feature. For a standard field you have to use the options provided by Views. There is a trim option as well, but it is named differently, trim in the alter section. You see it in Views UI. Try to configure it and check the exported View.


function name_module_form() {
  $form['logo'] = array(
    '#type' => 'managed_file',
    '#title' => 'Logo',
    '#default_value' => variable_get('logo', ''),
    '#description' => t('Upload File'),
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg'),
      'file_validate_size' => array(100 * 1024 * 1024),
    ),
    '#theme' => 'abc_thumb_upload',
    '#upload_location' => 'public://abc/',
    '#attributes' => array(
    'multiple' => 'multiple'
  ));
}

function name_module_theme() {
  return array(
    'abc_thumb_upload' => array(
    'render element' => 'element',
    'file' => 'name_module.module',
  ));
}

function theme_abc_thumb_upload($variables) {
  $element = $variables['element'];
  if (isset($element['#file']->uri)) {
    $output = '

';
    $output .= 'uri) . '" />';
    $output .= '<input type="submit" id="edit-' . isset($element['remove_button']['#name ']) . '-remove-button" name="' . isset($element['remove_button']['#name ']) . '_remove_button" value="Remove" class="btn btn-default form-submit ajax-processed">';
    $output .= '<input type="hidden" name="' . isset($element['remove_button']['#name ']) . '[fid]" value="' . $element['#file']->fid . '">';

    return $output;
  }
}


Does caching has to be manually disabled for ajaxified forms?

Not sure what you mean by "ajaxified". That sounds like a regular form is automatically "ajaxified".

Potentially this form is violating the principle that GET forms should not manipulate state. i.e. GET forms must be stateless. HTTP dictates this, but in Drupal 7 it was not respected. In Drupal 8 it is.

See https://www.drupal.org/node/2502785.


Problem with escaped characters in attributes

Make sure you aren't check_plain()ing the value before calling it, eg, don't do:

... theme('image', array('path' => 'test.jpg', 'alt' => check_plain($foo));

or otherwise use a $value that has been processed by any 'safe' filters.


Importing a bunch of users from csv spreadsheet file into Drupal 8

Check out the Migrate Source CSV

I know that it uses drush and can import nodes through mapping it in a twig file and I'm pretty sure that it supports users too.

Full steps located here.


D7 block view to only show child nodes based on taxonomy

It turns out the problem was not as hard as I thought. The hard part was to know what relationship to set up and what contextual filter to implement.

I solved it by doing the following

Created a view of content using fields
Created a contextual filter using "has taxonomy term with depth"

Selected default value of taxonomy term ID from URL
Set it to depth 1 to pick up children
Limited to my vocabulary

That part was obvious. The next part is what caused issues and was not obvious. I could not find an example anywhere on how to do it.

It is easy to exclude the current page by using the nid contextual filter and using the "exclude" option under the "More" section. This is the answer found by searching online. The problem is it does not resolve the "peer" content issue. It would only remove the current node and not other nodes with the same term.

To fix that problem I found that when I added a relationship, a new contextual filter previously not available was added to the list and it had the all important exclude feature.

So I

Added a relationship using my taxonomy (Content)
Added a new contextual filter "term ID" previously not available

Selected default value of taxonomy term ID from URL
Limited it to my vocab (probably not necessary)
Set exclude under the More section

This removed all the nodes with the same taxonomy term as the current node, including the current node, leaving only the children nodes


Compine the author id's of two nodes in views and display block if equal

I can't comment, so I'll answer instead.
If I read your question correctly, you want to show multiple specific views on a specific content type which you have associated as a profile page.

You could do the following in each view:

Create a relationship to the Author
create each view as a block, using a contextual filter

(author) User:Name
When filter value not available: provide default, Raw value from URL, Path component 2
path users/%/view-name

add it as a block in an appropriate place for your theme, and restrict it to show only on   users/*   pages

I have done this to show recent blog entries in a profile page.


How do I change a view pager submit from GET to POST?

You can't POST a link, it's a link; by definition clicking it will send a GET for the target href. The best you could do is hijack the click to POST via JS, set something in the session, then reload the page. Or wrap the View in a form and convert the pager to use submit buttons (possibly styled like links)

But that's very awkward, and would be more than a trivial amount of effort to achieve. Plus you'll need to write a custom Views pager for either method, and you lose the ability to link directly to a certain page, destroying navigation and SEO.

I would just leave it as it is (ie the same as every pager you're likely to find), or install Views Load More or something, if it's the UI you're concerned about.


Creating nodes and interacting with drupal from the command line

I think the best option would be to go with the Services module. About the module from the project page:

  A standardized solution of integrating external applications with Drupal. Service callbacks may be used with multiple interfaces like REST, XMLRPC, JSON, JSON-RPC, SOAP, AMF, etc. This allows a Drupal site to provide web services via multiple interfaces while using the same callback code.

You can build the other application (like android app, Java app, and many more...) in any programming languages you like and make the application interact with Drupal using Services. There is an extensive documentation available which would help you through.
Take time to read through the project page (as it contains more resources to explore) and the documentation as it might take time to get accustomed with the module (as it happened with me).

For command line access to Drupal there is a "Command line shell and scripting interface" - Drush (Drupal Shell). List of the Drush commands could be found at this site. It is very powerful utility for Drupal developers (on Windows, Ubuntu Linux, Mac, etc.); but I'm not sure if one is able to create/modify/read content (nodes) with Drush though, I think one cannot do that (please correct me if I'm wrong).


How does the Drupal session system work?

Drupal has a pluggable session handler, however it generally uses a cookie + database session model by default.

The sessions table in the database stores the session details for the users. The session id is stored and matched from a browser cookie.

The settings for session duration can be found in settings.php, in particular:

/**
 * Set session lifetime (in seconds), i.e. the time from the user's last visit
 * to the active session may be deleted by the session garbage collector. When
 * a session is deleted, authenticated users are logged out, and the contents
 * of the user's $_SESSION variable is discarded.
 */
ini_set('session.gc_maxlifetime', 200000);

/**
 * Set session cookie lifetime (in seconds), i.e. the time from the session is
 * created to the cookie expires, i.e. when the browser is expected to discard
 * the cookie. The value 0 means "until the browser is closed".
 */
ini_set('session.cookie_lifetime', 2000000);

You can adjust those settings to affect the session lifetime. Indeed, the "remember me" module uses the session.cookie_lifetime setting to apply its functionality.


How to get the list of fields available in the user entity

You can get user entity field definitions list by using the following code:

$user_field_definitions = \Drupal::service('entity_field.manager')
  ->getFieldDefinitions('user', 'user');
// List of user field definitions.
dump($user_field_definitions);


How to access a variable in the ready event within charts_google.js without hacking the chart module?

Consider looking at issues #1196712 and 1715638, which seem to be like variations of your request.


Add specific CSS class with Semantic Views

This is possible to accomplish by overriding the View's template. You would have to create a custom Views tpl file with logic for adding a custom class based on a field value. Unfortunately you can not do this by simply using Views UI.

How to achieve this:

Add your Boolean field to the View and "Exclude from Display". Keep the default formatter of the field.
Create a custom View template. Click on Theme: Information in *Advanced settings* of your View. You'll see template suggestion for overriding different parts of the View. Here you are looking to override the Style Output of your View.
Click on Style Output link and you'll see the default content of .tpl file. Copy the code and paste it in a file named *semanticviews-view-unformatted--machinenameofyourview.tpl.php*. The name of the file that you should use will be listed in step #2, right after the one that it highlighted in bold, so you'll be safer by just copying and using that. Save this file in your current theme's template folder.
Now go back to the Theme:Information dialog of your View and click "Rescan Template Files" - you'll see that your new template is now detected by the View as it will become highlighted in bold. Click OK - now you told the View to use your new template. Save the view.
Open your new template file and paste the code below in it. You can replace the content of new template with the code pasted below, or just find the section // ADDED and paste it in the right place. *Section //ADDED will define the logic for adding custom class when Boolean field is checked.*
Replace the field_field_boolean w/ field_field_yourfieldname. Note: double field_  is necessary here. Also, replace the name of the class to your desired class name.

.....

<?php
/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>
  <<?php print $group_element; ?><?php print drupal_attributes($group_attributes); ?>>
    <?php print $title; ?>
  </<?php print $group_element; ?>>
<?php endif; ?>
<?php if (!empty($list_element)): ?>
  <<?php print $list_element; ?><?php print drupal_attributes($list_attributes); ?>>
<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <?php if (!empty($row_element)): ?>

  <?php // ADDED CODE ?>
  <?php
        $custom_class = '';
        if (isset($view->result[$id]->field_field_boolean[0]['raw']['value']) && $view->result[$id]->field_field_boolean[0]['raw']['value'] == TRUE) {
            $custom_class = 'my-custom-class';
        }
        $row_attributes[$id]['class'] = $row_attributes[$id]['class'].' '.$custom_class;
    ?>
  <?php // END OF ADDED CODE ?>

  <<?php print $row_element; ?><?php print drupal_attributes($row_attributes[$id]); ?>>
  <?php endif; ?>
    <?php print $row; ?>
  <?php if (!empty($row_element)): ?>
  </<?php print $row_element; ?>>
  <?php endif; ?>
<?php endforeach; ?>
<?php if (!empty($list_element)): ?>
  </<?php print $list_element; ?>>
<?php endif; ?>

.....


I created a CheckoutPane plugin which worked well in order-information step as it can can include form fields so can use form-validate function to stop progress until cart manually corrected.
In theory the stock could change between order-information and review steps. The panel is automatically processed in review step but it is only a display string not a form so cannot enforce anything here.

It is possible to use  HOOK_form_FORM_ID_alter (mymodule_form_commerce_checkout_flow_multistep_default_alter) which is called on submit of review step - so can add a validate function and stop things

The Pane approach gives a better UI space for explaining things to user as HOOK.. can mostly only generate a validation error.


How to load the node to print the node title, etc?

$node = \Drupal\node\Entity\Node::load($id)
$node->getTitle();

or
$nodes = \Drupal\node\Entity\Node::loadMultiple(array $ids = NULL)


How to maintain a Drupal project on GitHub

Technically, this post on SO covers pushing/pulling from multiple git remotes. In your case, it sounds like you'd set up 2 remotes (git.drupal.org & github.com), pull/push from github.com as needed, then push to git.drupal.org when you're ready to publish updates.

As far as the politics, checkout this thread on g.d.o. It might contain some thoughts/insights from other people who are in the same situation you're in.


Dynamic menu item based on Views argument

I never used breadcrumbs and i am quite new to Drupal but i think breadcrumbs get their copy from the URL arguments  ( which is also where view is getting its arguments, well in most cases). Though the menu items get their copy from the taxo (if you use a taxonomy menu block) or whatever name you gave them in the menu section of the site admin.

Therefor the only solution i would see, is to create you owns menu template in which you can use function such as drupal_get_path_alias() to populate your menu.


How to merge two forms (with separate purposes) and have one submit?

Instead of using custom form you can add fields.
Go to
Administration » Configuration » People » Account settings

And In the manage fields tab u can add  fields you want.

You can check the commerce_auto_product_display module tar files which has used similar functionality of adding nodes to the already built form


How to convert image URLs in Drupal node's fields while rendering?

You can probably accomplish that with a custom filter involving a regular expression using either Flexfilter or Custom filter.


Language switcher shows me same node on switch

I try to solve it again and it's was Global Redirect module fault. Please use Redirect intead


Complex form - merge of two with single callback

When you submit a form, either by clicking a button or pressing enter, the first (by default) submit button is assumed clicked, that's why the value is always "Update".

When you submit a form, every enabled element of the form is submitted, so the #submit parameter doesn't do for you.

The complex_form_submit is not executed because you are building it using two forms with their own _submit. This way, the drupal_get_form() call doesn't link the complex form submit to the complex form.

ok, because of the reasons above, you can't proceed like that, but you still have several options:

option 1

I'm assuming that when you save, you're looking for the #value of some select/textfield/etc of your field_form, but when you save without changes, you use the #default_value of said elements for example.

If this is the case, can you consider the option to turn the save_without_change button from a submit to a reset button?

This way, the user will revert all changes to the form elements, then click on save, and you will only need one _submit callback that just save the #value.
You should still split field and partner forms like shown at the bottom of page anyway.

Drupal wont let you create reset buttons, but you can specify one like this:

$['reset'] = array( '#markup'=>'<button type="reset">Revert changes</button>');

if #markup doesn't work, use #prefix instead.

option 2

Split the field form into two forms.

The save form will be exactly like the field one, but with a button less.

The save without changes form instead, will only have the missing button, and will store the form parameters or default values you need into elements like:

$['#val1'] = $val1;

that wont be rendered, but that you can use inside its submit for its logic.

option 3

if you really want to keep the field form like that, the only workaround i can think of is adding a hidden checkbox to your field form, and adding an onclick event to one of the two save buttons.

The event will call a JavaScript function that change the checkbox value.

Later on, inside your field_form_submit, you can use the checkbox value to evaluate which button was clicked and execute the correct logic.

downside: JavaScript have to be enabled.
you still split partner and field forms.

split

The problem here is that the two "sub" forms don't really exist anymore, they are rendered as one, which you should be able to confirm inspecting the resulting html.

If you need that only one submit is sent, don't mix them up.

Use my_module_complex_form as page callback, fix arguments accordingly, and inside render each form with drupal_render():

function my_module_complex_form(.....)
{
  // ... some irrelevant code here ...

  $f1 = drupal_get_form('my_module_partner_form', $someParam);
  $f2 = drupal_get_form('my_module_fields_form', $someOtherParam);

  $page = drupal_render($f1);
  $page .= drupal_render($f2);

  return $page;
}


The GeshiFilter module may help you.

  At the time of this writing the GeSHi library supports highlighting for more than 130 programming languages and configuration syntaxes, including: ActionScript, Ada, Apache Log, AppleScript, ASM, ASP, Bash, C, ColdFusion, C++, QT, C#, CSS, D, Delphi, Diff, DOS, dot, Eiffel, Fortran, Groovy, Haskell, HTML, INI, Inno, Java, Javascript, LaTeX, Lisp, Lua, Motorola 68000 Assembler, Matlab, mIRC Scripting, MySQL, Objective C, OCaml, OpenOffice.org Basic, Oracle 8 SQL, Pascal, Perl, PHP, PL/SQL, Python, QBasic/QuickBASIC, Rails, Microsoft Registry, robots.txt, Ruby, SAS, Scheme, Smalltalk, Smarty, SQL, TCL, Text, Visual Basic, vb.net, VHDL, XML, X++.


Why is the recommended release of my module not proposed in Drupal updates?

Immediately after posting my question, I'd pushed a new 7.x-2.2 release, and it didn't change anything: all involved sites keeped reporting 7.x-2.0 as the most recent release.

But today I noticed that it suddenly changed (without any intervention in git nor in my module's page): now the sites correctly report 7.x-2.2 as the most recent release.

So I tend to think that the response to my question is merely: there is some variable latency in the way Drupal.org makes the information available for the admin/reports/updates/check page underlying mechanism to work.

Moreover it worth mention that also the git Age list now shows all release tags, while some of them were previously missing.


Is it possible to add fields definitions in entity?

When you create an entity using Drupal Console you'll find such a field as example already defined in baseFieldDefinitions(), which references the user entity:

$fields['user_id'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Authored by'))
  ->setDescription(t('The user ID of author of the {{ label }} entity.'))
  ->setRevisionable(TRUE)
  ->setSetting('target_type', 'user')
  ->setSetting('handler', 'default')
  ->setTranslatable(TRUE)
  ->setDisplayOptions('view', [
    'label' => 'hidden',
    'type' => 'author',
    'weight' => 0,
  ])
  ->setDisplayOptions('form', [
    'type' => 'entity_reference_autocomplete',
    'weight' => 5,
    'settings' => [
      'match_operator' => 'CONTAINS',
      'size' => '60',
      'autocomplete_type' => 'tags',
      'placeholder' => '',
    ],
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

You can define as target other entities:

  ->setSetting('target_type', 'my_other_entity')

BTW the two last two lines of the example make this base field configurable in UI. You can set this to FALSE if you don't want that anyone can change the configuration you've made in code.

You can customize this, for example if you want a dropdown select element:

  ->setDisplayOptions('form', [
    'type' => 'options_select',
    'weight' => 5,
    'settings' => [
    ],

To implement code to load the referenced entities extend the field widget OptionsSelectWidget, add a custom plugin id to the annotations my_options_select, which you can use for the type in the example above

    'type' => 'my_options_select',

and override the plugin methods to load the options. For simple cases use hook_options_list_alter, this hook is invoked by the widget base class method getOptions().


I backed-up my site and now my views are broken

It looks like it is looking for fields that do no longer exists?
Have you changed anything in your content types maybe?


Admin user can't manage fields on custom content type

I feel so stupid. But I'm leaving this answer so that the next person to have this same problem will save 3 days of development time:

The module that allows fields to be created on entities (nodes, user etc.) is creatively called "Field".

But, that doesn't mean you'll have a UI to create/edit them. There is another creatively named module called "Field UI". If this modules isn't installed AND enabled you won't have a user interface to edit your fields...


Access referenced entity in Rules using hook_entity_property_info

This works as-is. I actually had a typo in my code that took me a long time to catch. I'm leaving this up if anyone else has the same situation. The final code looked like this (cleaner):

function mymodule_entity_property_info_alter(&$info) {
  $properties = &$info['reply']['properties'];

  $properties['myentity'] = array(
    'label' => t("My Entity"),
    'description' => t("The entity this reply is associated with."),
    'type' => 'myentity',
    'required' => TRUE,
    'schema field' => 'entity_id',
  );
}


Error when trying to extend a db_select query

addField returns the alias of the field that's added, not the query object. You just need to break your code up a bit:

$query = db_select('z_revision', 't')
  ->fields('t', array('drupal_user_id'));

$query->addField('t', 'z', 'category');

$result = $query->extend('PagerDefault')
  ->extend('TableSort')
  ->orderByHeader($header)
  ->limit(30)
  ->execute();


call a modules function from preprocess_page

You are getting a taxonomy id. However, taxonomy_get_tree needs a vocabulary id as parameter, according to the documentation: https://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.module/function/taxonomy_get_tree/7.x . That's probably why you are getting an empty array.

In order to be able to call taxonomy_get_tree, you would need to get the vocabulary id first:

$term = taxonomy_term_load($tid);
$vid = $term->vid;
print_r(taxonomy_get_tree($vid));

(see this question for more details about getting the vid from a tid).


How to prevent access to a page but allow query

Simply check that your URL parameter exists and it's not empty before loading your view:

/**
 * Implements hook_views_pre_view().
 */
function MY_MODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'MY_VIEW_NAME') {
    // If your URL parameter doesn't exist or it's empty, deny access.
    if (!isset($_GET['name']) || empty($_GET['name'])) {
      drupal_access_denied();
      exit();
    }
  }
}

So, accessing:

http://example.com/cvstaff?name=user will work.

http://example.com/cvstaff will show an Access Denied page.


Why do I get this error when I try to use db_change_field()?

Check the documentation for hook_schema_alter(): db_change_field() is not supposed to be used there, instead change the $schema array to the required structure.

function mymodule_schema_alter(&$schema){
    if( isset($schema['field_data_field_document_title']) ){
        $schema['field_data_field_document_title']['fields']['field_data_field_document_title_value']['length'] = 500;
    }
}

However, if the module is already installed and has existing data (seems like this is the case), then a call to db_change_field() inside a hook_update_N() implementation is necessary to update the schema.

function mymodule_update_7100() {
    $table = drupal_get_schema('field_data_field_document_title', TRUE);
    db_change_field('field_data_field_document_title', 'field_document_title_value', 'field_document_title_value', $table['fields']['field_document_title_value']);
}

Note (if there is existing data): both these functions need to be included in mymodule.install, as the second function depends on the first: the change of field length made in mymodule_schema_alter() will be included in the table schema returned by drupal_get_schema().


Use hook_cron to send daily mail but I get 4~5 the same mail every day?

D7, I struggled a lot, this is what i did, works perfect, following modules are required: Job shcheduler, Rules, and optionally Rules switch user, i use core cron; make a custom module 'MYMODULE' and place this code:

   /**
   * Implements hook_cron_job_scheduler_info().
   *
   * Do not forget to run job_scheduler_rebuild_all() on any changes here,
   * see https://drupal.org/comment/8406919#comment-8406919
   */
  // * Implements hook_cron()
  function MYMODULE_cron_job_scheduler_info() {
    $schedulers = array();
  //add as many scheduled jobs as needed.
  //$schedulers['daily_email_6_am'] = array(...);
    $schedulers['daily_email_7_am'] = array(
      'worker callback' => 'send_emails_action_7_am',
      'jobs' => array(
        array(
          'type' => 'notification',
          'id' => 1,
          'crontab' => '0 7 * * 1-6', // 7am, mon-sat
          //'crontab' => '0 * * * *', // once a day, midnigth
          //'crontab' => '*/1 * * * *', // once every minute, dev settings
          'periodic' => TRUE
        ),
      )
    );
    return $schedulers;
  }
  function send_emails_action_7_am() {
    // Do stuff.
    rules_invoke_component('rules_send_emails_component_7_am');
}

now you have a cron based scheduled job at 7 am from monday to saturday that executes a rule-component machine name: 'send_emails_component_7_am', be carefull, function calls: rules_MACHINENAME of component,  built rule component to send your emails, i  usually i built my emails with views rules module and have a great control to built email-body-value. see this answer, and this one also could be many emails, benefits of using views-rules as you can loop by views all users and filter them as needed and inject to rules whatever you imagine. emails are not 'duplicated', only 1 mail per user.

cron run as anonymous user, so, only if you have some content_access restrictions your emails won't be sent, here comes the benefit of 'Rules switch user', do pay attention with this module settings as this img suggest, i hope this helps someone.


You could try drupal_get_path_alias('node/12345') (see docs) and then exchange the domain name.


Allows authenticated users to tag content

Check for field permission. If authenticated user has permission to add/edit the node then user should be able to tag it. You Just need to verify your permission settings.


Why does Drupal need list (integer, float AND text) and what is the difference?

Occasionally you want to access a dropdown with Jquery - in this case it can be useful to have keys which are more than just integers.

Nothing I ever did, but you could use a dropdown to apply different classes to an element:

style-red|Red Layout
style-blue|Blue Layout

The value is the human readable label and the key is the class to switch around with jQuery. If you had used '1|Red Layout' and '2|Blue Layout' you need to tell JQuery that is has to translate key 1 into class style-red and key 2 into style-blue before applying them. So whenever you would add a new key|value pair you would not only need to edit your css but also your jQuery code, while using text keys you only need to edit the css file.

It is not a real world example, but you get the point.

For the float it is similar. Imagine you have a list with prices each with a human readable label plus a float you can instantly use for calculation in jQuery.


Automatic creation of Product Display for Drupal commerce?

If your products and products display has a 1 to 1 relationship, you could use views to display your products instead. You also could do it with rules or custom code. Rules allow to create entities so it's all a matter of filling out data on the product display node with the product date.

The idea behind product displays is that you want to display multiple variants or related products. An example would be to display the variations in size, color, material etc and from the same node be able to select the product I want.

IMO you should go for Commerce and not ubercart. It's far more flexible and powerful. It's also better integrated with Drupal 7 features and the main modules in Drupal like, Views, entity, rules, and is doesn't have the history of legacy code that needs to be supported like Ubercart does.


How to find out allowed memory for a specific Drupal page

Check out the performance module (formerly part of Devel):

This module provides performance statistics logging for a site, such as page generation times, and memory usage, for each page load.
This module is useful for developers and site administrators alike to identify pages that are slow to generate or use excessive memory.

emphasis mine.


A multi-level taxonomy could accomplish this for you. Something like:

Music

Rock
Classical
Jazz

Politics
News

National
International
Sport

Create this, and then add a field for it on your single content type. Then use the Taxonomy Menu module to create a menu from your taxonomy, and the Menu Block module to place both a top level navigation, and the sidebar navigation. You can adjust what level the menu starts at for this.

Your taxonomy menu will link to each taxonomy term listing page, which is a default view. Further, if you setup URL aliases for your taxonomy, and then rebuild links, each page will have a meaningful URL (home/news/international). You can take it a step further by adding URL aliases for your content type as well, and use the taxonomy term path in that so you end up with (home/news/international/title-of-article).


You can use the Context module to conditionally show blocks in certain regions.

So, in your case, you can create a context that is activated on the /cart and /cart/checkout paths, and add the minipanels blocks that you want to the header and footer.


I found the checkboxes. I was printing the $form variable in the wrong hook function. I needed to do my modifications to the form in hook_form_alter.

I ended up using something like this:

unset($form['submitted']['outer_fieldset']['fieldset_1']['checkboxes']['#options'][$option]);


I think you are on the right track, but I think doing this as a true multi-site is overkill, and potentially the wrong idea.

Ideally, you want your desktop site and mobile site to share the same content.  If you are not going to go down the route of just using mobile stylesheets, then I suggest using Domain Access to create the mobile site.

You can use this module to set up your mobile domain, and then create your content accessibility rules for what is visible where.  When used in combination with Panels, you have great flexibility.

Mobile Tools let you choose your theme for a user and also shows up in panel selection rules, and domain tools lets you show/hide content for a particular user.

Note the issue log for Mobile Tools, though.  I found a bug with how the ctools selection rules work, and have a patch on the issue that hasbn't been committed or commented on.


You have to work very hard at caching. Particularly if the page is static, then make sure you caching on in  Home → Administer → Site configuration.

If this is not enough investigate 'boost cache' or alternative caching systems. This can takes some work to setup/prime and tune.

Caching most effective way of getting drupal-6 to be performant. What queries drupal makes can't really be beaten as you can't change the logic of Drupal. If the queries aren't being made at all because of caching they won't be slow.

Second thing. You could also make sure that MySQL is using INNODB tables and that you have set innodb_buffer_pool_size to as high a level as you can given memory limitations. Here is a MySQL tuning script that might provides some hints http://www.day32.com/MySQL/.

Third thing is to make sure that only the modules that are in use are installed on the system. Every module has an overhead.


I expect you could arrive at this by having a hyerachrical vocabulary. Use the drag handles indent terms as below.
A
- term 1
- term 2

B
- term 3
- term 4

If you needed to list terms in a view, you could use the 'terms with depth' option.
No idea why someone has downvoted your question. It seems perfectly reasonable.


Automatically backing up uploaded files?

I have not been in the situation before, if I were in your shoes I would take a look at the CDN module.

In File Conveyor mode (ie, a push model), it will automagically copy files up to your CDN of choice.  A side effect of this is the fact that the files will now live in two places.  You can go with one of the commercial CDNs, or you can set up your own with another server.


If I understand correctly your requirement, then you want to provide a functionality to user to upload images or video and then save the images or video respectively.

I have already implemented similar functionality in one of my recent project with following concept:

Create a new content type as upload
Add a list (select) field Filter type with options image and video
Add two fields  image as 'image' field type
Installed Media module and add video field as 'Media file selector'
Installed Conditional field module and set condition that image field be only visible if user select 'image' as Filter type options and video field be only visible if user select 'video' as Filter type options
Set the permission to user to create content of upload content type.
Now Create two views to display image and video separately.

I hope that it will solve your problem.


How to add markup inside a form radio button div

I was able to follow @Alfred's advice above and used the #theme element to make this work.
I added this to my module theme hook:

'my_module_is_member_radios' => array(
  'render element' => 'form',
  'template' => 'templates/my_module_is_member_radios',
),

and in the template used this:

$armedForcedInfo = "some markup";
$civilianInfo = "some more markup"

$variables['form'][0]['#suffix'] = $armedForcedInfo;
$variables['form'][1]['#suffix'] = $civilianInfo;
print drupal_render($variables['form'][0]);
print drupal_render($variables['form'][1]);


How to access/print fields in non-Drupal php files?

You could try it with drupal_bootstrap, but it is not tested.

define('DRUPAL_ROOT', '/path/to/drupal');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$title = drupal_get_title();
echo $title;


If you are using the services module and the user login endpoint, when you perform the login trough your app you should receive:

sessid
session_name
token
user

(This can be investigated further checking the source code here.)

To make all subsequent calls keeping alive the session you just opened (i.e. as a registered user), you need to send the cookie session value and the csrf token value.

For example:

$ curl http://example.com/app/v1/endpoint --header "Content-type: application/json" --header "Accept: application/json" --header "X-CSRF-Token: X-_xz1fu5eSyHeBPqExAPDg4CdZKlHdiW6Lr7SP3N3Y" --header "Cookie: SESS40c98733719ab6b30c22a4545524a6cc=VWcWeGkTF7xgeMyoQwx5CGPHzIhttUUwmcwq_usiimk"

In theory you shouldn't need to make an extra call just to get the CSRF token, because it is already returned in the first response.


How can I pass an empty case subject from Webform CiviCRM integration to CiviCRM?

In the webform, give the field the default value that you want to use, and then change the field widget to 'Hidden' so that the field is not exposed to the user on the form. The default value will then be submitted, and subsequently modified/overridden by your hook.


Create custom links for private message in OG group

There is a module for private message in group but it is sandbox module and for Drupal 6 only. You can customize it for Drupal 7

Just check this Sandbox

And refer this discussion also, it has nice roadmap regarding implementation of entire module. http://drupal.org/node/612664


Adding a full screen background image to Drupal 7 / Bartik theme

Are you actually trying to use fullscreenr because you want a full screen background image that re-sizes with the browser? Or do you just want to have a background image?

If you're just looking to use a background image, you don't need jQuery. You can just edit the CSS. Though, if you're changing a builtin theme like Bartik, you should actually create a subtheme instead of editing the builtin theme's files.

If you actually need fullscreenr then you need to add the javascript files for the plugin and your file that calls the fullscreenr method to your theme's .info file (again, you should not edit the builtin theme's files, you should create your own subtheme). In the example below, I'm just editing Bartik's files (don't do this, use a subtheme). You should add the following to the theme's .info file

stylesheets[all][] = jquery/fullscreenr/css/fsbg-style.css
scripts[] = jquery/fullscreenr/js/jquery.fullscreenr.js
scripts[] = js/fullscreenbg.js

In this example, I added a jquery folder to the theme's folder and put the fullscreenr folder containing the plug-in into the jquery folder. I also slightly renamed the style.css file that comes with the plugin (in addition to deleting all the extra option stuff from that file). I put my code for actually calling the plug-in into the js/fullscreenbg.js file. The code looks like (details on why it's wrapped like that in the Drupal docs for changes from D6 to D7):

(function ($) {
  // You need to specify the size of your background image here (could be done automatically by some PHP code)
  var FullscreenrOptions = { width: 1024, height: 768, bgID: '#bgimg' };
  // This will activate the full screen background!
  jQuery.fn.fullscreenr(FullscreenrOptions);
}(jQuery));

I think this was the part you were really having trouble with.

There are some other minor things you need to do to set up the fullscreenr plug-in. I highly suggest getting it to work on a very basic html page outside of Drupal before putting it into a Drupal theme so you know you're at least using the plug-in correctly. Also, keep in mind that Bartik has a lot of other stuff going on with background colors and such on various parts of the page, so just adding the background image without editing the theme's CSS is not going to appear to make any difference.


Programatically change autocomplete views exposed filter by a select list

It won't work because validateExposed function from core/modules/user/src/Plugin/views/filter/Name.php expect the values to be something like :

array:1 [▼
   0 => array:1 [▼
     "target_id" => "1"
   ]
 ]

So if you just modified the autocomplete to select you will send the value of uid like 1 for example:

Suggested solution

Add Validation function before validateExposed and refactor the value of input uid.
Here is code snippet:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // If not the view we are looking, move on
  if (stripos($form['#id'], 'views-exposed-form-my-form')) {
    return FALSE;
  }
  //- query
  $query = \Drupal::entityQuery('user');
  /**
   * @TODO: Add your conditions.
   */
  $options = [];
  //- get user ids
  $entity_ids = $query->execute();
  //- Get Users List
  $users_list = \Drupal::entityTypeManager()
    ->getStorage('user')
    ->loadMultiple($entity_ids);
 //- Prepare the list options.
  foreach ($users_list as $user) {
    $options[$user->id()] = $user->getAccountName();
  }
  if (isset($form['uid'])) {
    //- alter the Uid field.
    $form['uid'] = [
      '#type'         => 'select',
      '#options'      => $options,
      '#empty_option' => t('-- Select User --'),
      '#multiple'     => FALSE,
    ];
    unset($form['uid']['#size']);
    //- Add Validate in the beginning To be before validateExposed
    array_unshift($form['#validate'], 'validateUserExposedFilter');
  }
}

/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 */
function validateUserExposedFilter(&$form, FormStateInterface $form_state) {
//- Get the input value
  $input = $form_state->getValue('uid');
  //- Prepare value to be like the expected
  if ($input) {
    $value = [
      0 => [
        "target_id" => $input,
      ],
    ];
    //- Set the new value
    $form['uid']['#value'] = $value;
    //- Update the form state
    $form_state->setValue('uid', $value);
  }
}


How to insert line breaks in views global custom text field?

With HTML not allowed, you don't allow line breaks.  You would need a <br /> element to render a line break, otherwise it will be one big paragraph
If you have it set up the way you want, and all you want to do is add the /n to the output of a field:

Add a Global Custom Text field (make sure it is below the field you want to add the /n to).
Insert the token under Replacement Patterns for the applicable field.
In the text box, add the /n after the token.


Suggestions for Adding Documentation to a Drupal Application

Interesting question, I've been asking myself about the same thing. Read on for details ...

From your last phrase, I get the impression that you don't seem to like the "Drupal Help documentation", or that for some reason it doesn't fit your needs. I'm assuming that your talking about the Advanced Help module. If not please add an hyperlink to what exactly you mean. I've been considering actually starting to USE the Advanced Help module, e.g. in the modules I maintain, such as chart, charts and visitors. E.g. because of it's integration with Drupal searches in a site, and because it's basically HTML formatted content, which should be straightforward to use for building actual tutorial contents.

I researched a bit within some of the typical modules (in core or contrib) that do come already with such 'Advance Help' tutorial pages (like 'trigger' back in D6 I believe). It took me a while to figure out what exactly to go look for where (= "what does this 'advance help' module actually add to such module that uses it?"). After I got that, I wondered "how do they do that, or what am I supposed to do in my own module to get something similar, and what kind of options/features do I have?". I didn't quite get it at first, so then I started to just scan the code of those contribute modules (using a string that I saw in the help docu from that module). Then I figured out, as often is the case in Drupal, it is a matter of knowing how to call which hook in the advanced_help module.

Next step I started to look around for "Advanced Help" about the "Advanced Help" module (makes sense I think, no?). Too bad, couldn't find any info about "how" to get this magic to work. Now 6 to 12 months later, and rather by accident, I discovered '1' (only!) community documentation page about the advanced help documentation. But you know what: on the project home page there is no (repeat: no) Read documentation link. After I discovered it, I did 2 things:

a) create issue #2445025 . More then 1 day later now ('only?' one might say ...), no reaction at all from any of it's maintainers. Last commit to this project is from late 2013. It makes me wonder about the health of this module (sorry). Haven't checked the health of the issue queue yet ...

b) While filing that issue, I was trying to understand the available docu in that (1) community docu page. I perceived it as fairly hard to read / understand, partially because of it's poor formatting. So I did as described in my PS in that issue. There is still lots of docu about that advanced help to be added. At least (I think) for a target audience like "technical writers" who might not have the skills to go figure out how to use the available hooks (something for drupal developers, but not for site builders or something similar). Yes producing docu might be boring for the experts who wrote a module (or it's most experienced users), but it is really important for a module to be successful, i.e. lots of reported installs and as few support / docu requests as possible
OK, enough about the 'help' module (wrong name! That's another module not at all related to it), I really do want to give it a try soon to get started with it in my own modules I maintain ... How about a completely different approach (which might only fit for some modules), which is "eat your own dogfood". Which is what we did in the forena module. It's a module for reporting (and charting) in Drupal, whereas it uses XHTML to actually 'develop' your custom report (report writer if you want). Here are some sample "help" pages for that module, shipped as part of the module, which you can see at work by just following the links to this demo sample:

Forena Help: if you check it out, make sure to also experiment with that "Refine Table of contents" pull down menu near the top, and see what happens if you change the (default) value for "show chapter extract" (from no to yes).
FrxTitle: That's just one (out of many) of the links you can follow on the page in the previous bullet. After visiting that link, scroll to the top of that page where it says "Including". That's (obviously) the TOC for the subitems on the selected page. With some CSS (not shown in this sample), you could eg move that "including" to the upper right corner (to make it look more wiki style).

Voilà (oeps), here you have 2 alternatives to consider. But you know what, while writing this answer I came to realise this: for somebody who is NOT looking for a module that forena is originally designed for (= reporting about all sorts of databases), forena might ALSO be consider as a possible alternative for the "advanced help" module. To proof my point: the entire set of "help pages" I described in the previous bullet, is just a matter of some (what is called) 'FRX' files. Go checkout the forena GIT repository to go look at them to see the "source" files (in FRX format) of those tutorial pages.

What was the original question again? Did I answered it?

PS 1: For anybody wondering now "how did he do that forena tutorial?", please contact me (or 'hire us and we'll teach you') ... or just read that tutorial ...

PS 2: I actually contributed most of the work for these forena tutorials as included in the most recent version 7.x-4.x. It is a complete rework of the preio release version, in which I added tons of extra content (features that were undocumented), and introduced this new navigation links, etc. When I first shared it with the module owner (David), he asked me something like ... "How did you do that! Can't believe I never thought of that myself".


As far as I can tell this is a problem, the menu items aren't connected so the only thing that links them is through the node they are connected to and their translation sets.

Another possibility, but I never used it like this, is to make the menu items translatable and there's a module inside i18n that redirect links to the right language.


How to reverse order of pulldown Views Exposed Filter showing taxonomy terms reference field

You should give Entity Reference a go. You don't need to use the autocomplete widget. The standard dropdown list is sufficent. Just create a entitiy reference, type "taxonomy term", select your vocabulary, set to sort by "A property of the base table of the entity" and select "name" and "descending". This should work...

If you need to add new terms on node creation, you could try Entity Connect module. The module will allow you to dynamically create and edit some entity types (e.g. taxonomy terms) which should be referenced into an Entity reference field.


How to specify PHP block visibility settings for content types AND loads of urls?

This sounds like the perfect use case for something like the Context module. Contexts are triggered and become active, and would save you from writing tons of PHP to get the matching to work in an unlimited number of use cases and edge cases.

  Think of conditions as a set of rules that are checked during page
  load to see what context is active. Any reactions that are associated
  with active contexts are then fired.

Related modules


First, an explanation of why the changed timestamp gets updated. Actions can declare the attribute

'behavior' => array('changes_property')

in their hook_action_info entry. This attribute causes VBO to automatically call Entity API's entity_save function after the action has been called. This function ends up calling node_save, which updates the changed timestamp.

To avoid this behavior, simply create your own custom action by implementing hook_action_info in a custom module and follow the action_example of the Examples module. Make sure that your hook_action_info omits the attribute

'behavior' => array('changes_property')

Your action function will need to save the node or any other data by manipulating the database directly, or by making sure that you're using a function that doesn't trigger a node_save call.


jQuery ui embedded calendar on a drupal 7 form

I have already implemented my approach on a custom module and it's working fine! Here's my code:

function calendar_block_info() {
    $blocks['embedded_calendar'] = array(
    'info' => t('Calendar block'),
    'cache' => DRUPAL_NO_CACHE,
  );

  return $blocks;
}

function calendar_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'embedded_calendar':

      //JS code based on: http://stackoverflow.com/questions/5578259/jquery-ui-datepicker-how-to-add-clickable-events-on-particular-dates

      drupal_add_css(drupal_get_path('module', 'calendar') .'/calendar.css');
      drupal_add_library('system','ui.datepicker');
      drupal_add_js('jQuery(document).ready(function() {

                      var events = [
                        { Title: "Five K for charity", Date: new Date("02/01/2013"), class: "red" },
                        { Title: "Dinner", Date: new Date("02/02/2013"), class: "green" },
                        { Title: "Meeting with manager", Date: new Date("03/01/2013"), class: "blue" }
                      ];

                      jQuery( "#embedded_calendar" ).datepicker({
                                                   numberOfMonths: 2,
                                                   regional: "es",
                                                   beforeShowDay: function(date) {
                                                      var result = [true, "", null];
                                                      var matching = jQuery.grep(events, function(event) {
                                                          return event.Date.valueOf() === date.valueOf();
                                                      });

                                                      if (matching.length) {
                                                          result = [true, matching[0].class, null];
                                                      }
                                                      return result;
                                                   },
                                                   });
                    });', 'inline');

      $block = array(
        'subject' => t('&nbsp;'),
        'content' => '

',
      );

      break;
  }
  return $block;
}


Cannot get rules component to fire on Commerce Completing the checkout process

It's possible the user doesn't have access to execute the rules component. You can check the permission in admin user permissions or on the rule component edit page.

Keep in mind the rules component will need to be attached to a reaction rule to fire on the checkout complete event.

Other than that, if the component can process the passed $commerce_order parameter (passed to checkout complete), then it should be ok.


Javascript is not loading in Zen custom theme

The script.js started working after I cleared all caches.

If you're having this problem and followed Drupal's official documentation then login to your Drupal site as admin and In Performance section click clear all caches

navigate to: Home >> Administration >> Configuration >> Development


How can I limit submissions within a period of time?

You need to identify a unique identifier.

It can't be the UID as schlicki mentioned in the comment.

You can add an email field. But if you don't add validation to this, people can just make up something up.

If you're going to add email + validation, would an account on the site be worth it?

Another option is a combination that identifier the browser as unique. You can look into https://github.com/Valve/fingerprintjs2. You can take all those properties and hash all of those together. That should give you a good identifier.

THIS CAN BE FOOLED. BY DEFAULT THEY WILL BE ABLE TO SUBMIT A FORM PER EACH BROWSER ON EACH DEVICE THEY HAVE.

If it doesn't have to be super strict, it would work.

This link, https://panopticlick.eff.org/ may have more information on what you're exploiting.

What I would do,

Generate a hash based on all the properties from fingerprintjs2.
Take that hash and add it to a hidden field
On submit, you can check the value

Validate that it's not empty.
Check the value in the database (you'll need a table for this)
If it is on your table,

Check when was the last time this was submitted
Apply your rules.

If it can be submitted again, perfect.
If it can't be submitted again, show a message. You can show how much time they need to wait for the next submission.

If it's not on your table,

Add the value to the database
Allow the submission through

That's the logic that you would have to apply.


Send out welcome e-mail in users selected language

This is not a answer but can't fit this to a comment.
From what I see in the source of user.module, the function that fires drupal_mail favors user's preferred language.

3495 function _user_mail_notify($op, $account, $language = NULL) {
3496 // By default, we always notify except for canceled and blocked.
3497 $default_notify = ($op != 'status_canceled' && $op != 'status_blocked');
3498 $notify = variable_get('user_mail_' . $op . '_notify', $default_notify);
3499 if ($notify) {
3500 $params['account'] = $account;
3501 $language = $language ? $language : user_preferred_language($account);
3502 $mail = drupal_mail('user', $op, $account->mail, $language, $params);
3503 if ($op == 'register_pending_approval') {
3504 // If a user registered requiring admin approval, notify the admin, too.
3505 // We use the site default language for this.
3506 drupal_mail('user', 'register_pending_approval_admin', variable_get('site_mail', ini_get('sendmail_from')), language_default(), $params);
3507 }
3508 }
3509 return empty($mail) ? NULL : $mail['result'];
3510 }

Note the $language param defaults to NULL and, in line 3501, if the param is NULL, it will get the user's preferred language. Moreover, none of the function calls has the third argument, so in all cases, user_preferred_language() should be used to determine the language.

So,if you have correctly translated the message, with correct t() function's syntax, message should be translated.

However, rather than translating the entire message, I'd suggest a dirty hook_mail_alter() hack to translate line by line with t() or completely different messages on 2 languages.


Just use CSS to alter the size of your H2 elements on the home page.

Replace in this code XX by the desired font-size, and it will apply to all h2 elements but only on the home page (body.front)

body.front h2 {
  font-size:XXpx;
}

Otherwise, learn CSS to understand how to select your specific elements.


I have migrated other CMS's to Drupal and had experience moving user accounts.  Drupal's password algorithm is extremely good.

The salt you are referring to in the settings.php is not used for passwords. The drupal_hash_salt salt is used for generation of things like cookies.  Hence why it says you must keep it the same across all web servers if you are in a load balanced setup.

Generation of passwords uses the SHA512 algorithm with randomly generated salts using openssl php libraries (not mt_rand or other weak random number generators).

If you want to learn more about password generation you can start here reading the API documentation for Drupal

You see that in the function to generate it calls a "private" function to generate a new password salt (_password_generate_salt()). Which in turn calls a lot of other private, custom Drupal functions (it is a long rabit hole).

So in general the password scheme used for Drupal is extremely deep and nested, it does not use PHP functions considered to be "weak".


How do I get the modified field value of a VIEW

I am not exactly sure of what your are looking for. When I need to change the output of a field I usually change the $view->result for the field in hook_views_post_execute.


How to reduce the time needed to export a view with 50k rows into a CSV file?

As an alternative to using Views (and Views data export), you may want to give it a try using the Forena module (disclosure: I'm a co-mainter). If you do, I doubt it'd take 20 mins to complete such export (my bet is somewhere around 30 to 60 secs, at max ...).

To perform such export using Forena, just create a "report" to select (and sort, etc) the 50K records you want to export using the Forena module. And specify what kind of hyperlinks you want to make available for performing such "export". These hyperlinks correspond to various supported "formats", such as: CSV, PDF, XLS, XML, DOC, HTML ... (the "report designer" selects what the allowed/enabled export formats for a report are).

To get an idea of how that would look like, visit the Customized Simple Table of States. Notice the links in it, such as "CSV" (upper right), which in this case would "export" the results in a CSV file.


Add Profile 2 -> Field Colleciton -> Taxonomoy into Facet (Search API)

I found out the solution from Search API Drupal Recruiter  here

In short, I have to click "+Add index" to make a new index based Profile

For example, Please take a look at the picture below to understand how to solve this issue.


Migrate users datas to the profile module

I post an answer to my question. Feel free to comment or edit my answer in order to improve.

I’ve migrated users datas from a csv file. If you need help to do this, you can follow instructions in this questions :
Import users into Drupal with data from a CSV file

Now, i import the profile data in a migration process that maintains the relationships between source and destination identifiers in map table.

So the profile is related to the correct uid.

More information on this here (Process plugin: migration_lookup):

https://www.drupal.org/docs/8/api/migrate-api/migrate-process-plugins/process-plugin-migration_lookup-formerly-migration

The configuration file looks like this. You have to adapt some values as :

uid:
     source: xxx

This takes the value of the xxx property in the source data, and looks it up in the map table associated with the users migration, returning the resulting user ID and assigning it to the destination uid property.

You have to adapt the fields of course and the key to your needs.

id: profile_migrate
migration_tags: null
migration_group: null
label: 'Profile migration from CSV'
source:
  plugin: csv
  path: /path/to/csv/users.csv
  header_row_count: 1
  keys:
    - weblogin
destination:
  plugin: entity:profile
process:
   type:
    plugin: default_value
    default_value: 'profile'
   uid:
     plugin: migration_lookup
     no_stub: true
     # previous user migration
     migration: user_migrate
     # property in the source data
     source: weblogin
   field_profile_last_name:
     plugin: get
     source: nom_salarie
   field_profile_first_name: prenom_salarie
   field_profile_address: adresse1
   field_date_de_naissance: date_naissance
   field_code: code
   field_numero_societe: numsoc
   field_profile_function: qualification
migration_dependencies:
  required: {  }
  optional: {  }


How to change title of profile-profile2_machine_name only, but not profile-profile2_machine_name/%user

I think this module will do what you need. I have used it on a few projects. It works. And I think it supports wildcards. Also it says it supports tokens.


How to set the default value of an entity reference to an entityform type

I've found a way, but it might not be the best way. I remove all the other options from the select list so the one I want is the only one left. (What is strange, is that in some content types I can set a default value for the entity reference and in some I cannot, but this worked anyway)

if ($form_id == 'inschrijvingsformulier_testdag_p_node_form'){

    $form['field_inschrijvingsformulier_tes']['und']['#options']=array(1 => 'inschrijvingsformulier testdag',);
    $form['field_inschrijvingsformulier_tes']["#attributes"]['class'][] = 'element-invisible';
}


Why is $form_state always empty, even when my form-building-function is called after validation?

You've just got the signature for the form function slightly wrong, it should be:

 function form_identification($form, &$form_state) {

The first arg that's passed to your form function by the form builder is the $form, which for a new form is pretty much always an empty array.


How to prevent subsequent Rules to be executed if a previous rule is executed?

As far as your question title says "Execution Order", rules have weight which you can set in the settings tab which you will find on rule manage page.

  Order rules that react on the same event. Rules with a higher weight
  are evaluated after rules with less weight.

As far as your query concern, it seems you need to pick up he right condition while setting up those three rules,you can also use php in the condition if your condition is quite specific.The rules automatically execute their actions based on if condition get satisfied.


Redirect module does not allow redirection for existing node's path alias

I just ran into this also.  You may want to look at https://www.drupal.org/project/url_redirect to see if it fits your needs.


Solution

$form["#attributes"] = ["enctype" => "multipart/form-data"];

$form["base"]["fields"] += [
   "image_section" => [
    "#type" => "file",
    "#title" => "Image",
   ]
];

I solved my problem, as I only reloaded one part of the form, the form generator did not know that there was a file element, so it did not add "multipart enctype / form-data" to the form.

I hope this will help someone in the same situation as me in the future.


View with contextual filter using a taxonomy reference from a node

Views are complicated, so pardon me if i don't have this entirely right in the first go.

So as I understand things, you have one node that references a taxonomy term representing a product type, and you need to get a view on this node page to show other nodes (possibly of a different content type) that reference this same taxonomy term (possibly along with others). If that is correct, you should be able to do this with two relationships and a contextual filter. Both are found under the advanced settings portion of the view edit pane.

The first relationship you want to add is 'Entity Reference: Referenced Entity - A bridge to the Taxonomy term entity that is referenced via field_your_taxonomy_field'. This gets us from your 'result' nodes to the term you want to filter on.

The second relationship to add is 'Entity Reference: Referencing entity - A bridge to the Content entity that is referencing Taxonomy term via field_your_taxonomy_field_on_the_entity_we_are_viewing_the_view_from'. You set it up to use the first relationship as its relationship.

Last, you set up a contextual filter on 'Content: Nid' using the second relationship.

Edit
Since you are inside a block, you will also want to tell the view how to get the context (node ID) from the URL. Under the 'WHEN THE FILTER VALUE IS NOT AVAILABLE' you will want to select 'Provide default value' and in the resulting dropdown, select 'Raw value from URL'. Path component 1 should be correct. Save and update the view.
End Edit

To test this, pick the NID of a node where you might be viewing the view and put the NID in the 'Preview with contextual filters' box and click update preview. Did you see what you wanted to see? If so, great!


How to get views field data in defineOptions() method of custom filter?

You can access with:

$this->options['value']

Read more about this in Building Views Query Plugins for Drupal 8, Part 3


Here is your issue, your can't return twice in a function.

function mymodule_custom_page(){
  return theme('mymodule_template');
  return drupal_get_form('mymodule_form');
}

What you need to do is just the first line,  return theme('mymodule_template'); You also need to change your form function parameters to &$form, &$form_state.

Then, in your custompage.tpl.php, you do the drupal_get_form('mymodule_form');

Result:

/*
* Implements hook_menu
*/

function mymodule_menu() {
  $items = array();
  $items['foo/my_custom_form'] = array(
    'title' => 'My custom form',
    'page callback' => 'mymodule_custom_page',
    'access callback' => TRUE, // Everyone has access.
  );
  return $items;
}

function mymodule_custom_page(){
  return theme('mymodule_template');
}

/*
* Implements Hook_theme
*/

function mymodule_theme() {
  return array(
    'mymodule_template' => array(
      'template' => 'custompage', // template file called custompage.tpl.php
      'arguments' => array(),
    ),
  );
}

function mymodule_form(&$form, &$form_state){
  //my form in here
}

And in custompage.tpl.php:

print drupal_get_form('mymodule_form');


Migrate existing content types to MongoDB

Sure - you want to use the Migrate module to map your fields from a datasource (ex. CSV file) into your new MongoDB. Moshe has a post on this, more related to performance of his method for Amazon RDS but there is an example module that extends the Migrate API to pull the data from a CSV file into his MongoDB database. The relevant include file is here (maybe a little to long to include on stackoverflow?).

To get your data out of the content-type into a csv dump, I would recommend using Views Data Export.


There are plenty of modules are available for managing inventory and orders. Like Ubercart, Commerce.

But according to your requirement it seems that you want a partial payment system.

The default modules available in drupal community will not be able to provide you such kind of feature.

My Suggestion is to create it completely using your custom module and manage the complete order and partial payment process system.

Hope this will help you.


Using Node Limit, Show Role How Many Nodes They Can Still Add

I checked the node_limit module and you need to create an api to be able to get the remaining limit for a particular role or user.

The number of limit and limit id are stored on node_limit table.
Your limit id and role id are stored on node_limit_role table.

What you need to do next is count the number of nodes the role or user has created.

Now you need to alter the user profile to print the remaining limit. See the api that you can use here.


How to find which content type is using which context?

Here are some module suggestions that may help get you closer to find the exact answer to your question:

Context Inspector block provided by the Devel module

If you use the Devel module you'll have a "Context Inspector" block. You can place that block in a region on a page and then see the current contexts output via Krumho.
Devel Catcher module

To enhance your "debugging" experience (hm, hm ...), there is also the Devel Catcher module, which has Devel as a module dependency.

Here is an excerpt from its project page (why you may want to consider this module):

  ... aggregates or "catches" all development debug info into one easy to access place.

  Similar in style to Firebug or Chrome's Inspector. Devel Catcher intercepts common debug info into a tabbed interface as opposed to having to assign debug blocks to a region or dumping the output at the end of your HTML document.

  Currently Devel Catcher can catch the query log from the Devel module, node access rules from the Devel Node Access module and the context inspector block from the Context UI module.

So by using (repeating) this approach for a page of each of your content types, you might be able to find out which content type is using which context, no?


How can I detect when a node is changed from 'Published' to 'Unpublished'?

Nevermind. After reading through the issue linked above (especially comment #38), I found that the $node object (any entity, actually) stores the 'original' cached copy in $entity->original.

So, I wanted to detect whether a node changed from 'status = 1' to 'status = 0' (this happens when the node is unpublished), and the following code does this:

<?php
function custom_node_update($node) {
  if ($node->type == 'article') {
    // Act on the unpublishing of an article.
    if ($node->original->status == 1 && $node->status == 0) {
      // Do something here.
    }
    // Act on the publishing of an article.
    if ($node->original->status == 0 && $node->status == 1) {
      // Do something here.
    }
  }
}
?>


Looks like you have wrongly configured 403 page, in order to change it back, you can override it by adding following on your settings.php

 $conf['site_403'] = '';


Is there a way to avoid implementing a logic in the view template?

Templates are for displaying content, not building it, so you're right to want to avoid this.

Drupal allows you to preprocess any theme function to add variables. I guess in your case it would be something like

function MYTHEME_preprocess_views_view_grid(&$vars) {
  if ($vars['view']->name == 'some_view') {
    $vars['foo'] = markup_building_function();
  }
}

Then back in the template file you can output that var like so:

<?php echo $foo; ?>


If you use the Image URL Module module you can set the field to 'Image URL' format and call it with

$fields["field_name"]->content

and it should only output the url to the image without any surrounding html


Using theme hook suggestions for webform confirmation page

I think your problem is due to the use of $vars['theme_hook_suggestion'] (no trailing s) by webform.
This value overrides any that you could put in the $vars['theme_hook_suggestions'] array

I was having the same problem, I just unset this $vars['theme_hook_suggestion'] and my others suggestions in $vars['theme_hook_suggestions'] have been used.

Note: $vars['theme_hook_suggestion'] is a string NOT an array


How to render a custom entity in a controller?

Controllers should return a render array (or a custom response), you almost never need to render anything yourself outside a template.

Just replace this:

$build = $view_builder->view($entity);
$render_array = render($build);
$output['entity'] = $render_array;

with:

$output = $view_builder->view($entity);

to return a render array and let Twig handle the rendering.

But going further, you don't need to (and shouldn't) go into the database directly for this; the entity type manager works for all entity types, including your own, and entity storage classes have methods to help with this.

(As an aside, that service should also be injected rather than loaded from the static Drupal class method, your controller class is container aware).

Once that's available the code would be simplified to something like this:

public function content($name) {
  $build = [];
  $entity_type = 'foo';

  $storage = $this->entityTypeManager->getStorage($entity_type);
  $entities = $storage->loadByProperties(['name' => $name]);

  if ($entity = reset($entities)) {
    $build = $this->entityTypeManager->getViewBuilder($entity_type)->view($entity);
  }

  return $build;
}

To go one step further, you can add a loadByName() method to your entity class with a slight variation of the above, might save you some time and repetition further down the line.


Drupal 7 skip node in hook after node save

You can check using below condition while using node_save

  If $node->nid is omitted (or $node->is_new is TRUE), a new node will
  be added.

So, in your hook_node_update check for above condition before executing your code.


Form API + AJAX - Form doubles itself on submit

The issue you are facing is that you are not wrapping your form with the wrapper div, you're prepending a div to your form. When the ajax form is loaded, it is inserted into this wrapper div, rather than replacing the contents of the form.

Change this:

$form['wrapper'] = array("#markup" => "

");

To this:

$form["#prefix"] = "
";
$form["#suffix"] => "
";

This will wrap your form in the #status div.


How to prevent required field validation in validation function?

After a lot of debugging and search i get the solution.

function mymodule_reqursive_unrequired(&$form, &$form_state) {
    // print_r($form);die;
   if(!$form_state['values']['status']) {
     drupal_static('form_set_error', NULL, TRUE);
     drupal_get_messages();
   }
    // print_r($form);die;
}

for reference check it


I think what you would like to achieve is like a glossary.

You can by default create a glossary with views. How to do this is best explained or shown in this video.

If you want to show each of these on one page, i think you need to have some kind of a special field to group your results by. For this, try to the Views PHP module. Make a field where you grab the first letter of each term, and group by this (for example).


Drupal 7 Syntax Highlighter not applied when logged in as user or admin

Well, since nobody seems to want to answer my question, I will provide my solution to the problem. As I have discovered. Drupal do not load all javascripts, go figure why.

So, what I did is go to the admin panel. In configuration/performance you can aggregate all javascript files into one big file which apparently helps minimize server requests. When I did that, it worked. The syntax highlighting is now applied all the time, with a nasty side effect.

I got my code-hightlighting effect working but now, the wysiwyg shows up in comment's textarea field with a background that matches my websites... How unfortunate!


You can use this HOOK_menu_link_alter and add new attribute from there.

https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_menu_link_alter/7

function MYMODULE_menu_link_alter(&$item) {
  if ($item['link_path'] == 'user/login') {
    $item['options']['attributes']['data-toggle'] = 'modal';
    $item['options']['attributes']['data-target'] = '#login-modal';
  }
}

Note : Make sure you clear cache and are checking this for anonymous user.


Load single value from multiple value image field in View

Try to delete the delta field. You only need the content field and the restriction on the display values (like you did on the screenshot).


Why are hooks (except hook_help) not working?

You need to clear the cache after adding new hooks.


How to get one time login for all the users?

drush

To get one-time login for the specific user, use this syntax:

drush uli <user>

Where <user> is either uid (e.g. 5), user name, or email address for the user.

To get one-time login URL for multiple users or all, you need to run drush in the loop, e.g.

for uid in $(drush sqlq "SELECT uid FROM users"); do drush uli $uid; done

Run drush help uli for help with syntax.

To correct your http://html part, add -l http://example.com parameter, or set your $base_url in your settings file.

Custom code

If you're interested in sending one-time login via e-mail using Drupal, you can use user_pass_reset_url() function in your custom code.

  Generates a unique URL for a user to login and reset their password.

Contrib module

Or use Login one time module (for D8, check this issue).

  Login one time provides the ability to email one-time login links to users.


Add class to all labels in a comment form

Can't come up with a cleaner solution than implementing theme_form_element_label and adding the classes there depending on the elements name (comment_body) etc.

Maybe an option is to implement hook_form_comment_form_alter() and add specific identifiers to the elements you want to change the css class for the labels on in theme_form_element_label().


What should be used instead of raw filter?

The raw filter is still fine to use. The filter is not deprecated, only the raw tag.
From the Drupal 9 theming documentation:

As of Twig 1.x, the raw tag is deprecated in favor of verbatim.

Looking at the Twig 2.x documentation, you'll notice that the raw filter is not deprecated.
However, in the Twig 1.x documentation for the verbatim tag you can see that it replaced the raw tag in Twig 1.12. This is the cause of the deprecation in the Drupal 9 theming guide.
Note that there's a notice at the bottom of that page that says the tag was changed to help prevent confusion between the raw tag and raw filter.

The verbatim tag works in the exact same way as the old raw tag, but was renamed to avoid confusion with the raw filter.


You may need to increase the post_max_size value in php.ini


Changing a node field without going to the admin section?

Editablefields https://drupal.org/project/editablefields lets you edit many things, including terms, with ajax (without going to node edit form) but you'd have to be in fields mode.

Make a view, showing fields, and in the term's field settings you can choose "editable" and adjust some settings.


How do I display submenus separately from their menu tree?

I think the best way to go about it is to just use the Menu block module. Here is a quote about it (from the module's project page):

... have you ever used the Main and Secondary menu links feature on your theme and wondered “how the hell do I display any menu items deeper than that?”
Well, that’s what this module does. It provides configurable blocks of menu trees starting with any level of any menu. And more!
So if you’re only using your theme’s Main menu links feature, you can add and configure a “Main menu (levels 2+)” block. That block would appear once you were on one of the Main menu’s pages and would show the menu tree for the 2nd level (and deeper) of your Main menu and would expand as you traversed down the tree. You can also limit the depth of the menu’s tree (e.g. “Main menu (levels 2-3)”) and/or expand all the child sub-menus (e.g. “Main menu (expanded levels 2+)”).


thanks i had a misspelling in the router name. thank you all


Boolean fields configuration - How to enter a string in ON/OFF value bigger than allowed?

Trim the field down to something suitable so it makes sense, something like - 4% du montant total de la location et 0.5, and put the rest into the description field.


Show a view on a custom nodetype only if the logged in user is the author of this node

You just need to add an argument to this, passing the logged in user's uid. In Drupal 6, views 2 you used to have to reverse engineer this and add custom php into the argument handling code but this is built into Views 3. In your view:

Add Contextual filter, 'Content: author uid'
Select 'provide default value', type 'user id from logged in user'

This will find the uid of the logged in author and pass that as an argument to your view, restricting the view results to only items that were authored by the owner of that node.


Last form validation function is passing an error even though the first one registers the user

The OP mistakenly pasted user_login_final_validate() from D6 instead of D7. In D7, you avoid that error message by simply setting $form_state['uid'] = [a number]. You do that from within your custom #validate callback. Once you have done that, user_login_final_validate() will not throw an error and your form submission proceeds and thus login proceeds.


How to save validated third party API data if form validation fails

It sounds like before your mymodule_form_validation($form, &$form_state) function returns you want to store the Stripe information in the users $_SESSION array as a valid attempt/data.

You write to user session using the global session value in PHP and Drupal adds it to the Users' DB/Mongo user session info at the end of page execution. For example:

// in your form validation code ...
$_SESSION['stripe_username'] = 'john_doe';

On form load simply prepopulate the form data from $_SESSION. Eg, you're stuffing the content into session because it will be wiped on form reload -- then you're replacing it so a 2nd account isnt created.


Where should I place .htaccess to take effect in a particular site?

If you have a multi-site Drupal installation (ie. folders other than 'all' and 'default' in your /opt/apache/var/www/html/drupal-7.19/sites/ directory), then you cannot have a separate .htaccess file for each site, and must place your changes in the common .htaccess which should already exist in /opt/apache/var/www/html/drupal-7.19/. Note that as these changes will apply to all of your multi-sites, you need to ensure your rules don't break sites you're not interested in.

If you have a more traditional installation of one site per one Drupal instance, then you'll still be modifying the same .htaccess file in /opt/apache/var/www/html/drupal-7.19/, but don't have to worry about breaking other sites.


The settings form is hard-wired to only display the config field on the form if one of the following is installed: the Smart IP module, GeoAPI module, or the PHP geoip extension. Outside that you'll have to bypass the config form; if you're version controlling your config, make the change in the eu_cookie_compliance.settings.yml file; or use drush cset to make the change directly.
The hooks are documented in eu_cookie_compliance.api.php. You're wanting to use hook_eu_cookie_compliance_geoip_match_alter() that lets you alter the results from the eu_cookie_compliance_user_in_eu() function. The parameter $geoip_match is a keyed-array with country & in_eu keys that drive the logic.


how to unpublish a comment rather than deleting it

To unpublish a comment, click on the link to edit it. In the page that appears, you will see an "Administration" section that is a a collapsed field set; select the "Non published" checkbox, and the comment will be unpublished.

If you unpublish a comment, the child comments will still be published; you need to unpublish each of them.


Why can't I have hyphens in my db_query()

Make sure you use proper placeholders in your db queries, as per the Drupal API.

E.g in D7:

$query = db_query("SELECT * from {foo} WHERE bar = :bar", array(':bar' => $bar));

or

$query = db_select('foo', 'f')
  ->fields('f')
  ->condition('bar', $bar, '=')
  ->execute();

More info:

Database API
db_query
db_select

UPDATE: Now the the original SQL has been posted, the problem appears to be

Lack of use of fetchObject, fetchAssoc etc.. on the database result

You should be able to use

if($result->rowCount() == 1){
  $name = $result->fetchObject()->NAME;
}

As an aside, better to limit the query if you only want one record returned, e.g

$name = db_select('ukeys', 'u')
  ->fields('u', array('NAME'))
  ->condition('uid', $user->uid)
  ->condition('EMAIL', $user->mail)
  ->condition('GENERATEDKEY', $ukey)
  ->range(0,1)
  ->execute()->fetchfield();

That will return the $name value only, or FALSE if no record exists.


How to show pages other than nodes with the default language prefix

Probably the easiest way that I know is to turn off "Determine the language from the URL (Path prefix or domain)." on the languages page at "admin/config/regional/language/configure".
This way there is only 1 url for all content.

I do not know (of an elegant way) to have language prefix for nodes but not other pages.


Jquery Update doesn't implement hook_menu but instead uses form_alter with jquery_update_form_system_performance_settings_alter

You can find the configuration options at admin/config/development/performance.


how to distingush multiple ajax submit in single ajax callback

Last time I had to do this I used this method:

When creating the form create an array to hold deleted ids:

$form_state['deleted_items'] = array();

And give each remove button an ID relating to that items index:

$form['names_fieldset'][$i]['remove'][$i] = array(
    '#type' => 'submit',
    '#value' => t('Remove'),
    '#submit' => array('webinar_add_more_remove_one'),
    '#validate' =>false,
    '#ajax' => array(
        'callback' => 'webinar_add_more_callback',
        'wrapper' => 'names-fieldset-wrapper',
    ),
    '#attributes' => array(
        'id' => 'item-'.$i,
    ),
);

Then in webinar_add_more_remove_one check the id of the button that was pressed:

function webinar_add_more_remove_one($form, &$form_state) {
    $form_state['deleted_items'][] = str_replace('item-', '', $form_state['clicked_button']['#attributes']['id']);
    $form_state['rebuild'] = TRUE;
}

And then when building the form check the array of deleted items:

for ($i=0; $i < $form_state['num_names']; $i++) {

    if(in_array($i, $form_state['deleted_items']) continue;

    // rest of code....
}

You will also need to check the deleted item array in the submit and validate functions as we don't actually removed the deleted item from the $form_state array.


Without knowing what kinds of errors you are seeing, it is hard to say what to do.  If this is a live site, then I suggest that you edit your settings.php to turn off PHP error reporting.  IIRC, this will do it for you

error_reporting(0);
ini_set('display_errors', FALSE);
ini_set('display_startup_errors', FALSE);

or you could also edit your php.ini and do the same thing, or use the equivalent .htaccess directives.  You may get by with just turning off E_NOTICE.

If you are seeing favicon.ico errors in the in the log, then I suggest putting in a rewrite to point to the favicon in your theme, or at least on in one of the standard themes.

Another possible watchdog clogger are the internal connection messages.  You can try adding

# make sure internal dummy connections don't make it into drupal
RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
RewriteRule .* - [F,L]

to .htaccess if you are seeing them.

All of this said, if you are seeing several gigs of errors or warnings in your watchdog, then you have a serious problem with your site.  Clone the site to a development version, and figure out what is really going on:  fix the actual problem (ie, stop the errors) instead of curing a symptom (ie, hiding the error messages).


How to debug rules that are not being run?

/config/workflow/rules/settings

Enable all debugging and it should show in the log if the event is correct. It will go through each condition and say which passed and which failed.


Well, I'm really surprised such important functionality hasn't been implemented in D7.
Here we go: too much talk, not so much work.
In short: currently there's no token for dynamic taxonomy depth like termpath in D6.


How can my JavaScript-function access the Web Property ID from the Google Analytics module?

The most popular Google Analytics module (google_analytics) relies on generating inline JavaScript snippets for initializing tracking, which can make altering its behaviour difficult - likely requiring patching the module.

Googalytics is a more flexible alternative for Google Analytics in Drupal 8

drupalSettings is used to pass data to the front end.  This removes the use of inline JS, also making  the module compitible with Content Security Policy.
The data structure isn't intended to be modified on the front-end by JS, but hopefully the improved control possible in the back-end makes it unnecessary.
There's an open issue (with a patch currently needing feedback) for integrating  with the EU Cookie Compliance module.  If this matches your use case you may not need to write any custom code, otherwise it may provide a template for how to override the module's JS library for your needs.