Move required span of fields outside the label

You can achieve this goal via implementing theme_form_element_label.

I hope you already know how to implement or override theme.

e.g.

function MYTHEMENAME_form_element_label($variables) {
  $element = $variables ['element'];
  // This is also used in the installer, pre-database setup.
  $t = get_t();

  // If title and required marker are both empty, output no label.
  if ((!isset($element ['#title']) || $element ['#title'] === '') && empty($element ['#required'])) {
    return '';
  }

  // If the element is required, a required marker is appended to the label.
  $required = !empty($element ['#required']) ? theme('form_required_marker', array('element' => $element)) : '';

  $title = filter_xss_admin($element ['#title']);

  $attributes = array();
  // Style the label as class option to display inline with the element.
  if ($element ['#title_display'] == 'after') {
    $attributes ['class'] = 'option';
  }
  // Show label only to screen readers to avoid disruption in visual flows.
  elseif ($element ['#title_display'] == 'invisible') {
    $attributes ['class'] = 'element-invisible';
  }

  if (!empty($element ['#id'])) {
    $attributes ['for'] = $element ['#id'];
  }

  // The leading whitespace helps visually separate fields from inline labels.
  return ' <label' . drupal_attributes($attributes) . '>' . $t('!title', array('!title' => $title,)) . "</label>" . $t('!required', array('!required' => $required)) . "\n";
}

Put this function on template.php


What you do when you remove a PHP extension used from a module you installed is uninstalling the module and then removing the PHP extension.
In this case, you also need to do something more: Since you are using the APC module as alternative Drupal cache, you need to remove the lines added to the settings.php files. Probably you will find the following lines.
$conf['cache_backends'][] = 'sites/all/modules/apc/drupal_apc_cache.inc';
$conf['cache_class_cache'] = 'DrupalAPCCache';
$conf['cache_class_cache_bootstrap'] = 'DrupalAPCCache';

Alternatively, you could find the following ones.
$conf['cache_backends'][] = 'sites/all/modules/apc/drupal_apc_cache.inc';
$conf['cache_default_class'] = 'DrupalAPCCache'

In any case, you need to remove the $conf['cache_backends'][] = 'sites/all/modules/apc/drupal_apc_cache.inc'; line, and any line in settings.php that references the DrupalAPCCache class.
References

The README file for the APC module

Side note
This is one of few cases where disabling a module, or uninstalling it without deleting its files, doesn't stop Drupal from using it. In fact, Drupal uses the following code.
  // Allow specifying special cache handlers in settings.php, like
  // using memcached or files for storing cache information.
  require_once DRUPAL_ROOT . '/includes/cache.inc';
  foreach (variable_get('cache_backends', array()) as $include) {
    require_once DRUPAL_ROOT . '/' . $include;
  }

It doesn't check the files are for a not enabled or not installed module. As long as it finds the files, it uses them. If then the code is using a non existing function (as in your case), it will raise a runtime error.


Incorrect string value: '\xF0\x9F\x92\x99' for column "'comment_body_value'"

This explains how to solve this issue: https://www.jeffgeerling.com/blogs/jeff-geerling/solving-emoji-problem-drupal-7


How to programmatically print a webform block with caching enabled?

The Dynamic Page Cache needs to placeholder the dynamic part and it can only do so when it is built in a lazy builder:
/mymodule/src/WebformLazyBuilder.php
<?php

namespace Drupal\mymodule;

use Drupal\Core\Render\Element\RenderCallbackInterface;

class WebformLazyBuilder implements RenderCallbackInterface {

  public static function buildWebform($webform) {
    return  [
      'webform' => [
        '#type' => 'webform',
        '#webform' => $webform,
      ],
    ];
  }

}

Then you can put the lazy builder in a template preprocess hook:
$variables['contact_form'] =  [
  '#lazy_builder' => ['\Drupal\mymodule\WebformLazyBuilder::buildWebform', ['contact']],
  '#create_placeholder' => TRUE,
];

Blocks are placed in a lazy builder by default, see BlockViewBuilder::viewMultiple.


Create description for taxonomy term view

There are at least two ways to do this:

1. Views

In your views admin page, add a Global: Text area to header. Then check off Use replacement tokens from the first row. You can see the tokens (patterns) below under Replacement patterns. Your custom text my be like that:

"Improve your snorkeling, spearfishing and freediving with one of the many schools and freediving training courses held by apnea instructors across %1."

2. page--vocabulary--[machine-name].tpl.php

You could create a custom vocabulary tpl.php page and add your custom text. Details come from that answer:

Copy (and past) the page.tpl.php into your theme folder.
Rename it page--vocabulary--[machine name].tpl.php

(page--vocabulary--location.tpl.php etc.)

Open the template.php file in the theme folder and add this function:

Don't forget to change the THEME to your theme name and if you have already had the preprocess_page function in the template.php file and do not add the preprocess_page function again.

function THEME_preprocess_page(&$vars) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $term = taxonomy_term_load(arg(2));
    $vars['theme_hook_suggestions'][] = 'page__vocabulary__' . $term->vocabulary_machine_name;
  }
}

Open the page--vocabulary--location.tpl.php file and find that line:

(Your theme's template.php file may be different but the main structure is the same.)

Then add what you want:

(with your css class, spans etc.)

<div class="term_description"
"Improve your snorkeling, spearfishing and freediving with one of the many schools and freediving training courses held by apnea instructors across <?php print $title; ?>."
</div>

 - Clear all caches.


How to import XML (using an API) via Feeds module?

You need todo more debugging. As 1 possible debugging example use Chrome Inspector to assure that properly configured, Feeds is requesting the correct URL to get the XML payload. you can do this by logging HTTP persistently before you hit the drupal admin page and recording what Feeds is issuing.

Compare that to hitting the URL by hand in the browser, or whatever steps you take. I suspect that Feeds has an API to alter the outbound request to the remote server and make it 1:1 with hitting the remote url by hand.

There are other HTTP session records you can use depending on your OS.


How to block / restrict a list of URLs using Rules?

Assume the relative paths for your 3 URLs are like my/path1 (for ULR1),  my/path2 (for ULR2) and  my/path3 (for ULR3). And assume your homepage has a relative path MyHomePage. And assume this question is about D7.

With these assumptions, you could use a rule that answers your question which looks like so (in Rules export format):

{ "rules_limit_access_to_some_urls" : {
    "LABEL" : "Limit access to some URLs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "data_is" : {
          "data" : [ "site:current-page:path" ],
          "op" : "IN",
          "value" : { "value" : [
              "my\/path1",
              "my\/path2",
              "my\/path3"
            ]
          }
        }
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "MyHomePage" } },
      { "drupal_message" : {
          "message" : "Access to the content located at \u0022\u003Cstrong\u003E[site:current-page:path]\u003C\/strong\u003E\u0022 is not allowed.",
          "type" : "warning"
        }
      }
    ]
  }
}

Note site:current-page:path token in this rule, which is different from site:current-page:url.

To make the above rule work in similar situations, just adapt the paths by changing 'my/pathX' (with X=1, 2, 3) to whatever fits. And adapt the message to be shown.

Some more samples where you can see this technique at work:

How to use the Rules module to implement a custom redirect for an outdated URL?
How to hide the content of nodes/ completely, and still maintain use within Drupal 7?
What is the best way to restrict website's direct access through node urls?

Remark: Instead of using a data comparison in this Rules Condition, you may also want to try using a text comparison. That would allow you to use regular expressions. If your URLs have a common pattern for which you can write to single regular expression (such as URLx, with x=1, 2, 3, ..., 456, 457, ...), you would only need 1 such Rules Condition.


print individual field inside views-view.tpl.php

You are wise to admit it before someone else points it out:  "I am not php programmer." ;)  This is a pure PHP problem, having very little to do with Drupal.

Your foreach() loop defines the variables $delta and $item.  Unlike some other languages, they are still in scope when the loop finishes, keeping the values they had at the end of the loop.

You could do something like this (untested):

<?php
  $first_item = reset($view->style_plugin->rendered_fields);
  $last_item = end($view->style_plugin->rendered_fields);
  print $first_item['myfield1'];
  pring $last_item['myfield2'];
?>

After the foreach() loop, $item would be the same as $last_item.

The PHP docs are pretty good:  arrays
and array functions.


Entity Metadata Wrapper: Setting User Reference

Looks like Drupal is trying to set the delta column to the string "uid", which suggests you need another level in your array:

$user_perm[] = array (
  'uid'    => $account->uid,
  'access' => TRUE,
);

$ewrapper->field_user_permission->set($user_perm);


Form element validation #element_validate not working

It's probably this line:

$form['my_field']['widget']['#element_validate'] = array(array($this, 'myModuleValidateTrue()'));

Which should be this, without parentheses in the method name:

$form['my_field']['widget']['#element_validate'] = array(array($this, 'myModuleValidateTrue'));

See PHP: Callbacks / Callables for the full story.


The "entity_reference_revisions_entity_view" plugin does not exist

This looks like a problem when installing the module.

Check this with drush.

drush ev "var_dump(array_keys(\Drupal::service('plugin.manager.field.formatter')->getDefinitions()))"

Acc. to the error message the plugin is missing. Now reinstall the module:

drush pmu entity_reference_revisions
drush en entity_reference_revisions

and check again:

drush ev "var_dump(array_keys(\Drupal::service('plugin.manager.field.formatter')->getDefinitions()))"

If the plugin is not discovered report any errors you see.

Only debug this on a test site with no field data in this field type.


Note that print_r will be better in this case because to see the form he desires one must be logged out otherwise you'll get the password reset for the active user, which is different.

Leandros, try putting this in your theme's template.php and visiting user/password (not logged in)

function YOURTHEMENAME_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_pass':
        print '
';print_r($form); print '
';
      break;
  }
}

It will give you an array of everything that's in there.  Then, say you wanted to change the text "Username or e-mail address" and the text on the submit button you could do this:

function YOURTHEMENAME_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_pass':
        //print '
';print_r($form); print '
';
        $form['name']['#title'] = 'Please type your username/email quickly.';
        $form['actions']['submit']['#value'] = 'Email it to me!';
      break;
  }
}


Drupal routes aren't display in a UI anywhere, but you can look them up in a database client (e.g. PHPMyAdmin). The route defnitions are stored in the router table. The name, path, & pattern_outline columns should be enough to search for what you're looking for. The name column contains the unique ID for each route. In your case, contact.site_page is the name of the contact form route.


I can't turn off/pause automatic slideshow when there is only 1 picture (using lightbox2)

when there is only one picture then it won't go off untill click somewhere else on the screen ... for better understanding go to lightbox configurations...


Probably you have nodes where the "field_heading" field has not been set, or you didn't enable the field in output tab on content type section.

Try this code:

if (!empty($content['field_heading'])) {
  print render($content['field_heading']);
}


Does Drupal CORE have any built-in analytics?

The only module that comes with Drupal core is the statistics module. And by default it is normally turned off. To use it, you have to enable it. So if it was not enabled initially, you will not be able to get the stats for dates prior to the date it was enabled.


Emails sent by actions not using html email formatting

When you build an action on the settings page (/admin/config/system/actions) you have 2 options. One is 'send e-mail' and the other is 'send HTML e-mail'. 'Send e-mail' is plain text only, as where 'send HTML e-mail' allows the use of HTML templates. Make sure you are using the 'send HTML e-mail' action.


Image wrapper by img tag with external url

You can use the Media module to get external images via their URL and show it in the node page.

By saving locally if you mean 'locally' in the server that is running Drupal then it doesn't do that. To achieve it you will need a separate server like Amazon S3 to store your images alone.


How to change a user to a different role based on the number of their posts?

I found a module User Stats which integrates with Rules and provides tokens like [user:post-count] which can be used for numerical comparison. Hope this helps someone else.


I found the problem. I needed to add the id configuration to the source:

ids:
    title:
      type: string

I also changed the selector back to: title


Routing to production and testing Drupal installations on shared hosting account

Most shared hosting plans have a feature called subdomains or addon domains (these features exists in cpanel plans for sure. I m attaching a screenshot from a godaddy hosting plan). You may use this feature to effectively create a new apache virtual host so you dont have to mess with the .htaccess file to do the routing depending on the domain name

Also note that most shared hosting providers do not support overriding many features using the .htaccess file so many on of the options in your .htaccess file may be ignored depending on the apache configuration file (which you usually do not control)

Also note that .htaccess is an Apache concept. If your hosting provider uses another http server (e.g. nginx or IIS) the .htaccess file will be totaly ignored.

Last if you really want to do this with .htaccess (i dont recomend this) make sure you dont miss the query option in any of your cases. Notice the last part here index.php?q=$1  the ?q=$1 part is very important


How can I avoid extraneous divs in my form?

The first
 is hard coded into the theme_form() function, so you can override that in your theme's template.php file if you want to. You should be aware, though, that the wrapping
 is actually there to ensure XHTML compliance; if you remove it your page will fail validation.

That said, this is the code to do it (replacing MYTHEME with the name of your theme):

function MYTHEME_form($variables) {
  $element = $variables['element'];
  if (isset($element['#action'])) {
    $element['#attributes']['action'] = drupal_strip_dangerous_protocols($element['#action']);
  }
  element_set_attributes($element, array('method', 'id'));
  if (empty($element['#attributes']['accept-charset'])) {
    $element['#attributes']['accept-charset'] = "UTF-8";
  }

  return '<form' . drupal_attributes($element['#attributes']) . '>' . $element['#children'] . '</form>';
}

The only change from the original function is the removal of the
 and
 from the last line, and the removal of the XHTML compliance comment as that no longer applies.

Overriding the fieldset theme is pretty much the same, except you'll be borrowing the code from theme_fieldset():

function MYTHEME_fieldset($variables) {
  $element = $variables['element'];
  element_set_attributes($element, array('id'));
  _form_set_class($element, array('form-wrapper'));

  $output = '<fieldset' . drupal_attributes($element['#attributes']) . '>';
  if (!empty($element['#title'])) {
    // Always wrap fieldset legends in a SPAN for CSS positioning.
    $output .= '<legend>' . $element['#title'] . '</legend>';
  }

  if (!empty($element['#description'])) {
    $output .= '
' . $element['#description'] . '
';
  }
  $output .= $element['#children'];
  if (isset($element['#value'])) {
    $output .= $element['#value'];
  }

  $output .= "</fieldset>\n";
  return $output;
}

Once you clear Drupal's caches the extraneous markup should just disappear.


Breadcrumb displays overridden page label instead of node title

This is an issue related with page_manager module.
Check out the d.org issue queue https://www.drupal.org/node/2665328


How to add custom column in-between people/users admin page table?

You need to change the sequence of the array, like:

function meme_user_update_form_user_admin_account_alter(&$form, &$form_state, $form_id) {
  $changed_column = array(
    'data'  => 'LAST CHANGED',
    'field' => 'u.changed'
  );
  $operation_column = array_pop($form['accounts']['#header']);

  $form['accounts']['#header']['changed'] = $changed_column;
  $form['accounts']['#header']['operations'] = reset($operation_column);

  foreach ($form['accounts']['#options'] as $key => $row) {
    $user_object = user_load($key);
    $user_language = ($user_object->language) ? $user_object->language : LANGUAGE_NONE;

    $operation_column = array_pop($form['accounts']['#options'][$key]);

    $form['accounts']['#options'][$key]['changed'] = $user_object->field_user_changed[$user_language][0]['value'];
    $form['accounts']['#options'][$key]['operations']['data'] = reset($operation_column);
  }
}


You can try to use this module https://www.drupal.org/project/dfv


How to Enter Fields in the Order Information form (and confirmation email)?

Adding additional fields to the customer

You'll want to add the fields to the customer profile:

/admin/config/people/profiles/manage/customer/fields

Editing the email text

According to the Commerce documentation:

Use the template file located in /commerce/modules/order/templates/commerce-order-receipt.html.twig.


individual user profile on click of user name in view

You can try Colorbox Node to open particular node content in popup. This module gives the user the ability to display ANY page inside a colorbox modal without the header and footer.

It can be integrated with views also.

Views Integration with node colorbox modal


This does the job:

#main-content table tbody .views-field a:hover {
  color: orange;
}

It's a CSS specificity issue (also the reason that I never use ID's to style elements).  Check this page out from Stuff and Nonsense for a REALLY good explanation on CSS specificity (in relation to Star Wars).


Change search results pager to mini pager?

you can override   template_preprocess_search_results in your template.php and
instead

   $variables['pager'] = theme('pager', array('tags' => NULL));

use

   $variables['pager'] = theme('views_mini_pager',array('tags' => NULL));

( just make sure you installed views module)
also this question can get you some clue

How do I customize the search result page?


How to stop the jquery element being added on ajax requests

The better way would be to use the context of the behaviour along with .once() as mentioned here ( https://www.drupal.org/node/1667874 ), something like below:

(function ($){
  Drupal.behaviors.customjs  = {
    attach: function (context, settings) {
      // Add context along with .once something like below.
      $("#superfish-1", context).once("CLASS-NAME").before("Menu");
    }
  }
})(jQuery);


If you use, '%path-aliases', either specify the full path to Drush, or ensure that the Drush that you are calling (e.g. drush) is on your PATH.

Example:

$aliases["mysite"] = array (
  'uri' => 'mysite.org',
  'root' => '/path/to/drupalroot',
  'remote-host' => 'myisp.com',
  'remote-user' => 'www-admin',
  'path-aliases' =>
  array (
    '%drush-script' => '/home/myuser/drush/drush',
  ),
);

If setting the PATH in your .bashrc, always do so at the very top of the file.  It is common for boilerplate (host-provided) .bashrc files to have a line somewhere in the middle that exits prematurely when not in interactive mode -- and Drush makes remote Drush calls non-interactively in most instances.


How do I implement drag and drop node re-ordering in a view?

I think you're looking for the Draggable Views module:

  DraggableViews makes rows of a view "draggable" which means that they can be rearranged by Drag'n'Drop.


How to embed a view into the teaser of a node?

You can install and activate the Field views module, and add the field type to your content type. Configure it for your view.

Then edit your content type, and under 'Manage Display' configure the field to be visible in your teaser.


Is it possible to put Drupal.settings javascript in separate file

Yes - this won't make a difference to Drupal where the file is coming from. In Drupal, you can load this using drupal_add_js:

drupal_add_js('http://example.com/example.js', 'external');

Note that these files will not get aggregated when preprocessing is on.

The other thing to watch for with external javascript is to make sure you are testing for the existence of functions / variables if you are calling them in your file since you can't control the order / speed that they are loading in.


How to know which module is responsible for each database query?

For any modules you download from drupal.org, you can click on the function link within the where column and it will direct you to api.drupal.org and you can see the module there.

I couldn't find any settings that would enable showing where the call originated (file path) if the module wasn't an 'official' contrib.  A little digging and you can find the information within the devel.module.  Specifically, devel_query_table() receives $queries as its first argument.  $queries contains the rows that will be displayed and it does have the file path.

I created a quick patch to test this (Doing this does not imply that i think you should modify contrib modules in a production environment):

diff --git a/sites/all/modules/devel/devel.module b/sites/all/modules/devel/devel.module
index 0ebdef4..dd6aaa8 100644
--- a/sites/all/modules/devel/devel.module
+++ b/sites/all/modules/devel/devel.module
@@ -1482,7 +1482,7 @@ function _devel_print_object($obj, $prefix = NULL, $parents = NULL, $object = FA
*/
 function devel_query_table($queries, $counts) {
   $version = devel_get_core_version(VERSION);
 -  $header = array ('ms', '#', 'where', 'ops', 'query', 'target');
 +  $header = array ('ms', '#', 'what', 'ops', 'query', 'target', 'where');
    $i = 0;
   $api = variable_get('devel_api_url', 'api.drupal.org');
   foreach ($queries as $query) {
 @@ -1514,7 +1514,8 @@ function devel_query_table($queries, $counts) {
   'id' => "devel-query-$i",
   'data' => $placeholders . $args . $explain,
 );
 -    $cell[$i][] = $query['target'];
 +    $cell[$i][] = $query['target'];
 +    $cell[$i][] = '
' . check_plain($query['caller']['file']) . '
';
      $i++;
     unset($diff, $count, $ops);
 }

Here is the raw output on pastebin: http://pastebin.com/Ww5CkQsL

And a screenshot of the un-styled results:

This is a little rough looking as there are style sheets involved, but it gets the information.

Even better would be if the where column builder checked for the availability of the function on d.o but I'll digress, as I feel we may be entering, 'file an issue (feature request)' territory.


A General Strategy for Images with Captions in Content

Your desire for a "non-Javascript" solution is in conflict with your desire to allow users to "see" the image in their WYSIWYG editor, as you need to run Javascript for those to work.  So, you'll have to either drop the "non-Javascript" requirement, or be satisfied with image fields that may appear above or below the main body.  [Note 1: Images "above" the node body can be set to float left or float right, and thereby appear to be inside the text.  Note 2: If by "non-Javascript" you mean non-JS at render time, then no problem.]

Whichever way you go -- be it images embedded in a WYSIWYG editor, or images as file fields, you'll probably want to use the media module, as it can support either method.

There is a lot of information available on the media module, which is becoming "the way" to do images in Drupal.  Many additional contrib modules are compatible with media. You'll want to take a look at the following two configuration guides:

Media 2.0 Quickstart

Configuring embedded images with media and wysiwyg modules

Here is the point where I remember to take a step back and point out that my experience is with media 2.0-unstable7.  Depending on how comfortable you are with making adjustments to php code, you might prefer to use the stable release, which is currently 7.x-1.2.  I didn't have too much trouble with 2.0-unstable7, except for the fact that it does not support editing of arbitrary image metadata on WYSIWYG images, so I am using only image file fields at the moment.  If the only metadata you wish to attach to your images is a caption, then I expect that 7.x-1.2 should work for you, although I have not tried it myself.

In any event, I would recommend using the provided "title" field, and render that as a caption. Doing that is as easy as visiting admin/structure/file-types and clicking on "manage display" for the image file type.  This page works just like the "manage display" page in cck; you can just drag the "title" field up so that it is under the "file" field, and use css to style it as a caption.  You'll probably also want to download and enable the entity_view_mode module, which will allow you to define additional view modes for your image files.

As I said, I'm not embedding images in WYSIWYG editors at the moment, but the article you quoted gives good advice on that.  If you're using the media module, you should still be able to format the title field as a caption regardless of whether you're using file fields or WYSIWYG.


Get an Error with rendered page content in custom template file

You haven't passed a variable named $title to the template, so one won't be available.

To do so, add variables to your hook_theme implementation:

function MYMODULE_theme() {
  return array(
    'MYMODULE-page' => array(
      'path' => drupal_get_path('module', 'MYMODULE') . '/templates',
      'template' => 'MYMODULE-page',
      'render element' => 'page',
      'variables' => array('title' => ''),
      ),
    ),
  );
}

and in your page callback:

return array(
  '#theme' => 'MYMODULE-page',
  '#title' => 'Title here',
);


Module for enforcing mandatory minimum number of tags in content type field?

You should be able to use Field Validation.

  This module adds an extra tab to each field instance, allowing you to
  specify validation rules for your field instances.

Just create your term/entity reference field and set up a validation rule using the Number of Selections rule.

Leave the maximum number of fields empty, and enter the minimum you require as the minimum required values.


Is it still possible to use a custom attribute for a form (e.g. $form['#foo'])?

See FormCache::setCache(). The whole $form is put in the cache, anything that's in there is stored and fetched again.

That said, I would definitely advise against using it. The recommended and standard way to store something is $form_state->get()/set().

Also be aware that while this still works when the form is cached, Drupal 8 only caches form/form_state once an actual form submission happens. Usually that means only for ajax requests and in case of form validation errors (although I don't 100% know how it behaves then).

That means you can not put something in $form['#whatever'] or $form_state->set('whatever, ...) on the first form build and expect it to stay there.


Drupal way of sending push notification to android devices

Try the Push Notifications module. I've never done this -- but you're basically asking how do I send X message type to a user (SMS, Email, whatever). I've sent emails and SMS messages before ...

Beyond wanting to send this notification from within drupal/php ... there isn't anything really drupal specific in your question in terms of the drupal API.

If you dont userstand the protocol or APIs you want to talk to I would suggest you research them more as well. I would start by looking at the source code for the PushNotifications module and see how it handles the logic of what you are asking about ...


how to hide the tags and category in the front page

You can hide it by going to admin/structure/types/manage/YOUR-CONTENT-TYPE/display and just drag the field(s) info the Disabled section.


You can directly add fields to users (at admin/config/people/accounts/fields) if that's all you need. You can set for each field if it should show up on the registration form.

What Profile2 allows additionally is to create multiple profiles for each user, similar to the categorization feature of the core profile.module.


Can I use the function menu_tree() in Drupal 7 to customize a menu and add CSS classes?

The easiest way to add custom classes to menu items in Drupal 7 is the Menu Attributes module.

If you really want to do this programmatically, then you can override the theme_menu_link() function in your theme's template.php file. Be sure to read the drupal.org documentation on Overriding Themable Output.


Can use Webform for add combobox for select language on the site?

No, you can't do this with webform. Webform's purpose is to collect and store user submitted data.
You can create a language dropdown by creating an override template for links--language-block.html.twig in your custom theme.


How to get Views Criteria Filter arguments inside Views API hook?

Ok, I found it.

In $view->filter property is an array of views filter handler objects. In selected object inside $hander->value array are arguments passed to this filter.


It is very simple.

The steps are the following:

Please go to: admin/config/people/accounts
In the secction "REGISTRATION AND CANCELLATION
" select "Visitors".
Uncheck "Require e-mail verification when a visitor creates an account".
Click in the buton "save configuration".

Try again register one user.

I did a test and everything went well.


How to write big updation code using Batch API?

The timeout is caused because you're trying to load all 5K+ users before you start the batch. Instead get the User IDs first and load when processing. Check an example below. Also have a look at Batch API Overview documentation page, before you continue:

function anonymize_data_menu() {
  $items = array();
  $items['admin/config/content/anonymize-user-data'] = array(
    'title' => 'Anonymize User Data',
    'description' => 'Click this link to anonymize user data',
    'type' => MENU_LOCAL_ACTION,
    'page callback' => '_anonymize_users_data',
    'access arguments' => array('administer user anonymize'),
    'file' => 'anonymize_data.user.inc',
  );
  return $items;
}

function _anonymize_users_data() {
  // Instead of loading all users at once,
  // first get there uid and then load chunk of user while processing.
  // $users = entity_load('user');
  $uids = db_select('users', 'u')
    ->condition('u.uid', 1, '>')
    ->fields('u', array('uid'))
    ->execute()->fetchAllKeyed(0, 0);

  $chunk_count = 20;
  // We've all rows here, split them in chunks.
  $chunks = array_chunk($uids, $chunk_count, TRUE);
  // Get all rows count.
  $num_operations = count($uids);

  $operations = array();
  foreach ($chunks as $chunk) {
    $operations[] =  array('user_anonymize_op', array(
      $chunk,
      array(
        'max' => $num_operations,
        'chunk' => $chunk_count,
      )
    ));
  }

  $batch = array(
    'operations' => $operations,
    'title' => t('Import batch'),
    'init_message' => t('Initializing'),
    'error_message' => t('An error occurred'),
    'finished' => 'user_anonymize_op_finished'
  );

  batch_set($batch);
  batch_process('admin/people');
}

function user_anonymize_op($rows, $batch_data, &$context) {
  // Define variables on start of batch operation.
  if (!isset($context['results']['progress'])) {
    $context['results']['progress'] = 0;
    $context['results']['chunk'] = $batch_data['chunk'];
    $context['results']['max'] = $batch_data['max'];
    $context['results']['failed'] = array();
  }

  // Do your processing here. START HERE.
  $names = [];
  $users = entity_load('user', $rows);
  foreach ($users as $account) {
    if (!empty($account->uid) && ($account->uid > 1)) {
      // What is $i here?
      $account->name = $i . '-' . $account->name;
      $account->pass = user_hash_password('blah');
      user_save($account);
      $names[] = $account->name;
    }
  }
  // Do your processing here. END HERE.

  // Update completion count.
  $context['results']['progress'] = $context['results']['progress'] + count($rows);

  $context['message'] = t('Processed @name user data.', array('@name' => implode(', ', $names)));

  // Inform the batch engine that we are not finished,
  // and provide an estimation of the completion level we reached.
  if ($context['results']['progress'] != $context['results']['max']) {
    $context['finished'] = $context['results']['progress'] % $context['results']['max'];
  }
}

function user_anonymize_op_finished($success, $results, $operations) {
  if ($success) {
    $message = count($results) . ' processed.';
  }
  drupal_set_message(t($message));
}


How to run cron automatically after node published?

have you managed your cron configuration, if no then go to /admin/config/system/cron and set your cron settings to run on that interval of time.

Hope it solves your issue.


You can try Embedded Google Docs Viewer and check whether your requirements are fulfilled or not. Here is the demo of the module.

The Embedded Google Docs Viewer module adds a new formatter to the File field using the Field API. This formatter displays PDFs, Microsft Word documents, Powerpoint presentations, or Excel spreadsheets directly within a Drupal node.


How this gets started is hard to tell. But once it does it spreads quickly. When a user clicks on a link with /index.php the page will include /index.php in the base url, which then is used for all links generated on this page. The same is the case for search bots, once they hit a link with /index.php they will crawl the whole site with it.

To stop this, redirect the unclean urls. You could use this core patch or Redirect, but as long as the core patch is not committed and the module is not released, you can do this in .htaccess. Place these two lines at the top of the rewrite rules:

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

  RewriteCond %{THE_REQUEST} "^[A-Z]{3,9}\ /index\.php(.+)\sHTTP" [NC]
  RewriteRule "^" "%1" [R=301,NE,L]


Drupal 6 has a module to publish to a site via external GUI applications. It supports different XML-RPC based blogging APIs, such as the Blogger API, the new Blogger Data API, the MetaWeblog API, and most of the Movable Type API.

In Drupal 7, the module has been removed from core, and it is now a third-party module.

Reference

BlogAPI: post from blog tools


Collapsible items in menu administration

The Big Menu module seems to do the job. Here is a quote about it (from the module's project page):

An alternative to core menu management - adds scalability to the admin menu management screen, by loading subtrees via AJAX (not related to megamenu & similar display modules - this is an admin-only content management utility).
When dealing with a site menu that contains thousands of links, the Drupal Menu UI admin interface becomes so unwieldy as to be impossible to use. When the drag & drop functions for tree management are running, a page can take minutes to render.
This module attempts to replace the all-in-one global tree view with a similar interface, but sub-trees are "collapsed" below a certain level, and can be expanded as needed.


Removing HTML rendered for Block Regions

This may help some one else who is having this issue.
So how to remove the extra black divs inside a region you would do the following:
Find "core/modules/system/templates/region.html.twig"
Change it from this –
{#
/**
 * @file
 * Default theme implementation to display a region.
 *
 * Available variables:
 * - content: The content for this region, typically blocks.
 * - attributes: HTML attributes for the region <div>.
 * - region: The name of the region variable as defined in the theme's
 *   .info.yml file.
 *
 * @see template_preprocess_region()
 *
 * @ingroup themeable
 */
#}
{% if content %}
  <div{{ attributes }}>
    {{ content }}
  </div>
{% endif %}

To this –
{#
/**
 * @file
 * Default theme implementation to display a region.
 *
 * Available variables:
 * - content: The content for this region, typically blocks.
 * - attributes: HTML attributes for the region <div>.
 * - region: The name of the region variable as defined in the theme's
 *   .info.yml file.
 *
 * @see template_preprocess_region()
 *
 * @ingroup themeable
 */
#}
{% if content %}
    {{ content }}
{% endif %}


I'm one of the maintainers of the GDPR module.

First of all I'd like to call your attention to the fact that GDPR is not an IT-related question solely. Personally I'd suggest stop considering "adding an extension to my CMS will make me legally good". That's not that easy. You, or the owner of the Drupal website you maintain/develop on their behalf should transform their organization/company's inner workflow of dealing with personal data.

However, the GDPR module indeed can be a perfect starting point to install, go through on its checklist points and after you read them carefully, hopefully will realize that you're just stepped on the path of becoming GDPR-compliant, but a big portion of tasks ahead probably falls out of the scope of configuring Drupal.


You can easily execute and render a view with arguments in a custom module.

I would:

1 - Set up some JS code to trigger an AJAX call to the server

2 - Use hook_menu() to define a custom menu callback on a specific URL, ie: /views/ajax/view_name/view_display/view_arguments

3 - Create your callback function()

4 - Load and render the view with arguments: (this is From Views 2 API):

$view = views_get_view('foobar');  // get the view named `foobar`
$view->set_display('page_1');  // Set the view display you want to use
$view->set_arguments(array($foo));  // Pass an array containing one or several variables you want to use as arguments in the view
$result = $view->render(); // Returns HTML

5 - Return your result in JSON (practical sometime if you want to pass more information than the view itself). You can use drupal_json_output() in D7.


How to force drupal 7 to load HTTPS assets?

I updated settings.php with: $base_url = 'https://'.$_SERVER['SERVER_NAME'];


How to show picture of the user who triggered the rule for message activity?

Since you are using Rules to create your messages to be delivered, you can try to make the missing tokens available by using the Replacement patterns for each message type. Refer to the answer to What's the purpose of "Replacement tokens" of a Message type? for way more details on that (it explains how these Replacement tokens can be used to pass data available in Rules to the Message module).

With that, your only remaining challenge is to get access to the user picture in a custom rule. In D8 that picture has become a field also, but that's not the case in D7. Therefor you may get it to work in D7 also if you also use the user picture field module (which doesn't have an official D7 release yet, but about 11K reported installs sounds like it's a pretty stable module).


Why do only some of my hooks get called?

I'm surprised doing a 'print' works at all and does not produce a headers already sent error.
Your hooks may well be being called.
Instead of calling your own console.log function, install the devel module and call dpm('my message');
It will give you a much better idea of what hook is and is not being called.

eg. (your module with devel enabled).

function test_module_help ($path, $arg) {
    switch($path) {
        case "admin/help#test_module":
            return '<p>' . t("This is just a test module right now.") . '</p>';
            break;
    }
}
function test_module_insert ($node) {
    dpm("node inserted");
}
function test_module_user_login_submit (&$form, &$form_state) {
    dpm("login submitted");
}
function test_module_block_view ($delta = '') {
    dpm("block viewed");
}
function test_module_user_login (&$edit, $account) {
    dpm("user logged in");
}
function test_module_user_logout ($account) {
    dpm("user logged out");
}
function test_module_view ($node, $view_mode) {
    dpm("node viewed");
}
function test_module_form_alter (&$form, $form_state, $form_id) {
    dpm("form altered");
}
function test_module_delete ($node) {
    dpm("node deleted");
}
function test_module_form_user_login_alter(&$form, &$form_state, $form_id) {
    dpm("user login form altered");
}


For custom blocks it's pretty easy to add classes without any module. Simply add a text (plain) field - or whatever fit's your needs best, get the value in the block.html.twig (maybe use Twigs |clean_class filter) and add it to the classes.


Block is not showing up in a custom taxonomy page template

A page.tpl.php template file doesn't get blocks to render; it gets the theme regions to render, which by default are the following ones:

$page['help']: Dynamic help text, mostly for admin pages
$page['highlighted']: Items for the highlighted content region
$page['content']: The main content of the current page
$page['sidebar_first']: Items for the first sidebar
$page['sidebar_second']: Items for the second sidebar
$page['header']: Items for the header region
$page['footer']: Items for the footer region

Themes can define other regions as well.

When you want to show a blocks that has been associated to the "highlighted" region, the page template file needs to contain the following code (or similar).

<?php if ($page['highlighted']): ?>
<?php print render($page['highlighted']); ?>
<?php endif; ?>

Without that code, a block that should visible in the "highlighted" region would not be visible.

In a taxonomy term template file, you need to get the block content using code similar to the following one.

  global $theme_key;

  $query = db_select('block', 'b');
  $block = $query
    ->fields('b')
    ->condition('b.theme', $theme_key)
    ->condition('b.status', 1)
    ->condition('b.delta', $delta)
    ->condition('b.module', $module)
    ->orderBy('b.region')
    ->orderBy('b.weight')
    ->orderBy('b.module')
    ->addTag('block_load')
    ->addTag('translatable')
    ->execute()
    ->fetchObject();

  if ($block) {
    $array = module_invoke($block->module, 'block_view', $block->delta);
    drupal_alter(array('block_view', "block_view_{$block->module}_{$block->delta}"), $array, $block);

    if (isset($array) && is_array($array)) {
      foreach ($array as $k => $v) {
        $block->$k = $v;
      }
    }

    if (isset($block->content) && $block->content) {
      // Normalize to the drupal_render() structure.
      if (is_string($block->content)) {
        $block->content = array('#markup' => $block->content);
      }

      print render($block->content);
    }
  }

You need to know the module implementing the block, and the delta used for that block. It is better to put the code in the preprocess function to set a variable that is then rendered in the template file. As usual, the logic code should be in the template.php file of the theme, or in the module file, and the rendering code in the template file. (Don't confuse the template.php file with the template file.)

Instead of executing that code, it is easier to assign the block you want to show in the taxonomy term page to taxonomy term pages. In the settings page for the block (admin/structure/block/manage/<block id>/form/configure) select Only the listed pages, and in the textarea enter:

  taxonomy/term
  taxonomy/term/*


Your code seems fine. Maybe you could add an additional condition to see if your role argument is proper:

$role_name = 'Role to add'; // The name of the role to add.
  if ($role = user_role_load_by_name($role_name)) {
    user_multiple_role_edit(array($user->uid), 'add_role', $role->rid);
  }

I would try adding this condition to make sure all arguments are as intended. Maybe 6 is not a valid index? With this extra condition you will be sure.

Hope this helps, cheers!


Issue with module's hook_uninstall (not uninstalling db entries)

% is used as the placeholder marker for D6 queries, so you need to escape it with another %:

db_query("DELETE FROM {date_format_types} WHERE type LIKE 'eventdates_custom_date_%%'");

As a test I just added the following to the date_format_types table:

And then ran this query from the devel/php page:

db_query("DELETE FROM {date_format_types} WHERE type LIKE 'eventdates_custom_date_%%'");

And both rows were deleted:


Can we output individual form items within a Layout?

That is not how you're supposed to use layout templates as those should be for for placing content, just like normal Drupal regions, and then modify the output using field and node templates. The general idea being to be able to reuse the templates in other places and as such reducing the number of templates needed.

Of course you can output content directly in the layout template. I would recommend you install the Twig Tweak module. You can then use {{ dd() }} to see what is available to you. As an example you can display a field value like this:

{{ node.field_myfield.value }}

It depends on what you want to display, but that's the general idea, very similar to the node template.


The coupon's applicability is tied to the discount. Use Commerce Discount and Commerce Discount Extra. Commerce Discount Extra provides an inline condition that lets you specify a user/role condition for an order, which is exactly what you want.


How to make view mode available only to selected bundle?

No, there is not. A view mode is not bundle-specific.

That hardly matters, because a view mode doesn't do anything unless you actually enable it and configure field formatters for it, resulting in a view display. If you don't then it just falls back to the default view display.


How to import/sync comments from Disqus into my drupal database?

here is some sandbox project for drupal 7, that import comments from disqus to drupal core comments


I get an exception when re-installing a module

What you have done in the first step is disabling the module, not uninstalling it. To uninstall it, you need to click on the "Uninstall" tab, select that module, and then click on the "Uninstall" button.

The exception raised from DatabaseSchema::createTable() is because it contains the following code.

  if ($this->tableExists($name)) {
    throw new DatabaseSchemaObjectExistsException(t('Table %name already exists.', array('%name' => $name)));
  }

The code in DatabaseSchema::tableExists() is then the following one.

  $condition = $this->buildTableNameCondition($table);
  $condition->compile($this->connection, $this);
  return (bool) $this->connection->query("SELECT 1 FROM information_schema.tables WHERE " . (string) $condition, $condition->arguments())->fetchField();

You could also manually remove the database table, but if the information about that table is still contained in information_schema.tables, DatabaseSchema::createTable() will raise an exception.


You dont necessary need the SSMTP module.

I think this is a bad configuration with your local environment. For testing purpose you should consider using Gmail.

  Debian/Ubuntu users can Install with this command or click here to
  open up apt:

  sudo apt-get install ssmtp

  We need to then need to edit, ‘/etc/ssmtp/ssmtp.conf’:

root=username@gmail.com mailhub=smtp.gmail.com:587 rewriteDomain= hostname=username@gmail.com UseSTARTTLS=YES AuthUser=username AuthPass=password FromLineOverride=YES

  Then add each account that you want to be able to send mail from by
  editing, ‘/etc/ssmtp/revaliases‘:

root:username@gmail.com:smtp.gmail.com:587
localusername:username@gmail.com:smtp.gmail.com:587

If you do not want to used Gmail here is another tutorial with an alternative Sendgrid.


How to allow users to attribute accumulating points to nodes?

Step 1 - Use the Flag module

I'd definitely use the Flag module for what you're trying to achieve. To allow authorized users (to use such flag) to flag relevant nodes. Maybe you want to limit them to only selected content types also.

Step 2 - Add a field to a Flag to specify the points

However, to also implement those points to nodes that get flagged, you should configure the flag (you only need 1 flag!) by attaching a field to such flag. Such field can then be used to enter, or select, any of the allowed values of points you want to be granted (appointed) to a node that gets flagged by such flag.

However when doing so, make sure to also be aware about (and do) what is described in Attaching fields to flags, i.e.:

  By default, Flags use the "JavaScript toggle" link-type. While this allows entities to be flagged without reloading the page, users cannot set any field values with the Flag. In order for users to set a Flag's field values, you must use the "Form" link type.

  Navigate to Administration > Structure > Flags page. Click the Edit link for the Flag. Scroll down to the Display Options box and select the Confirmation Form radio button.

Step 3 - Add some 'Total points' field to your nodes

Define some other field in the content types for the nodes you want to use these points for, which will contain the total number of points. And which will get updated each time a node gets flagged with '+X' (or '-Y') points, as explained in the next step.

Step 4 - Use the Rules module to maintain the value of the 'Total points'

The Rules module integrates extremely well with the Flag module. So it should be fairly simple to create a rule to maintain the value of the 'Total points'. Here is a blueprint (to avoid writing an entire manual ...) of this rule:

Rules Event: when a node is flagged (with the flag you created in step 1)
Rules Conditions: whatever you might need (if anything), on top of what is not yet covered by the way you configured the flag.
Rules Action(s): Perform some Rules Actions that use the value of the points as specified by the user who flagged the node, and then adds that to the current value of the 'Total points' field. For an example of such calculation, refer to this answer to the question about "How to add up all items of a field collection field using Rules?". In your case here, you don't need the 'loop' (you're not processing a field collection, only 2 fields for which you want to calculate the sum of it).

Summary

Using Flag (with 1 extra field) and Rules, and by adding a field (for 'Total points') to relevant content types, the above is how you can create something similar to what User Points can do, though with a summary like so:

  provides a technique an API for nodes users to gain or lose points for selected nodes performing certain actions on your site.

And btw ... zero custom code involved ...


How to set published status to a static value while importing a CSV using Feeds

Add a new column to your CSV, fill it with 0, and import that as Published Status.


How to delete a comment via an HTTP GET link in an email

This will do it.

Obviously you don't want to allow just anyone to delete any comment.

The authentication step is to require the user to be logged in with "administer comments" permission.

Alternatively, you could perhaps use a token in the querystring to check access to delete the comment.

/**
 * Implements hook_menu
 */
function MY_MODULE_menu() {

  $items['action/comment/%/delete'] = array(
    'title' => 'Delete comment',
    'page callback' => 'MY_MODULE_action_comment_delete',
    'page arguments' => array(2),
    'access arguments' => array('administer comments'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
 * Menu callback
 * Delete comment via GET request
 */
function MY_MODULE_action_comment_delete($cid){

  try{
    // Delete the comment
    comment_delete($cid);
    drupal_set_message(t('The comment and all its replies have been deleted.'));
    watchdog('MY_MODULE', 'Deleted comment @cid and its replies.', array('@cid' => $cid));
    // Clear the cache so an anonymous user sees that his comment was deleted.
    cache_clear_all();
  }catch(Exception $e){
    drupal_set_message(t('There was a problem deleting the comment.'));
    watchdog_exception('MY_MODULE', $e);
  }

}

The path to delete a comment would then be:

http://www.example.com/action/comment/12/delete

Where "12" is the comment cid.


Invalidate a specific cache tag on any saved taxonomy term

You don't invalidate entity tags, Drupal does this automatically on CRUD operations.

Instead add a cache tag to all nodes of the specific content type:

/**
 * Implements hook_preprocess_node()
 *
 */
function mymodule_preprocess_node(&$variables) {
  if ($variables['node']->getType() === 'my_content_type') {
    $variables['#cache']['tags'][] = 'taxonomy_term_list';
  }
}

The tag taxonomy_term_list gets invalidated on any taxonomy term saved/updated/deleted.


I ran into something similar recently, and I opted for the Block Reference module.

I created a new paragraph called Block Reference
Added a block reference field
Selected "system blocks" as being referable under the field settings
Selected the user login block

and wham bam thank you mam ive got a user login block in a paragraph.


With the core user profile you can have just one profile.

Profile2 gives you the permission to create different profile type and with the permission you can relate it to the role.
Every profile can have different fields.
Quick example:

Let's say you have a football website, so you have different profiles for different role player like goalkeeper wing, midfilder etc...

You create one profile per each role with different fields with Profile2
goalkeeper: height, gloves size etc...

Wing: first foot, side, speed etc...

You go to people->permission->role and you create a role per each role player and then you give the permission to a role for the related Profile so user with wing role can use the wing profile.

In the core user account you can create a field "Role player" (a radio button in this case is better)

Goal Keeper | Wing etc...

Then you will use "Rules" to create the rule

React on event = After saving a new user account

Condition = data comparision (you should look for you field "role player" in core user account)

Action = Add user role (you can select the relative role)

Automatically the role is assigned.


Drupal admin themeing and customizations

Use https://drupal.org/project/admin_views
Go edit a view and add a new display: block.
Register a new path in system:

a) using hook_menu in your custom module OR

b) using https://drupal.org/project/empty_page
Place that new created block in a region (edit also the paths where block should be displayed)
I'm not sure what you mean by WYSIWYG editor in content area - do you want to edit node or what?

a) If you used hook_menu, point its page callback into a function which returns WYSIWYG editor OR

b) If you used a empty_page you must create another block with editoror inside, and place it into content region


Change the number of returned results in a taxonomy item list?

The Views module has a default View for that page. If you enable it you can adjust it the way you want like you would normally do with Views.

Without Views: see comments.


Which tables can i share in multilingual multi-site installation?

As i understood you almost cant use common tables on multi-site installation - i`ve been checking them one by one. First i configured all of sites - only the main site (from which tables were shared) could switch languages and translate nodes. On the others there were no switcher showing and translated nodes were not linking.

Maybe you can some, but still you got to have everything identical (starting from content types and endind with nodes)

Maybe i am wrong.


How to change view's field (Custom-Text field specifically) value based on other field value using hook_view_pre_render?

You can't set a value for "nothing" aka "Global: Custom text" in hook_views_pre_render() because _entity is the entity object. The entity (Taxonomy Term in your case, and Node in my test case) does not contain this field.

Therefore, you need to use template_preprocess_views_view_field

function THENAME_preprocess_views_view_field(&$vars) {
  if(isset($vars['view']) && ($vars['view']->id() == 'test_view') && ($vars['view']->current_display == 'block_2')) {
    if (isset($vars['view']->field) && (count($vars['view']->field) > 0)) {
      if ($vars['field']->field == 'nothing') {
        $tid = $vars['row']->_entity->get('tid')->value; // get tid
        if ($vars['field']->field == 'nothing') {
          $vars['output'] = [
            '#markup' => "
This is my custom mark-up with term id: $tid
",
          ];
        }
      }
    }
  }
}


how to remove duplicate in view search API?

Depending on your setup there are different reasons why you can get duplicates. A common reason is, that you're using related entities (nodes, taxonomies). Let's say you got a content type car with a taxonomy term that shows the car's color. If you create a relationship between car and color in your view, you can see duplicates if a car has multiple colors.

There are three different options that allow you to reduce duplicates.

In the view's ADVANCED tab you can find USE AGGREGATION and QUERY SETTINGS. Try out which of them works for your use case.

Inside QUERY SETTINGS you can find the DISTINCT option.

If you enable USE AGGREGATION your fields and filters will receive a new option AGGREGATION SETTINGS where you can define the type of aggregation (ie. Group results, Minimum, Maximum, etc.)

When you add fields to your FILTER CRITERIA there is another setting to prevent duplicate entries when a filter is applies.

But beware, complex views tend to get slow when aggregation is enabled.


drupal 7, paths and urls are not working properly

Use the global variables for resolving the issue of path of files as below:

Use base_path if your fine with domain name not to be included:
It will return path respect to the drupal root.
Eg:  "/" for drupal root(http://localhost:81/my_website), and
"/images/header" for http://localhost:81/my_website/image/header/header

Example:

/*Assuming image path: http://localhost:81/my_website/image/header/headerR.png*/
global $base_path; /* will return "/" for http://localhost:81/my_website*/
$image_path = $base_path . 'image/header/headerR.png';

Note: Don't use trailing slash / for adding path of files with $base_path as it adds a "/" to the beginning and end of the returned path.
Use base_url if you want to get the full path: It will return
base URL of the Drupal installation.

Example:

/*Assuming image path: http://localhost:81/my_website/image/header/headerR.png*/
global $base_url; /* will return http://localhost:81/my_website in you case*/
$image_path = $base_url . '/image/header/headerR.png';


I think block_exclude_pages was created for these types of scenarios


When to use the Flag module versus a boolean field?

For this particular use case, you could go with the field. There is no need to install a contrib module for something that a field can do fine.

Flags create a new entity for each new flag you create. This adds an extra layer of complexity when you are need to migrate or deploy.

It would make sense to use flags, if for example, you wished that your each of your users could mark this article (eg mark it as favorite)

Drupal also offers the 'promote to front page' functionality that you could use.


You could use the Forena module to create a report using the data block that matches your "mock up query". While doing so, you could also use the WYSIWYG query writing facilities to further tune your query if needed (think of it as using PhpMyAdmin integrated within your Drupal site).

Visit the demo site samples for more details, and/or refer to 2 types of documentation that's available:

Community documentation, which includes a child page Video demos and tutorials.
Documentation that comes with Forena, which you can access right after install and enable of the module. Checkout the demo site for an online example of it.

Disclosure: I'm a (co-)maintainer of Forena.


The short answer is you can't do what you want, but there are other things you can do. You need to look into using the #ajax properties of form elements to submit data to the server when the customer clicks your button without initiating a POST redirect as you would for a full form submission.

However, that will still trigger a validation of the entire form, not just the pieces that you specifically want to validate. What Drupal allows you to do is limit validation errors from resulting in form errors when the form is rebuilt.

The topic is honestly a big bigger than can be answered here, but I hope this points you in the right direction. The best thing to do will be to investigate how a module with similar functionality achieves what it is you want to do and imitate the code (if it's up to date and / or well-maintained ; ).


Display custom field content in node.tpl

There are two parts in your problem: one is getting the values, and the second is themeing them.

As far as getting the values is concerned, if you don't mind using the Entity and File Entity modules, a simpler way to access field content is to use entity metadata wrappers. This way you don't need to worry about deltas and languages.

You can write code as follows:

$w = entity_metadata_wrapper('node', $node);
foreach ($w->field_objectif_bts->getIterator() as $file_w) {
  // $file_w->file returns the wrapper of the File entity. You can
  // then address it's values as:
  $name = $file_w->file->name->value();
  $mime = $file_w->file->mime->value();
  $custom_field = $file_w->file->field_custom_field->value();
  // etc. You can see all available fields by inspecting the
  // return value of $file_w->file->getPropertyInfo()
}

As far as themeing the table goes, I think your call to theme is correct (If unsure, you can check the documentation for theme_table)


Generating URLs with fromUri and the language prefix, base vs internal

Drupa8 - as a Symfony application - abstracts paths with routes. So paths may change, the route stays.
So the cited "The internal: scheme should be avoided except when processing actual user input that may or may not correspond to a Drupal route." means: If you can, use a route.
If you can not use routes, the right prefix for routed paths is internal:.
In contrast, base: was introduced for use cases like README.txt which is unknown to the symfony router and served directly by the web server.

You can find background in these issues, and help improve the docs:

Remove the base: scheme in favour of user-path:/internal: [#2422995] which concluded that we still need the base scheme
Evaluate and document each use of base: in core [#2417827] which then was started to at least document usages of the base scheme
Url::fromUri DocBlock does not mention base: and internal: custom schemes [#2877023] which is about improving the docs


How can I access the CiviCRM contact record 'group' value(s) of the current user?

You can even use 'email' api to get the contact id(as you have the email address in $GLOBALS['user']->mail) and then use 'GroupContact' api as above to get the groups record.

$result = civicrm_api3('Email', 'get', array(
  'sequential' => 1,
  'return' => "contact_id",
  'email' => $GLOBALS['user']->mail,
));


In webform, you can go to form settings, and in the advanced tab at the bottom, there is an option expose your form as a block.

Then go to structure > blocks and place the webform block on the page/region that you want.


Populate node image field with files submitted by webform?

Any issues with using: hook_webform_submission_insert and copy these images to current viewing node?

If node ID isn't available in webform submission, you can always put hidden field to webform with a NID.


How to prevent Migrate from creating null fields?

Apparently this feature was added to Migrate 2.6 and for now is available only when you're using dev version. For those who want to try it out, there is RC1 version available.

For older Migrate module versions, the empty field needs to be unset in prepare function, not inside prepareRow as the comment from drupal docs page suggested. Here is an example:

function prepare($entity, $row) {
  // Assuming that 'year' maps to 'field_year'
  if (!isset($row->year) || $row->year === null)
    unset($entity->field_year);

  // Assuming that 'gender' maps to 'field_gender'
  if (!isset($row->gender) || $row->gender === null)
    unset($entity->field_gender);
}

There is also a more "generic" solution prosed in one of the comments on drupal.org (pasting it here for future reference):

/**
 * Removes empty values prior to migrating.
 * @see http://drupal.org/node/1665332
 * @see http://drupal.org/node/1792894
 */
function mymodule_remove_empties($destination, $entity) {
  if ($destination instanceof MigrateDestinationEntity) {
    $entity_type = $destination->getEntityType();
    $form = $form_state = array();
    _field_invoke_default('submit', $entity_type, $entity, $form, $form_state);
  }
}

And in each of your Migrate classes:

public function prepare($entity, stdClass $source_row) {
  mymodule_remove_empties($this->destination, $entity);
}


How to place content/user field value inside of a rules action?

Have a look at issue # 430274, which somehow explains that "after saving something" actually happens ... "before saving something" (which is not a bug, simply how the Rules module works ...).
From the limited details provided in the question, it could well be that this also explains what causes your issue.

A possible compromise to avoid these kind of issues, is to transform relevant parts of what you're trying to do in your Rules Action(s) in a Rules Component, so that your Rule "schedules the execution" (using the Rules Scheduler submodule) of that Rules Component. For example after only a few seconds or minutes later on (if your cron job runs frequent enough, otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules Component is executed, the "Save of the entity" for sure completed, and updates will have been applied as expected.

PS: as an alternative, add an extra "save entity", after your first Rules Action (possibly that might be sufficent also).


I would add a node reference field to the content type you want to add a poll to, and choose the formatter that renders the referenced poll node (instead of rendering just a link). I must add that I never tried this with poll nodes, but I expect it to work just like it does with other nodes.


Not sure this would be the recommended way but I got it working using hook_form_alter. Customers start by filling their shipping address at step 1 (required) and on complete step, I grab this shipping address and copy it to the customer_information address field on guest registration, so the customers don't need to fill the same address again. In case the customer address would be different, it can be modified at this step.
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  // Commerce checkout form
  if ($form_id === 'commerce_checkout_flow_multistep_default') {

    // Multistep "complete" step
    if ($form['#step_id'] === 'complete') {

      // Get shipping address and copy it to customer profile address
      $profiles = $form_state->getFormObject()->getOrder()->collectProfiles();
      $shipping_address = $profiles['shipping']->address->getValue();
      $form['completion_register']['customer_profiles']['widget'][0]['entity']['address']['widget'][0]['address']['#default_value'] = reset($shipping_address);
    }
  }
}


Yes.

alias drush5='~/drush5/drush'
alias drush6='~/drush6/vendor/bin/drush'
alias drush7='~/drush7/vendor/bin/drush'
alias drush8='~/drush8/vendor/bin/drush'

You will get help from Switching Drush Versions.


The best way to store drupal Configuration

If you're literally looking for variable storage, then variable_set() and variable_get() are the way to go...during development.  However - that means the variables are stored in the DB rather than the file system which can make deployment a bit painful later on.  From your question, I assume this is what you are trying to avoid.

If you're looking to store sitewide configuration as opposed to just variables, then there are a couple of options.

Features

I know you said you don't want Features, but Features 2.x is actually a MASSIVE improvement over 1.x, so if you've not ooked at it for a while I'd suggest giving it another go.

Disclaimer: I love Features 2.x :-)

Configuration Management

Then there's Configuration Management which is an attempt at working some of the Drupal 8 CMI work to Drupal 7.  It's relatively easy to use, and also pretty easy to extend.

On another note; Clive is kind of a Configuration Management evangelist - so if you have any difficulties with it then you have a wealth of information here.

Manual

Lastly, you could create a custom module that implements default configuration hooks (such as hook_views_default_view or hook_default_rules_configuration).  A keen eye will notice that these hooks are a key element in getting configuration into Features :-)

Strongarm is also not dependent on Features, so you can utilise the Strongarm API yourself :)

Extra

I tend to use $conf[] in combination with a Git-excluded local.settings.php (see this question for a reason as to how and why) file for storing environment-specific configuration (such as site e-mail - things that might change between environment).


Administrator's approval required after published node has been edited

Use the Rules module to create a rule that sets a node to unpublished when it is saved. You might also want to have a look at the Moderate module.


I can't tell which element is giving you trouble.

For the div, instead of prefix/suffix you can create a container element:

$form['submit_container'] = array(
  '#type' => 'container',
  '#attributes' => array(
    'class' => ['modal-footer'],
  )
);

And then you can put a submit input inside of that:

$form['submit_container']['submit'] = array(
  '#type' => 'submit',
  '#value' => $this->t('Submit'),
  '#attributes' => array(
    'class' => ['btn', 'btn-sm', 'btn-default'],
    'data-dismiss' => 'modal',
  )
);

If you need a button type='button' just to fire Javascript and not submit the form, that is somewhat problematic, it seems. One method is to override the button template.

Type inline_template may be the best bet:

$form['submit_container']['button'] = array(
  '#type' => 'inline_template',
  '#template' => '<button type="button" class="btn btn-sm btn-default" data-dismiss="modal" onclick="closeButton()">Close</button>',
);

Change a normal submit 'input' type to 'button' type with button tag


Where is the Profile2 field data hiding?

Each profile type comes up as a second-level tab on the user edit page, like this (using admin theme):

'Parent Information' is a profile type, and the 'Account' link is for the normal edit page.

If those tabs are missing from your theme I'd have a look at page.tpl.php to make sure you're outputting the tabs correctly.


The short answer is: "yes, it is possible".

There may be different ways of approaching this, but one approach is to use some sort of URL rewriting (e.g. Apache RewriteRule) to let Drupal pick up the external xml file, and then have a custom module that picks up and parses the XML and programatically creates a node with this data stuffed into the appropriate fields and redirects the user to this node.

I've written a custom module for a client that does exactly what I describe above.


show archive block on every page containing certain content type

If you are using Drupal 7, you can go to Home » Administration » Structure » Blocks, and hit configure next to block you need:

In the Visibility settings section use Content types tab. In Drupal 8 it looked similar and probably will not change significantly.

The same functionality was backported to 5 and 6 by Block Node Visibility module.

If you don't want to install above module, and you're using Drupal 6, use Pages tab, and select last radio button "Pages on which this PHP code returns TRUE", and use code like:

<?php
// valid node id in view mode
if ( arg(0) == 'node' AND is_numeric(arg(1)) AND arg(2) == FALSE ) {

    $node = node_load(arg(1)); // cached

    if ( $node->type == 'insert type you want' ) {
        return TRUE;
    }
}

return FALSE;
?>

Code sample by bluesherpa from Drupal.org.


Is there a way to have a customized content add page form depending on who has logged in?

see this path on your drupal installation :

admin/people/permissions where admin had power to set accessbility of menus,content etc


What happens to a node/menu item once it's been deleted?

When you delete a node or a menu item you cannot restore it unless reverting the DB.

You can use revisions and published status in order to emulate the node deletion or you can try modules like Recover.


Retrieve Webform submission data from database

Easiest is probably to preprocess the webform's new submission, load the desired submission, and then pre-populate your fields. I doubt that this is built-in.
fe
<?php
function HOOK_webform_submission_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($form['#webform_id'] == 'your_webfom') {
    $form['elements']['your_element']['#default_value'] = $your_value;
  }
}

There may be several ways by not-coding, but using modules.
LMGTFY - https://www.drupal.org/forum/support/post-installation/2021-02-01/how-to-use-webforms-submissions-in-other-forms

Install the 'Webform Views Integration' module.
Create the view for display submissions of the 'Client' webform.
Add to the view the 'Entity Reference' display and add the 'Name' field (or any field you want to see on the 'Project' webform).
Click on the 'Settings' and check the field that will use for serach.
In the 'Client' webform select the following reference method: 'View: Filter by an entity reference view'.
Select the view created by you from the 'View used to select the entities' list.

The screenshots of the example:

https://ibb.co/ZJxgK9w
https://ibb.co/C6sxCFv
https://ibb.co/mFWDCTX
https://ibb.co/QcwYYm6


How to dynamically add css after image upload on node?

If you use drupal behaviors to modify the css, it should run after the ajax too.

eg.

(function ($) {
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.example', context).css('backgroud-color', '#ff0000');
    }
  };
})(jQuery);

More info at: http://drupal.org/node/756722


Form API: Form field not being translated

the field options are not going through the t function.

you would need to take each value from the following array and make it go through the t() function

$field['settings']['allowed_values'];

and please check that $info['label'] is a plain text and not an array.


Migrate module only imports first line of CSV file

It's possible that the CSV is saved with the wrong line endings. Try saving the CSV file with Unix-style line endings. By default, I believe Migrate expects a Unix format text file.


Force Rebuild of Custom Entity's Task Menu

After days of painful searching and reading code, I figured it out on my own. It was super easy once I got it. Since I am using a custom permissions handler to determine if a user should see an entity's task, I added cache tags to the AccessResult object that the custom handler returns:

$cache_tags = array('my_custom_entity_type:' . $my_custom_entity->id());

$access_forbidden = AccessResult::forbidden()->addCacheTags($cache_tags);

Later when my custom entity changes, I invalidate the tag(s) in the submitForm() function of my custom forms:

\Drupal\Core\Cache\Cache::invalidateTags(array('my_custom_entity_type:' . $my_custom_entity->id());


The development snapshot of Drupal causes error on my server

Apache 1.3, is considered deprecated. The very first thing I would try, is upgrading to a 2.* version, preferably 2.2, and try installing again with the standard .htaccess file. Given the enormous amount of apache servers running Drupal, the standard file should work.
What is the output of "cat /proc/sys/fs/file-nr"? That's useful for tracking down the to many open files issue, which likely is a server wide issue, and not really Drupal related.
While all patches to the 7 branch of core should pass all tests, it could be that you have stumbled on a broken commit. Why do you install -dev? Install 7.10 instead.


Content type or web form(creating own form using hooks) Which one is best way of collecting input from user?

If you dont want to make your hands dirty playing with code then better use webform module as per your drupal version.
Webform module  in drupal gives you everything, you dont need to make further queries to manage the input data, its just a use of normal CMS. Better try with that, an in addition you can export data as well.
I hope this helps you.
Thanks


How to create a default value for an entity base field in Drupal 8

The code is outdated, you should create a patch to fix it.

There is a new separate method for the default value, setDefaultValue().


applyUpdates() is deprecated. Is it really needed in hook_install() anyway?

The change record you've linked is about update hooks for already installed modules, not hook_install().

You've never needed applyUpdates() in an install hook. If your custom module is adding a new field, it will be added automatically when the module is enabled, and removed when the module is uninstalled. There was only an issue with base fields containing data, but this is resolved since Drupal 8.5. See this change record: Base fields with existing data can now be uninstalled.


Set and Get $form_state with ajax button submit function?

Should be:

public function customCallback(array &$form, FormStateInterface $form_state) {
  $list = $form_state->get('list');
  $form['fieldset']['list']['#description'] = $list;
  return $form['fieldset'];
}


How to send an email to the admin when user fails to login?

People mistype or use wrong alternate passwords all the time. Would be overkill to send e-mail on a first failed attempt.

For security reasons, Drupal blocks user account after 5 login failed attempts.

You can use Rules Block/Unblock User to send e-mail when user gets blocked. (failed 5 times)

  This module adds rules events, as well as some default rules, for when
  a user account is blocked or unblocked.


The email may not have been sent without any error at the Drupal end. I recently experienced this problem, and found that the mail server was rejecting emails sent "from" someone claiming to be the same host as itself.

In short, Drupal could successfully send the email without knowing that it wasn't received.

We solved the problem by installing the modules "mailsystem" and "mandrilL" and signing up for a free Mandrill account.


Is it possible to give inactive accounts a custom error message upon login?

You can alter the login form and add a custom validator where you check if user is blocked and show the error message you want.

If you check the code you'll see that login validator are set by the user_login_default_validators() function. Those validators are:

user_login_name_validate
user_login_authenticate_validate
user_login_final_validate

What I don't understand is why are you getting the "wrong username/password" (actually the message is "Sorry, unrecognized username or password. Have you forgotten your password?"). The first validator checks if the user is blocked:

/**
 * A FAPI validate handler. Sets an error if supplied username has been blocked.
 */
function user_login_name_validate($form, &$form_state) {
  if (!empty($form_state['values']['name']) && user_is_blocked($form_state['values']['name'])) {
    // Blocked in user administration.
    form_set_error('name', t('The username %name has not been activated or is blocked.', array('%name' => $form_state['values']['name'])));
  }
}

As you can see when a user is blocked the message es "The username %name has not been activated or is blocked".

Anyway, to achieve what you want I think you ca follow the steps:

Implement hook_form_FORM_ID_alter adding your custom validator as
FIRST validator. You have to alter two forms, 'user_login' and
'user_form_block' (tose are the form ids). Use:

array_unshift($form['#validate'], 'my_custom_user_validation');

to add your custom validator as first validator.

Then code your custom validator. It should be same as user_login_name_validate but using your custom message.

Edit: As I've pointed out in my answer and J. Reynolds says the blocked message is not the standard wrong user/password. If you get the blocked user message you can go with J. Reynolds suggestion (just altering the standard user blocked message). If you need to check for any other different condition (for example, blocked and spam role) you can use what I say in this answer.


If your meta tags aren't in your page source, search engines (and any other robots) won't be able to read them.

You should never have anything sensitive in meta tags anyway so trying to hide them doesn't really make sense.


You're looking for HTML Tidy module.

  This module tidies Drupal's HTML output with HTML Tidy by optionally
  sanitizing it when it is saved or when it is displayed, like a
  traditional input formatter. Missing and mis-ordered tag components
  are replaced and reordered automatically so that user input doesn't
  break site structure with open tags and the like.

  User interface configuration supports:

  Code indenting: Automatically format HTML for easier reading, or strip
  indenting for proper parsing and display in the less compliant
  browsers. Word wrapping: Automatically wrap lines in an intelligent
  fashion once they get to a specified length Info/Warning/Error
  information: Optionally appended to pages and includes details about
  the wrong HTML attributes and W3C validation info.


Redirect when translation of node is unavailable

I finally got it working with the Global Redirect Module

I had to enable the option Language Path Checking.

Then I got another problem with the redirects which was fixed by this patch:

https://www.drupal.org/node/1514166#comment-11657665


Drupal 7 submit function not called for themed form

You have the #disabled property set on your submit element. Drupal's form API does not process the input for any element, including submit buttons, if the #disabled property is set on the server side.

If you're interested in the code behind this, the decisions are made in the _form_builder_handle_input_element() function in the includes/form.inc file of your Drupal installation.

If you want the submit button to be disabled by default for client-side purposes (i.e. you'll be enabling it through JS based on some action taken by the user) you would be better off setting the disabled attribute directly on the element, as Drupal pays no attention to this when processing the form:

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
  '#attributes' => array(
    'style' => "padding: 0 10px;",
    'disabled' => 'disabled'
  )
);


How to normalize / resolve membership ID to all account UID per group_content

I was using extending Drupal\serialization\Normalizer\FieldItemNormalizer. I added this service extending
 Drupal\serialization\Normalizer\ContentEntityNormalizer to get the group id from group_content

  serializer.normalizer.group_content:
    class: Drupal\tam_api\Normalizer\GroupContentNormalizer
    arguments: ['@entity.manager']
    tags:
      - { name: normalizer, priority: 8 }

<?php
namespace Drupal\tam_api\Normalizer;

use Drupal\group\Entity\Group;
use Drupal\group\Entity\GroupContent;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Drupal\serialization\Normalizer\ContentEntityNormalizer;

class GroupContentNormalizer extends ContentEntityNormalizer implements NormalizerInterface {

  protected $supportedInterfaceOrClass = 'Drupal\group\Entity\GroupContent';
  const FORMAT = 'json';

  public function normalize($entity, $format = NULL, array $context = []) {

    $attributes = parent::normalize($entity, $format, $context);
    $gid = $attributes['gid'][0]['target_id'];

    $connection = \Drupal::database();
    $sql = "SELECT G.id as memberid, G.label, F.field_name_value, P.field_headshot_target_id as fid
            FROM group_content_field_data G LEFT JOIN group_content__field_name F
            ON F.entity_id = G.id
            LEFT JOIN group_content__field_headshot P
            ON P.entity_id = G.id
            WHERE G.type = 'groups-group_membership' AND P.deleted = 0 AND F.deleted = 0
            AND G.entity_id = :uid AND G.gid = :gid";

    $fields = ['uid', 'field_leaders', 'field_editors']; // my fields that need the membership data
    foreach($fields as $field_name) {
      if (isset($attributes[$field_name])) {
        foreach($attributes[$field_name] as &$entry) {
          $uid = $entry['target_id'];
          $membership =  $connection->query($sql, array(':uid'=>$uid, ':gid'=>$gid))->fetchAssoc();
          $entry['target_gc'] = intVal($membership['memberid']);
          if (!empty($membership['field_name_value'])) {
            $entry['target_label'] = $membership['field_name_value'];
          } else {
            $entry['target_label'] .= ' FALLBACK';
          }
          if (!empty($membership['fid'])) {
            $file = \Drupal\file\Entity\File::load($membership['fid']);
            if ($file->getSize() > 600000) {
              $entry['url'] = \Drupal\image\Entity\ImageStyle::load('medium')->buildUrl($file->getFileUri());
            } else {
              $entry['url'] = $file->url('canonical');
            }
          }
        }
      }
    }

    return $attributes;
  }

  public function supportsNormalization($data, $format = NULL) {
    return $format === static::FORMAT && $data instanceof \Drupal\group\Entity\GroupContent;
  }

}


Rules Comparison Operator Is Missing The Direct Input Method

The key to this problem was that the data comparison was actually comparing against a field belonging to an entity that was referenced to an entity that was referenced to the entity in question.  The structure was: Task -> Ticket -> Equipment: field-manufacturer.

The solution was to specifically declare the field in Rules using "Entity has field".  In this case, I was using two entity references, so I had to use "Entity has field" once to bridge to the first entity, twice to bridge to the second entity, and a third time to identify the particular field on that entity that I wanted to compare data against.

After I set the "Entity has field" conditions in place, I was able to compare data using "is one of" and it gave me a field to type in multiple TIDs.


Create a table with courses of a certain curriculum

Add a vocabulary for Curriculum List ,then  add Drupal 7, wordpress etc as terms in your vocabulary.

Create a content type for 'Courses'. Link your Curriculum List taxonomy to courses content type.

Then create view to list your taxonomy term and Total Credit Hours  with format as table.

Create another view to list all courses, with a 'contextual filters' as taxonomy term id.

Link your first Curriculum view's taxonomy term to the courses view , eg: courses/2 where

courses is your course views display path and 2 is the term id.


From the libraries/openid-selector/README.txt:

  how to plug-in facebook provider
  put the following code in providers_large or providers_small:

facebook = {
     name: 'Facebook',
     url: "javascript:facebook_click();"
}

  where facebook_click is something like:

function facebook_click() {
      $('#<id of html fbconnect element>').click();
}

  the same mechanism also applies if you want to plug-in any oauth or xauth provider

So that is what the README says. I specifically had to do the following I'm using Drupal7.8 with openid-selector module 7.x-3.x (2011 May 07):

In modules/openid_selector/openid_selector_fb.js:
Replace the chunks that look like similar with the ones Ive posted.

providers_large.facebook = {
  name: 'Facebook',
  url: "javascript: $('.fb_button').click();"
};

and again for this chunk

Drupal.behaviors.openid_selector_fb = { attach: function (context) {
  $('.fb_user-login-button-wrapper').hide();
}}


Try
function HOOK_link_alter(&$variables) or function HOOK_preprocess_menu(&$variables)
Or just override the menu template (menu--main.html.twig) and replace line
{{ link(item.title, item.url, {'class': link_classes}) }}
with
{{ link(item.title, item.url, item.attributes.addClass(link_classes).setAttribute('itemprop', 'url') }}


Display two Views blocks with equal height

Try using the equal heights module

  This module implements a jQuery Equal Heights plugin that can equalize
  the height of the elements of the specified class.

  To use it, give the elements the same class, then go to the
  administration interface and add this class (separate multiple classes
  by a space). By default, it sets the height to the height of the
  tallest element but you can also specify minimum and maximum height.

To use the just give both the blocks the same class and add the admin name in the admin interface of the module and then js will do the rest.


db_add_unique_key() is the function you're looking for.


Check the following:

What version are you using? There was an issue with Fields and alpha 2.
Are the libraries downloaded to the correct location? Check the project page for instructions.
If the libraries are there, does the webserver user have permission to read the libraries?


If you look at the of baseFieldDefinitions method in class Term:

Here is a list of fields you can set in create Term:

tid : Term ID
uuid : The term UUID.
vid: The vocabulary to which the term is assigned.
langcode : The term language code.
name : Name of term.
description : description of term
weight : weight of term.
parent : Term parent.

Example:

$term = Term::create([
    'name' => 'term name',
    'vid' => 'tags',
    'status' => 1,
    'tid' => 13,
    'uuid' => 1,
    'langcode' => 'en',
    'description' => 'tags description',
    'weight' => -12,
    //'parent' => parent tid
  ]);
  $term->save();


Is there an existing "pin" login module?

I'm not aware of any module that does this itself. There are some pin-related modules, but most of them are related to using 2-factor authentication authentication.

Is a pin field actually useful to improve security?

My sense is that adding a pin would not be worth it.

First, pins are easily guessed: this article on commonly used pins shows how only 20 pins would break over 26% of accounts!

Second, if you were to just require the pin to be on the end of the password that actually makes it harder to break than making it a separate field because they would both need to be cracked at the same time rather than serially. That is in addition to the problem above of pins not being well distributed among the 10^4 potential combinations.

Third, you would have to build, audit, and then maintain this additional code for managing per user pins. That's a new database table, some form fields, and at least a few hundred lines of code that can be buggy that overall adds very little extra security.

Alternate improvements to login security

So, I have some other suggestions on how to improve login security in general:

Security Review offers brute force detection.
You could use one of the 2-factor authentication modules. My favorite way to do that is the tfa module which is the module deployed on drupal.org.
You could use a module to improve true password strength (vs. password policies that usually promote nonsense).


add variable to process_page($vars) in form function

It seems to me that you are talking about two different things: altering form fields vs. modifying the $variables array in page.tpl.php.

1) When you say "form creation function", what I hear is that you want to change fields in an existing form. For this, you would want to implement hook_form_alter(). If you want to learn more about how to structure a form, visit the Form Generation page in the Drupal API.

2) If actually you meant that you want to add or change variables in your page.tpl.php file, then you'll want to implement hook_preprocess_page().


Node Add / Edit Options Vertical Tab Problem

Here is a series of things I would try. Check tabs after each test.

Try with a different browser.
Flush all caches (that one often solves a lot of problems).
Put your site in maintenance mode and Run updates (update.php).
Disable the Overlay module.
Disable all modules. Flush all caches. Re-enable all modules.
Update to the latest version of core if you can (currently 7.22).

Number 5 is a bit time consuming but it has solved issues for me in the past. First, make a list of all enabled modules. I do this with screen captures. Second, start disabling modules (except maybe Admin menu). You won't be able to disable all modules at once. It may take half a dozen Save configuration to completely disable all modules. When done, Flush all caches and while you're at it, clear your browser's cache too. Finally, re-enable all required modules. Run updates. Run cron. Flush all caches.

Hope this helps.


Empty title on one View based on Taxonomy Terms

Ok I found the answer (might not be the right answer but it's working).  I changed the "title" section in the View to %1 %2 and it started pulling from the metatag title section in each taxonomy term.


Add link that performs database function

There are two separate things to take care here, one is dealing with the database table, you will find all the functions you need to use for CRUD operations on databases here.

The other issue is dealing with the table showed on the browser page, if you want to operate with tables your best bet (IMHO) is to use Ctools, install  it and enable the Ctools Ajax example submodule, there you will find exactly what you want, a link that removes the file.

Hope this helps.


Pagination for image field in one node page

You can use the CCK Pager project.

  CCK Pager allows to page the item list of any CCK field with multiple values.

  The module extends others CCK formatter by paging the field item list; setting the number of elements per page and pager type (full or mini) can be made per field.
  It only works with versions of CCK >= 6.x-2.5.

Look at this demonstration, and if you are using Drupal 7, follow the status of these issues.


How do I display all the nodes in an organic group?

Here's how you can do it with views in Drupal 7.  Create a new view of nodes as you normally would, but make sure you set up the appropriate relationship for it that will allow you to filter your nodes based on their group membership:

Add a relationship (under the 'Advanced' section of the view)
Select the 'OG membership: OG membership from Node' field, which is under the 'OG membership' section of the fields

Mark this as a required relationship on the next screen if you don't want to include nodes/content that do not have a group
Only after you've added that relationship will you be able to see the appropriate 'Group id' filter.  Go ahead and add a 'Contextual filter', also under the 'Advanced' section and select 'OG membership: Group ID'.

This filter will now allow you to input the Group Id as a filter to the view through the URL (test it with www.[your site].com/[your view path]/[group id]) or by figuring out which group you're currently in if you set the following screen properly for the contextual filter

You can now test this in the view preview pane by entering in different OG id's and seeing that it should filter the list of nodes to ones only with those Groups set as their audience.

Let us know if this worked for you!!


How to remove unused files from directories

I found this post https://drupal.org/node/733258... may help...

The main purpose talked in this issue is about removing the images which doesn't have any use directly from database via SQL queries.

Audit files module is suggested as a good start (because doesn't delete files) to find files which are unused.

This code snippet is one of the suggested solution from the issue :

<?php
//db_query to find all files not attached to a node:
$result = db_query("SELECT fid FROM file_managed WHERE NOT EXISTS (SELECT * FROM file_usage WHERE file_managed.fid = file_usage.fid) ");

//Delete file & database entry
for ($i = 1; $i <= $result->rowCount(); $i++) {
  $record = $result->fetchObject();
  $file = file_load($record->fid);
  if ($file != NULL) {
    file_delete($file);
  } }
?>


White screen error when migrating between servers

Issue solved.

I had not disabled all of the date sub-modules (Thanks Molot for making me double check this). I ensured they were all disabled, cleared caches and was then able to export the database and import it on the new server.

I did get some errors on the new install. Running update allowed me to see that workflow needed updating. Updating workflow and ensuring the right sub-modules were installed (You can't run Workflow Node and Workflow Field at the same time) fixed the other errors.

I was then able to re-enable the date module.


Alter a field by select list in entity form

A good place to start is the aJax example module, and specifically the dependant example.

In that example, the seconds list is updated when the first list is changed, and it's value it updated according to its helper function _ajax_example_get_second_dropdown_options($selected) which is passed the value of the first list.

You could do something similar except use a simple text field for the second field but place the helper function on default value or value :

'#default_value' => _ajax_myentityfieldquery($selected),

and in the helper _ajax_myentityfieldquery return the result of your EntityFieldQuery function.


PDOException : SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'registration

If anyone stumble on this error again, note that it is due to corruption in the database. In this case, the registration tables got corrupted at some point.

Just unninstall everything registration related, and start anew.

Thx.