Articles listed in order base upon "Last-edit Date" instead of "Publishing Date"

By your description, it seems to me that there's some code in your theme implementing a views hook or a theme hook, and doing a custom ordering before rendering the results (either altering the query, or altering the results after the query). The following hooks could do that:

hook_views_pre_execute()
hook_views_post_execute()
hook_views_pre_render()

plus the theme_preprocess_views_view()

I'd suggest having a look at the theme to see if any of those is implemented, and is getting in the way.


Pass the id of one node by url for new node

One easy way to do this is with the module

nodereference_url

  The Node Reference URL Widget module adds a new widget to the Node
  Reference field type. It auto-populates a node reference field with a
  value from the URL, and does not allow this value to be changed once
  set. It can automatically provide a link on the referencing node
  types, that will contain the proper URL to prepopulate the field.


Usually there is always a module that can help out.

In your case I recommend Path Redirect Import. It has a bulk import mechanism for redirects via CSV. It supports the Drupal 7 redirect module.

To get the redirects exported from D6 in the right format, check the Path Redirect Export module.

I believe that should do the trick for you.

I hope this helps you.


You can use the Context module to set the block active on content types and url wildcards (ex. /event/*). There are also much more conditions available with Context.


If you read the Drupal compatibility table in the docs, you'll see that the correct version for Drupal 7 is Drush 8. The installation instructions for Drush 8 are simple and clear, no Composer required - just download a phar file.

PS! If you are planning on maintaining Drupal 8 sites (with Drush 9) too, I recommend getting Drush Launcher.


How do you programmatically create a webform with a managed_file type?

Making a couple of leaps here:

I couldn't find a D8 release for Webform so assuming D7
I'm assuming by managed_file (which is a FAPI element type) you mean a field API file field, as you mentioned making it accept multiple files (which the managed_file element doesn't have any support for).

So with those in mind...

Webform implements its own set of components, of which file is one type; it doesn't use the field API, so unfortunately you can't attach field API fields of any type to it.

The out-of-the-box file component doesn't support multiple uploads, but there's a contributed module, Webform Multiple File, which does:

  Module Webform Multiple File provides new Webform component for multiple file uploading. The module based on principles of file field widget and has similar design.


You can build your query while looping through each keyword and adding this as an OR condition.

$db_or = db_or();
$query = db_select('my_table', 'mt');
$query->fields('mt');

foreach ($keywords as $keyword) {
    $db_or->condition('my_column', '%' . db_like($keyword) . '%', 'LIKE');
}

$query->condition($db_or);
$results = $query->execute()->fetchAllKeyed();


How do I alter a field content before saving the form?

You can do it inside a hook_form_alter in a custom module.

function module_name_form_alter(&$form, &$form_state, $form_id){
  if($form_id == 'your-form-id'){
    if(your conditions){ // single or multipe if condtions based on your requirement.
     $value = 'value based on your condition';// your value based on condition.
    }
   $form['your-field-name']['language'][0]['value'] = $value;
  }
}

Hope this will help you


Yes there is: it's a two or three step process, but automatable.

Step 1) Create a Drush alias, or in Aegir terminology, 'context' for the site using drush provision-save (arguments)

Step 2) Install the site using drush @(site context name goes here) provision-install

Step 3) (optional but recommended) Verify the platform in the Aegir interface to have it automatically detect the site and 'import' it into the frontend so that you can do other things to it later via the web interface. You can also run this verification from the command-line with drush @hostmaster hosting-task @(platform context name goes here) verify

For specifics on the syntax of provision-save etc, see my article, "Manage your Aegir system from the command line": http://mig5.net/content/manage-your-aegir-system-command-line.


What is the difference between hidden and value types in form API?

With the hidden form element, the HTML output in the form is <input type="hidden" /> (plus other HTML attributes), while with the value form element nothing is output for the form. The value is simply kept in the cache Drupal uses for forms created with the form API, but nothing is sent to the browser. (In other words, the value is kept on the server side.)

Generally, the "hidden" form element is used when the value is used from JavaScript code, but it is not a value editable, or visible in the form.


Using Views Slideshow to display images with specific url links

As pointed out by @Clive and @loolooyyyy in the comments, the problem here is that there were multiple images on a single node.  Best practice (and problems like this one) dictate that there should be one node per slide.

Answered to remove this post from 'unanswered' list, all credit goes to the commenters who were here long before me.


Views Geolocation field proximity: How to alter views field setting

Digging through the exported views.yml config helped me to get on the right track:

function MYMODULE_views_pre_view($view, $display_id, &$args) {

  if ($view->id() == 'WHATEVER' and $display_id == 'MY_DISPLAY') {
    $allFields = $view->display_handler->getOption('fields');

    $user = _MY_BUSINESS_LOGIC();
    if (!$user->get('field_geo')->isEmpty()) {
      $allFields ['field_geo_proximity']['proximity_lat'] = $user->get('field_geo')->lat;
      $allFields ['field_geo_proximity']['proximity_lng'] = $user->get('field_geo')->lng;
      $view->display_handler->overrideOption('fields', $allFields);
    }
  }
}


How do I properly add a custom source for RSS feed import?

The RSS/Atom parsers only work with predefined sources. The custom sources in this case are only useful when using them in combination with Feeds Tamper (or alike).

If you want more control about selecting data from a XML file, try the XML parser from Feeds extensible parsers instead. With that parser, you can select data from a XML file using XPath queries. So you are free to select about anything from a XML file.
It would be good idea to learn more about XPath before using the XML parser. I think that the XPath tutorial from W3Schools is a good resource for this.


How can I view & access all available variables for a Drupal Commerce cart?

You can use the function commerce_cart_order_load & commerce_line_item_load() to load the current order(cart) object & order product objects respectively:

  global $user;
  $order = commerce_cart_order_load($user->uid);
  $cart_items = array();
  foreach ($order->commerce_line_items[LANGUAGE_NONE] as $line_item) {
    $cart_items[] = commerce_line_item_load($line_item['line_item_id']);
  }

In this example, $order contains the Commerce order(cart) object for the current user & $cart_items contain an array of line item (order products) objects.


Error: Syntax error, unrecognized expression:

I had using jQuery 1.9. I changed it to 2.1 and the problem is solved (jquery_update module)


How to configure Views to determine pages never visited by anonymous users?

You may want to use the Flag, Rules and Views modules, as further detailed below ...

Step 1

Enable the Flag module, and create a global flag which you label something like "Visited by an anonymous user".

That way, later on, any node that is NOT flagged by this flag, is one of the  nodes that your question is about.

Step 2

Enable the Rules module, and create a custom rule that looks like so:

Rules Event: Content is viewed.
Rules Condition: Current user has role "anonymous".
Rules Action(s): Flag the node being viewed (using the flag from Step 1).

Step 3

Enable the Views module, and create a view of all nodes that are NOT flagged. Those are the nodes that have not been visited at least once by an anonymous user.

Step 4

After you complete (implement) the previous steps, the (Views) results you get are correct as of the date you completed the previous steps. If you do have some type of historical (logging) information available about anonymous users visiting nodes, it would be a matter of using that information to also "flag" those nodes, so that your (Views) results would become more accurate/complete. And if you can make that info available in the format of some view, you could use the Views Bulk Operations (VBO) module, combined with another custom rule to also flag those nodes.


Add comma in between the Tags Display in Drupal 7

For anyone who needs to do this in the future:

div.field-name-field-tags div.field-items div:after {
  content: ", ";
}

div.field-name-field-tags div.field-items div:last-child:after {
  content: "";
}


Trying to use EntityFieldQuery to find all nodes with a node reference field not set

As crazy as it might sound, you can't. Normally you'd use the IS NULL operator to do this but it is apparently not supported by EntityFieldQuery:

EntityFieldQuery does not support isNull or isNotNull

Also I think the EntityFieldQuery internally uses INNER JOIN, rather than LEFT JOIN so records that don't have a value in your condition table would be excluded from the query results anyway. The issue has been reported several times:

EntityFieldQuery doesn't support query for entities without a value for a specific field
EntityFieldQuery doesn't support query for entities without a value for a specific field (duplicate)
In field_sql_storage_field_storage_query, any condition on a field's column excludes entities with a NULL value for this column


How to check if this page is user Profile Page

Anywhere in code, you can use code like that:

if (    arg(0) == 'user' // test if you are on user page
    and is_numeric(arg(1)) // and if user ID was provided and is possibly valid (a number)
    and arg(2) == FALSE // and there is no /edit or /delete added
) {
  // Do something
}

Substitute 'user' with any name provided by module, if you are using alternative user profile module.


Where is the code of a new view i've created?

If you click on the Theming link in the Advanced tab, you will get a list of possible template files that you can use. See here:

Next, you can click on "Display Output" to get a copy of the PHP that is powering the view. See here:

Copy that PHP into a file and save it using the naming pattern of your choice from the list beside "Display Output".

Click on "Rescan template files" to make your theme aware of the new template.

Now, any changes you make to that template - add CSS classes, etc - will automatically be picked up.

If you wish to edit HTML for the style or row, just click on the relevant "Style Output" or "Row Style Output" link instead of "Display Output".

I hope this helps you.


Create a Modal to Add new fields dynamically

I am not sure how this can be done entirely with Webforms. One option is to include in this webform all necessary fields, including the ones that would appear as a modal dialog. Even better, group these as a fieldset.

Then in a custom module or theme include some jQuery logic with which would be very easy to create a modal dialog in the same page. There is a dialog widget in jQuery UI and this is a relevant question in SO.


White Screen of Death on Cron, fixed with update.php

Looks like an issue with either a theme hook implementation, or call to a theme function. In particular seems related to theme_block

While it could be something else, I'd suggest making sure you have the file block.tpl.php in your base and sub-theme directories and then clear cache.

Other possibilities are a file permission issue, make sure the files are readable by the webserver


Multiselect values not getting saved in hook_settings()?

1) If variable_get('post_type_unique_serial') returns an array to populate the options, then it can not also be used for setting the default value, as this should be a single key within the array.

2) Generally it is good practice to use the same name for the variable as the form element if it is being used to set the default value eg $form['MYMODULE']['post_type'] and '#default_value' => variable_get('post_type'),


Views Module: Related Content by Title Only

The way I achieved this was by using the Apache Solr module https://drupal.org/project/apachesolr

It has a "More Like This" feature that makes it easy to show related content, see the documentation for that module.


Relationship between node and other nodes related by node reference to same parent

Start with a view that lists Content of type video.

In the ENTITY CONTENT SETTINGS use:

Entity type: Node
Bundles: Video
Arguments: Use the ID of the entity the view is attached to.

This adds the EVA field to all nodes of type Video and provide the node id to Views. I suppose you have gotten about this far.

Now add a contextual filter to the View, and choose the Content: nid. This value will be populated by EVA as just specified in the arguments. This makes the view aware of the node we are currently viewing. If you want to hide the current node from the playlist, you can select exclude hidden behind the more fieldgroup.

Then add a relationships from the playlist back to the video called Entity Reference: Referencing entity.

This includes all other video nodes associated with the same playlist in the view.

As you can see in my preview, when I view Video 1 (node id 2 because 1 was for the playlist), I see the other 2 videos in the playlist (I chose to hide the current node in the contextual filter).

If you DO want to include the current video in the view (you left exclude unchecked) it becomes a bit more complicated as you will need to use an extra relation: Entity Reference: Referenced entity. Then alter the other reference to use the reference of this one (you might have to change the order).

Then make sure all your fields and filter make use of the last relationship, so they display the title of the attached nodes and not the title of the initial node. It should look something like this:


I found a solution myself.

The problem is that Drupal's mail system converts HTML to plain text, and therefore strips all HTML tags.

A workaround to this is to replace all < and > characters with their unicode string and send the mail as text/plain.

I did like this:

$mail_message = [
  '#type' => 'theme',
  '#theme' => 'my_module_xml_mail',
  '#name' => 'Name',
  '#phone' => 'Phone',
  '#email' => 'E-mail',
];

$rendered = \Drupal::service('renderer')->render($mail_message);

\Drupal::service('plugin.manager.mail')->mail('my_module', 'xml_mail', 'test@example.com', 'en', [
  'message' => str_replace(['<', '>'], ['&#60;', '&#62;'], $rendered->__toString()),
]);


Unable to create multi-site sub-directory in drupal

You don't need to alter the hosts file if you don't care about serving on more than one address. If you have an Apache vhost entry for 127.0.0.1/localhost (you will by default, and I think Apache will add a hosts entry for 127.0.0.1) then if you have a public_html dir at mysite you can just dump any number of Drupal installs under that dir.

E.g.
/home/niklp/public_html/index.html <- get this working, then you can do:
/home/niklp/public_html/drupal1
...
/home/niklp/public_html/drupalx

Sorry if this is a little vague but it's not a Drupal issue, it's an Apache config thing that should be easily resolved.

Edit: you will have a billion less issues if you get off windows and onto linux even for basic setups.


Generate image styles on upload or in some other memory-conscious fashion?

I don't like the "lazy" image style generation either. After I imported 100,000 photos I batch created image styles for all of them. I just looped over each image and created the 5 or 6 styles for each image.

I noticed that there isn't a big penalty for looping over images that already have all image styles generated. So you could just run a cron, say every hour, that loops over all images created or updated within the last hour (or two to be save) and create the image styles.

I used something like this to generate the image styles, just select which ones should get generated:

    foreach(image_styles() as $style) {
        if ($style['name'] = 'thumbnail' || $style['name'] = 'medium'){
            $dest = image_style_path($style['name'], $uri);
            print ' '.$style['name']. ', ';
            if (!file_exists($dest)) {
                image_style_create_derivative($style, $uri, $dest);
            }
        }
}

You'll just need to $uri variable, in my case I get it directly from the file_managed table since I ran a batch job.


HTML5 web app: How do I create a dynamic manifest file with drupal?

images should be attached to content via image field(if not I know another way, just ask), so you can create a new views and fetch only these images

add page display to that views and use it to create manifest, in this way you have dynamic manifest. if you want write it to file, small module is needed.

in this case you need have more than one manifest (multiple manifest), one of them is for your images

steps to create images manifest:

create views to fetch images: named manifest_1
create page display in that views: named page_1
create a small module to create your manifest, dirty sample:

function mymodule_menu() {
  return array(
      'manifest/images' => array(
          'page callback' => 'mymodule_manifest',
          'access arguments' => array('access content'),
          'type' => MENU_CALLBACK,
      )
  );
}

function mymodule_manifest() {
  $images = views_get_view_result('manifest_1', 'page_1');
  //sent header text/manifest
  //output image paths
  die();
}


Access callback for user/%user/edit menu item not working

Ok, it appears I have to set the access as per following:

function si_dashboard_menu_alter(&$items) {
  $items['user/%user/edit']['access callback'] = 'user_access';
  $items['user/%user/edit']['access arguments'] = array('edit account');
}


How to make friends ajax with dynamically created links?

I found solution, for loading balloons I use module IP Geolocation Views & Maps it has js file ip_geoloc_leaflet_goto_content_on_click.js
where I add line Drupal.attachBehaviors();
Now it works as designed.

jQuery(document).bind('leaflet.feature', function(event, marker, feature) {
  // marker is the feature just added to the map, it could be a polygon too.
  // feature.feature_id is the node ID, as set by ip_geoloc_plugin_style_leaflet.inc
  // Need to set this up for code below.
  // The same code is used for cross-highlighting. See ip_geoloc_leaflet_sync_content.js
  if (feature.feature_id) {
    marker.feature_id = feature.feature_id;
  }
});

jQuery(document).bind('leaflet.map', function(event, map, lMap) {

  if (map.settings.gotoContentOnClick) {
    for (var leaflet_id in lMap._layers) {
      lMap._layers[leaflet_id].on('click', function(e) {
        var id = e.target ? e.target.feature_id : null;
        if (!id && e.layer) id = e.layer.feature_id;
        if (id) {
            //document.location.href = Drupal.settings.basePath + 'node/' + id;
            document.location.href = Drupal.settings.basePath + 'load_node/' + id;
        }
      });
    }
  }
  if (map.settings.openBalloonsOnHover) {
    for (var leaflet_id in lMap._layers) {
      lMap._layers[leaflet_id].on('mouseover', function(e) {
        this.openPopup();
         Drupal.attachBehaviors(); <<<<--------ADDED LINE
      });
    }
  }

});


Is it possible to count sub-items in view in Drupal 7?

In views, there is an one field called global counter. Render it and it will give you the count. If you wish you could also hide it via display setting.


How do I access field variables directly in Drupal 7 without having to drill down into a node array?

There are two main methods:

Procedural, using field_get_items(), e.g.

$node = menu_get_object();
if ($items = field_get_items('node', $node, 'field_device_type_vocabulary')) {
  $tid = $items[0]['tid'];
}

Objected oriented, using an EntityMetadataWrapper, e.g.

$node = menu_get_object();
$wrapper = entity_metadata_wrapper('node', $node);
$tid = $wrapper->field_device_type_vocabulary[0]->tid->value();


How to configure edit permissions for Panel panes?

That blog post doesn't seem to have been followed up on.  There is some discussion here regarding more granular permissions for Panels IPE:

https://www.drupal.org/node/1821618#comment-9502245

I mention it would be great to be able to change role permissions for an individual pane such as 'Move', 'Edit', 'Change Style'.


User warning: Incorrect key file for table

Two quick things you can try.

First, make sure the disk on your server isn't full.  MySQL can behave very weirdly when this happens.

Second, take a backup of your database (like with Backup and Migrate).  Then, from mysql CLI, MySQL Query Browser, or something similar do

CHECK TABLE watchdog;

and see if there is anything weird.  If so, you can do

REPAIR TABLE watchdog;

The MySQL docs will have more info on CHECK TABLE and REPAIR TABLE.

Sometimes, though, when a database gets wonky it is just best to restore a backup and move on.


Programmatically loading Custom block in page/node preprocessor

I think the problem here is that Drupal 8 has both block definitions (a.k.a. plugins) and block instances.  Both of which tend to be called blocks.  What is listed in the custom block library is a block definition. This is like what is done when a block is created with code.  It define the block but not the configuration.

An instance is the configuration data for a block.  It has the settings for a specific block.  E.g., title override, display title, region, and the like.

So, you are trying to render the block definition with code that requires an instance block.

How do you get an instance of a block to render?  The simplest way is to create a hidden region in your theme by adding a region line in the info file.  Something like "Hidden Blocks".

Add your custom (or code based) blocks to this region in the block placement screen.  I also tend to set the rules for where this can be displayed just to help keep these from being generated when not needed.

Once you do this, you should be able to render using the block id from the placement screen.  Note this can be different from the plug-in id on the custom block page if you have placed it more than one.


How do I associate multiple nodes to a user?

There is a module for handling relationships between entities for Drupal 7 which shows great promise called relation. At the current time it's still in alpha and I haven't tested it out for a while, so I am not sure where it is at. When I last tried it out, it wasn't quite suitable.

A more stable version which could be made obsolete by the relation module is the references module, which is a port of the Drupal 6 CCK node reference field. I've used that with great success.


Custom validator for checking if fields match

I'm not sure if constraints is the best way to go when you need access to two fields. In your form alter, could you add a custom validation method? That way you would have access to array &$form, FormStateInterface $form_state giving you access to all fields.

$form['#validate'][] = 'my_test_validate';

And then your validation function...

/**
 * {@inheritdoc}
 */
function my_test_validate(array &$form, FormStateInterface $form_state) {
  // Do what you need to do here...
}


Contact Us works on local machine, but not on bluehost.com

Installing the SMTP module and configuring it correctly was the solution to the problem. Since I am a newbie to Drupal it seems magical that it solved the problem. I don't fully understand the logic flow of SMTP and SimpleNewsletter.

It took three different chats with bluehost before I got SMTP configured correctly.

Following are the SMTP parameters that finally worked. The email address in Home » Administration » Configuration » System - Site Information also was incorrect. I set it to admin@columbiablooms.org and everything finally worked. The admin@columbiablooms.org email address had to first be created via cpanel at bluehost. The password in the screenshots below is the one that I used when I created the email address at bluehost.

I hope all this helps another newbie ...


Problem changing language - Redirection to installation

Increase the size of max_allowed_packet = 16M in the my.cnf file of mysql


Need to filter events from the current week only

Views can do this.

Add a contextual filter for the date field you're trying to filter. In the "Preview with contextual filters" box, you will be able to specify something like "2012-W34" (Edit: or any other valid date format for that matter) to say year 2012 on week 34. Use PHP's date() function to retrieve the current week and pass that as an argument to your view. This will give you your current week while avoiding current day +/- 7 days.

Edit: When passing the argument to your view, be sure it's a string in the date format and not just a week number.


How do I add social bookmarking icons to my site that only load or look for javascript only when executed?

Had this same issue on a site when using the Addthis widget and its probably similar for most sharing situations. We tried the addthis module but were also concerned about the overhead involved with loading the module and adding this on every page. We only wanted this to appear on blog posts so we wrote a simple preprocess_node hook to our module, ex:

if ($vars['type'] == 'blog_post') {

    drupal_add_js('http://addthis.com/<script-link-here>.js', 'external');

}

And then added our specific call to AddThis in our blog post template. You could also add the script tag in your template as well but its not best practice and wouldn't get cached as well as if its done through drupal_add_js.

We considered caching the addthis file locally (which is allowed for by addthis) but resolved that it would be better performance-wise to shift the external load to their servers rather than adding another file hit to ours. This page may also be helpful for addressing performance concerns (for AddThis).


I think you want to do something like this?...

http://vimeo.com/79462942

I did this with some jQuery and CSS.

jQuery to create and place "button" - in my case, this is a font-awesome icon. This may seem strange, but we're placing the button inside the div.tabs tag, and then placing div.tabs tag inside the h1 tag...

// edit node buttons
(function($){
    // wait til everything loads before firing
    $(document).ready(function(){
        //insert edit icon into div.tabs
        $('div.tabs').prepend($("<i class=\"icon-edit\"></i>"));
        //insert div.tabs into page title
        $('h1').prepend($('div.tabs'));
    });
})(jQuery);

Now, if this is all we did, it would look crazy! We need CSS to do the magic part...

/*first we hide div.tabs, but we also define properties for when we expose it later*/
    div.tabs ul {
    display:none;
    position:absolute;
    padding:10px;
    margin-top:-10px;
    background:rgb(0,0,0);
    border: 0px none;
    width:260px;
    border-radius: 4px 0 4px 4px;
    z-index:100;
    }

/*this exposes the tabs when we hover over the icon!*/
    a:hover.icon-edit,
    div.tabs:hover ul,
    div.tabs:active ul {
    display:block;
    }

/*position button - I want it to the left of the h1*/
    div.tabs {
    float:left;
    width:1em;
    }

Your selectors and styles may differ, but the essential thing is to have a trigger/button class (or id) that is inside the div you want to hide/show.


Generate a random image on front page each time it is loaded

You can use Views slideshow Module to get the same. In the view all you need to make is a random query.


Advanced form block - fields not showing in block configuration

It seems formblock and afb (advanced form block) conflict with each other. On my development site i disabled and uninstalled formblock and then all aspects of advanced form block worked as it should.
I do not want to do this to my production site because I am unsure of whether I will switch due to the work invovled


How to add large number of pages to a content type?

Use the Devel module, and its devel_generate submodule.

Using this submodule, you can perfectly create 200 nodes (with randomly generated content) of any content type.


Drupal 7: how to redesign, move stuff around, for a content type page?

Not clear with your questions ,adding some pointers on some assumptions.

Custom Way

1 . If you want to override a node structure for a specific content type

-- You can copy the node.tpl.php to your theme and rename it to node--type.tpl.php. Inside node--type.tpl.php , you will be rearranging the elements.

2 . If you want to override every node,irrespective to any content type.

-- Copy node.tpl.php inside your theme and do the rearrangement of elements.

3 . If you want to override a particular node

-- Copy the node.tpl.php and rename it to node--nodeid.tpl.php and do the rearrangement of elements

Some Helpful Links:

https://drupal.org/node/1089656

http://www.youtube.com/watch?v=dfwU0WtCuPs

Remember to clear the caches after you are done with building of templates.

Using Contrib Module

You can use panels module to override node templates without creating them. panele module will do that for you.

Some Helpful Links:

http://www.youtube.com/watch?v=_VIkE2ZS5oU


Trying to save an image field on a user using services, but for some reason it isn't saving in base64

You need to make two requests, the first you will POST the base64 encoded string of the file which in turn will return to you the file id, at which point you can make the second call to save the user entity with the file id on the field in question. I have a blog post about this here: http://tylerfrankenstein.com/code/drupal-services-file-create-example-json-and-jquery

Here's the gist of it (assuming your endpoint path is api):

// Get the file id...
$.ajax({
  type: "post",
  data: {
    "file":{
      "file": my_base_64_encoded_image_string,
      "filename": "my_image.jpg",
      "filepath": "public://my_image.jpg",
    }
  },
  url: 'https://www.example.com/api/file.json',
  dataType: 'json',
  success: function(result) {

    // Now that we have the file id, save it on the user entity.
    var userAccount = {
      field_picture: { und: [ { fid: result.fid } ] }
    };

    $.ajax({
      url: "https://www.example.com/api/user/" + localStorage.uid,
      type: 'PUT',
      crossDomain: true,
      headers: {
          'X-CSRF-Token': token
      },
      contentType: 'application/json',
      data: JSON.stringify(userAccount)
    });

  }
});


Why do both Text- and Data comparison seem to not work in my Rules conditions?

I am not sure it is your only problem, but for sure you are not correctly using the AND constructs in your rule. It is one of the typical mistakes many Rules users make, but if you want to model a condition like A AND B, then first you must have a line with AND, and that should be followed with A and then also folowed by B. Something like so:

AND
  A
  B

For way more details, refer to my answer to Combining AND and OR in Rules.

So start with fixing this, and then verify if your issue is solved or not.

As a sample, just import this minor variation of your last rule (note I slightly renamed the rule to not overwrite your existing one, and moved the AND construct to where it belongs):

{ "rules_create_a_drupal_user_by_pierre" : {
    "LABEL" : "Create a Drupal User By Pierre",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "civicrm", "rules" ],
    "ON" : { "civicrm_membership_create" : [] },
    "IF" : [
      { "AND" : [] },
      { "NOT civicrm_entity_user_exists" : { "civicrm_contact" : [ "civicrm-membership:contact-id-contact" ] } },
      { "data_is" : {
          "data" : [ "civicrm-membership:contact-id-contact:contact-sub-type" ],
          "value" : "Parent"
        }
      }
    ],
    "DO" : [
      { "civicrm_entity_action_create_user" : {
          "USING" : {
            "civicrm_contact" : [ "civicrm-membership:contact-id-contact" ],
            "is_active" : "1",
            "notify" : "0",
            "signin" : "0",
            "username_format" : "email"
          },
          "PROVIDE" : { "civicrm_user" : { "civicrm_user" : "Created Drupal User" } }
        }
      }
    ]
  }
}

If the above still doesn't solve your issue, then I suggest you do some extra Rules debugging as explained in my answer to "How can I display the value of a variable inside a condition?".

Update:

The above (related tot the AND-construct) is for sure "a" reason why it doesn't work. However, yet another issue you may have to correct, is related to what you wrote in a comment below this answer, i.e. this part of it:

  ... The value of the variable is the expected, but I'm not sure if I'm accessing in the right way to the variable, as it's an array: ... (Array, 1 element) 0 (String, 6 characters) Parent

If what you're trying to compare is an array (a "list of values"), then you should NOT (repeat: NOT) use something like a "Data Comparison", because that's like trying to compare an array with a single value (which doesn't make sense). To get your rule to work like you want it to work, you should use the Rules Condition  List contains item. For an example Rule (in Rules export format) in which you can see this at work, refer to the answer to "How to check for product taxonomy term in Rules actions (Ubercart)". In that case it's about a list of taxonomy terms, but the idea is the same.


So after we ran regular update (current version was 8.6.10), our website crashed. We followed this fix to recover from WSOD https://www.drupal.org/project/drupal/issues/3039408#comment-13018093

After website was restored we tried running all kinds of composer commands to update (like mentioned in question) and it would just spit out "Nothing to install or update".

Solution:

remove "twig/twig": "1.37.1", from composer.json
Run again composer update drupal/core webflo/drupal-core-require-dev --with-dependencies

Updating twig/twig (v1.37.1 => v1.38.2): Loading from cache
Updating drupal/core (8.6.10 => 8.6.13): Downloading (100%)

So, not sure what's going on.


Inspecting HTTP headers when requesting a route generated from Views

You can add a _custom_access requirement to any route via a custom RouteSubscriber extending off of RouteSubscriberBase. This requirement will add a method which can check the request headers to take action accordingly.

Define your event subscriber class in your mymodule.services.yml:

services:
  test.route_subscriber:
    class: Drupal\mymodule\Routing\MyRouteSubscriber
    tags:
      - { name: event_subscriber }

Within your src/Routing/MyRouteSubscriber.php class file extend RouteSubscriberBase with an alterRoutes(RouteCollection $collection) method:

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class MyRouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    // Add _custom_access to the my_view_machine_name REST export display
    if ($route = $collection->get('view.my_view_machine_name.rest_export_1')) {
      $route->setRequirement('_custom_access', '\Drupal\mymodule\Controller\MyCustomAccessController::access');
    }
  }
}

Within your src/Controller/MyCustomAccessController.php class file, perform the AccessResultlogic:

namespace Drupal\mymodule\Controller;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Custom controller adds additional checks to REST data export view.
 */
class MyCustomAccessController {

  /**
   * Checks access for a specific request.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   */
  public function access(AccountInterface $account) {
    $allowed = FALSE;
    $request = \Drupal::request();
    // @TODO: Add logic based off of $request->headers.
    return AccessResult::allowedIf($allowed);
  }
}


REST Server with my module service returns 404

With the Services module, the "CRUD" resources are typically mapped only to entities, and routed to each based on the HTTP method:

GET -> Retrieve
POST -> Created
PUT -> Update
DELETE -> Delete

When building a custom service resource, you need to use the actions array when building your resource. In your example, your resources array would become:

return array(
  'my_module_resources' => array(
    'actions' => array(
        'hotel_search' => array(
            'help' => 'Search for Hotels',
            'callback' => 'MY_MODULE_hotel_search',
            'access callback' => 'MY_MODULE_access_callback',
            'args' => array(
                array(
                    'name' => 'name',
                    'description' => 'hotel name',
                    'type' => 'int',
                    'source' => 'param',
                    'optional' => false,
                ),
            ),
        ),
    ),
  ),
);

Your callback can just return an array or object, it doesn't need to encode the result, because Services will automatically do that based on the extension on the URL, e.g. .json.

You'd then make a call to it with a POST to:

?q=rest/my_module_resources/hotel_search.json


Uploaded pdf file with multiple dots (.) in name are renamed for security reason

when the upload file name contains multiple (.) in file name, after each dot it will be considered as extension of the file. In your case(this.is.an.example.10.pdf) it will check (is,an,examplem,10) in valid extension, It is not match with that it will add (_)inthat. If your uploaded file name is not same after drupal changes it will give that error. For more detail check file_munge_filename


How to get latitude and longitude from user with Form API

I'm quite happy with the Geolocation Field module for Drupal 7. It allows you to put a field on any entity (user or node or whatever) that uses a map. It also has an html5 module to collect the information. Great stuff, actively maintained.


How can I get the sub-navigation to show up in the sidebar on child pages

I got some help with this, and what it needed was for this checkbox to be selected:


How to change the blog page title with specific user's only blog posts?

Tryout this one   Reference

class CustomController extends ControllerBase implements ContainerInjectionInterface
  public function getBlockContent() {
    if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
      $route->setDefault('_title', $some_title);
    }
  }

}


There is an option on contextual filters to exclude the resulting value, rather than limiting the search to that value. Turn on this checkbox, and you should have the results you are seeking.


You can do it from views itself from the filter criteria.

Or if in need of additional options try out the Better Exposed Filters

  The Better Exposed Filters module replaces the Views' default single-
  or multi-select boxes with radio buttons or checkboxes, respectively.
  Description fields and Select All/None links can be added to exposed
  filters to make for a better user experience


User submitted content in drupal (Drupal Noobie)

Have you taken a look at Open Atrium? It is not a Drupal module, rather a Drupal distribution pre-configured with a set of modules to help you manage projects. It includes functionality to upload files into projects, allows users to create new projects, etc.

Open Atrium has been around for a few years now, and it is pretty stable. Since it is Drupal (and hence, GPL'd), if the features that it brings does not satisfy your needs, as always, you can create your own modules to extend the existing functionality, or as a minimum, you could use Open Atrium to provide you ideas on how you might structure your project, which modules might help you out, etc.

There's also Storm, but it is currently available only for Drupal 6.x, and it's 7.x version is still not stable.


In a custom module, consider using PHP's built function for email validation: filter_var().

$email_a = 'joe@example.com';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "This ($email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "This ($email_b) email address is considered valid.";
}

This code will go into a validation function. A validation function can be added as an element to the form array (see the form API for details) that you linked to. If your module is named spade, for example, your form may be in function spade_form(). Your submit may then be put in function spade_form_submit(), and your validation would be in function spade_form_validate(). This is the default handler for validation.

See the following links for more information.

http://php.net/manual/en/filter.examples.validation.php
http://php.net/manual/en/filter.filters.validate.php
https://www.drupal.org/project/examples

The first example is exactly what you're looking for (and the example that I copied above). The last link contains the examples module, which has a lot of great form examples.


CCK Node Reference options not showing "this post can't be referenced."

Nodereference checks that the node is valid before allowing it to save. This check is either a 'standard' check that sees if the node is of the appropriate content type (if you configured the nodereference under the Content types that can be referenced checkboxes); or if you're using Views it can be a 'views' check (if you configured the nodereference under Advanced - Nodes that can be referenced (View)) that sees if the specified node is in the output of the view.


What's wrong with a new installation of Drupal 8.6.10?

Twig version 1.38.1 is broken (or not D8 compatible)

Revert to 1.37.1


How to only allow specific users to edit certain "fields" when creating content?

Use the Field Permission Module. This will provide the functionality you're looking for.


Login with Firefox.
While logged in on Firefox, open a separate window to www.example.com/user in Internet Explorer and try to log in.
If it fails, got back to the logged in session on Firefox and navigate to the Drupal Watchdog. See if any error appears.
Locate your PHP error logs, and see if they logged in any errors.
Edit your question and post any errors that you see.
...
Profit!

I feel this is a somewhat ambiguous error that could be being caused by almost anything, and there will be no way that anyone here is going to be able to psychically log in to to your server and figure out what exactly is causing that, without a more descriptive question. Checking what are your current watchdog/PHP errors is probably the best thing that you can do at the moment.


By playing around with the preprocess function I seem to have fixed the errors. I changed the preprocess function to:

function cr_preprocess_user_login(&$vars) {
  $vars['content_attributes_array']['class'][] = 'content';
  $vars['title_attributes_array']['class'][] = 'content';
  $vars['attributes_array']['class'][] = 'content';
  $vars['classes_array'] = array('content');
  $vars['forgot_link'] = l(t('Forgot password?'),'user/password');
}

I just added in the undefined indexes that were coming up in the errors. I'm really not completely sure what I am doing but it does seem to be removing the errors so far.

It would be great if someone could comment how this is working.


add render array to custom entity in controller

You can simply add this to the build array with an arbitrary key name. The only condition is of course that it does not already exist. Every key that does not start with a '#'-sign will be interpreted as another render element or an array of nested render elements.

$build['articles'] = $articles;


How to display number of results that would show in a contextually filtered view

Add an Attachment to the View. You can control the Access and change the filters.


It means that the file admin.inc (part of the Views project) is not found.

This file is supposed to be on the following path below your Drupal root sites/all/modules/views/includes/.  If you check, I'm sure that you'll find that it is no longer there.

Why this happens is more difficult to say.  I presume that you had the Views module installed on your site in sites/all/modules/views/ as indicated by the path (for the record: this is the right place), but that after the upgrade, it is no longer there?  Again, please check?

When upgrading, the sites subdirectory from the pre-upgrade site is supposed to be the sites subdirectory in the upgraded site.  If this, for some reason, in not the case, the contributed modules you've installed (such as Views) will be lost.

Please check if the files are missing (as I belive they are).  If they are missing, the solution is to make sure that the entire sites subdirectory hierarchy is properly moved into the upgraded site file hierarchy.


anonymous voting using poll module invalidates cache

After hours of testing, it looks like the Advanced Poll module does the job. Here is an excerpt about it from the module's project page:

... a replacement to Drupal's poll module and provides multiple voting systems, decision-making tools, and management options.

Voting systems: Basic polls, Approval Voting, Borda Count, and Instant-Runoff Voting.
Vote management: view each user's vote, delete all votes, or restrict the poll to a list of users.
Time management: schedule when to open or close the poll, and choose when to show results.
Choice management: write-in choices, and support for HTML (or other input filter).
Usability: fast Ajax interaction and customizable default settings.
Migration: convert regular Drupal polls into Advanced Polls.


New User Registration take long time (more than 60 seconds)

You can install the devel module and see which part of Drupal that slows things down. You could start out by taking a look at the queries that are run.


Can I change the default tab at /admin without losing access to /admin/tasks?

please find this code to do this

function hook_menu_alter(&$items) {
$a_title = $items['admin']['title'];
$admin = $items['admin'];
$t_title = $items['admin/tasks']['title'];
$tasks = $items['admin/tasks'];
$i_title = $items['admin/index']['title'];
$index = $items['admin/index'];
$items['admin/tasks'] = $admin;
$items['admin/tasks']['title'] = $t_title;
$items['admin/tasks']['type'] = MENU_LOCAL_TASK;
$items['admin'] = $index;
$items['admin']['title'] = $a_title;
unset($items['admin']['type']);
unset($items['admin/index']);
$items['admin/index'] = $tasks;
$items['admin/index']['title'] = $i_title;
}


Add another item by multivalued fields directly from node (or entity) view page

You can able to achieve it using Edit module which supports D7 and file Entities...

Project page says

  In-place editing for fields on any entity. Including WYSIWYG editing
  powered by CKEditor.

  In-place editing through forms will work for any field. For textual
  fields, "direct" editing is used, powered by contentEditable.

Here is the sample screenshot which shows inline editing of Multiple File Field.. Here is how i can able to achieve it..

Install like any other Drupal module.
Download Underscore 1.5.x and Backbone 1.x from http://underscorejs.org/ and
http://backbonejs.org/, respectively and put them in sites/all/libraries, in
a "underscore" and a "backbone" subdirectory, respectively. Either the
development or production version will work. Edit module will automatically
use the production (minified) version if it's available, because it's more
efficient.
Grant the 'Access in-place editing' permission to relevant roles.
Contextual links on nodes will now have a 'Quick edit' link. Clicking it will
start in-place editing of that node!

Seems like editablefields module also provides same functionality..


Modifying user view to display correct gender

Have you checked your Manage fields to make sure your select options are correct?

1|Female
2|Male

Your custom code doesn't do anything with the gender so I'm not quite sure why you posted it.

Also I would verify if you have english to russian translation going on that they map correctly to the right english version.


Authcache: Getting user_link to work in template.php

Ok so here is my solution.

Menu's are themed in MYTHEME_preprocess_page, the menu data is also still structured here unlike in MYTHEME_preprocess_menu_tree.

I enabled the memcached example module, this enables the variables user_link and user_name in the preprocess. Then I created a third variable user_account just copying from the other two and altered the cookie so it stores uid not name.

This is because I wanted the "My Account" link to link to "user/x/edit" and I didn't need the name.

I then added the following chunk to my page preprocess.

function MYTHEME_preprocess_page (&$vars) {
  $user_account = $vars['user_account'];
    if (array_key_exists('menu-xxxx', $vars['secondary_menu'])) {
      $vars['secondary_menu']['menu-xxxx']['href'] = $user_account;
    }

The secondary menu in this case is my user menu and My Account is always labelled menu-xxxx in the array. (xxxx will be numbers).


How to call a function when a node is being viewed?

You can implement hook_node_view()

  Act on a node that is being assembled before rendering.

e.g.

function MYMODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'the_type' && $view_mode == 'full') {
    // Call your function here.
    my_function($node);
  }
}


Is there any way to know which theme hook or template is being used to output certain area of a page

Yes, there is a module for that: Theme Developer.

  Firebug for Drupal themeing

Note that this is a heavy module, enable it only when needed and on your local machine.


Here's one way to modify your code to add a unique class for each menu level dynamically:

Add a new class appended with the value of menu_level plus one:

  {%
    set submenu_classes = [
      'sidebar__menu' ~ menu_name|clean_class ~ '--submenu',
      'sidebar__menu--submenu-' ~ (menu_level + 1),
    ]
  %}

Remove the previously added class, otherwise I believe it will add the class for each level incrementally.

    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('container mx-auto', menu_classes) }}>
    {% else %}
      <ul{{ attributes.removeClass(menu_classes, 'sidebar__menu--submenu-' ~ (menu_level)).addClass(submenu_classes) }}>
    {% endif %}


I don't know the particular flag api to get the usernames of flagged node.
But it can be possible using custom implementation. Here is code

function get_usernames_flagged_node($entity_id, $flag_name) { //Supply node_id and flag_name
  $get_all_nodes_of_flagged = flag_get_flag_flagging_data($flag_name);
  $flagged_content_detail = array();
  $username = array();
  foreach($get_all_nodes_of_flagged as $get_all_nodes_of_flags) {
    $flagged_content_detail[] = $get_all_nodes_of_flags;
  }
  foreach($flagged_content_detail as $flag_content) {
    if($entity_id == $flag_content->entity_id) {
     $user=user_load($flag_content->uid);
     $username[]=$user->name;
    }
  }
  return $username;
}

It can be also possible using views and flag modules. For your reference see this page


How to perform a redirect to custom page after node save or delete?

Basically the code will work for submit action alone, but drupal node save form have many actions, I think you would have logged in as admin and trying it, then follow the code below.

if you want this to be work for other actions too, That means login as admin and see the node save button, you will have select option "save and publish" , "save and unpublish". as mentioned

use Drupal\Core\Form\FormStateInterface;

//hook_form_alter
function hook_form_alter(&$form, $form_state, $form_id) {
  foreach (array_keys($form['actions']) as $action) {
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
      $form['actions'][$action]['#submit'][] = 'callback_submit';
    }
  }
}

function callback_submit($form, FormStateInterface $form_state) {
  $form_state->setRedirect('custom.page');
}


Using Drupal 8 Feeds with Xpath parser, can I concatenate two attribute values that appear in a single tag?

Well, I have a solution but it's not elegant. I used this query:
//theme/@name|//theme/@rank

and Imploded the resulting array to get theme1,rank1,theme2,rank2, etc,

then used a regex to replace every odd comma with a dash:
/(\w+)\W*,\W*(\w+)/
$1-$2

and then Exploded back to an array.

Would still like to know if there's a better alternative.


How to enable an authenticated user to vote?

Authenticated users probably do not have permissions to vote.

Go to administration > People > Permissions and then grant authenticated users the "vote" permissions.


View for Entity Reference reverse, backwards forwards

No additional module need to be installed.
No coding needed. Just site building for Drupal 8.
First we need to check if our content types are ready.

Landing page content type, don't need any change.
Page content type need a field of type Entity reference.

Add field -> Add a new field = Reference Content

Then in Edit tab chose your kind of content type (parent)

After Save you will get...

Now go to admin/structure/views and + Add view

In this case we are going to check the option to create a block

In ADVANCED

Add Relationship for our field_back_parent in Page content type. This important to connect the two content types.

You need to tick Require this relationship.

In ADVANCED

Then Add Contextual filter for our current content type Landing Page. In this way, we will get our actual node id to be used in the view. So, now we can find only the pages that have same node id in field_back_parent.

So find by ID (Content)

Select the relationship name.

Check Provide default value -> Content ID from URL

Then you will get something like this:

In Relationship you must to have the word Content in the rightside

This is the result of our settings

If you click in Update preview you will corroborate that it doesn't display anything.

You must to add the node id from parent. In our case is the node 2 from Landing page.

Other way for reference https://mushtaqtahir.com/blog/4/drupal-8-reverse-entity-reference-in-view

I hope that this info help you.


There is a module that's compatible with the 7.x-3.x branch that gives you the option to do just that:

  This module adds the ability to choose whether a webform should be saved to database or not. Within settings of each webform you can choose the option.

There is also a related issue in Webform's queue that is tracking the progress of getting the functionality into the webform module.

If you don't want to use the sandbox module, I'm sure you could check out the source and see what they're doing differently from what you have posted above.


Output from preprocess_views_view_field in Drupal 8

Use the raw twig filter - so, in your template:

{{ mystars|raw }}


Way to prevent drush from eating custom profiles when updating core?

Consider to use Aegir. It supports this usecase.


Drupal can't out of the box. Doesn't mean YOU couldnt in PHP :) (i think)

I've written PDFs on-the-fly using Ruby and mucked with it in PHP soooo ....

Using Fields in Drupal you could supply an File Upload widget for PDFs.

Then write a module to process the file on upload,

Using PHP's built in PDFs functions like:

http://php.net/manual/en/function.pdf-get-pdi-value.php

simply get the numbers of pages, and then retrieve each page's content and make a new simple 1 page PDF out of it. Then save the file and FID to another Field of files with unlimited values for any number of pages .... It sounds doable for most PDFs (not necessarily crappy built non-standard PDFs) -- but definately some work .... :)


How to log simpletest test results into files using drush test-run?

I don't use drush test-run, but Drush options are always in the form --xml=/var/tmp.

c.f. http://drupal.org/node/1416198

From drush help test-run

 --xml      Output verbose test results to a
            specified directory using the JUnit
            test reporting format. Useful for
            integrating with Jenkins.

Try:

sudo -u apache drush test-run Comment --all --xml=/var/tmp


How to prevent access to Views-only content?

In D6, I set the path alias for these content types to be

no-view/[nid]

and then use

function MYMODULE_init ()
{
    $path = drupal_get_path_alias(request_uri());

    if (strpos($path, "no-view/") !== FALSE) {
        drupal_not_found();
        exit;
    }
}

I think this will work as-is in D7, but I haven't tried it.


How to create a custom menu in Drupal 7?

Step 1: Create the menu

Navigate to admin/structure/menu/add in your site and add the menu you want. Add at least the "Title" of the menu (like Custom menu), save it, and it will show up in admin/structure/menu also. From there you can start to add menu items (which will be the "new links" you are looking for).

Step 2: Make the menu visible

Head over to admin/structure/block to indicate in which region of your theme you want that newly added menu (Custom menu) to be shown.

Step 3: Clear the cache

And don't forget to clear the cache (since you're changing things that are cache sensitive ...). I think "menu" cache should be sufficient, but to be sure I usually just clear all caches ...


How set a time type field programmatically?

The form element property #type refers to an element type, not a HTML element. It is okay to define your own element types (or theme types), and you can provide your own markup for it. This can be done by implementing a RenderElement plugin.

Update:

You can also use the datetime render element and disable the date portion.

$element['#date_date_element'] = 'none';

Update 2:

The comment form has an example of a render array that uses the datetime type. So given that as a guideline,

  $form['time_without_date'] = array(
    '#type' => 'datetime',
    '#title' => $this->t('Time without date'),
    // HTML 5 time element format can be H:i
    '#default_value' => DrupalDateTime::createFromFormat('Y-m-d H:i:s', '1970-01-01 20:00', 'UTC'),
    '#size' => 20,
    '#date_date_element' => 'none',
    // This sets html 5 time element use explicitly, probably not necessary.
    '#date_time_element' => 'time',
  );


How do I get a user profile's picture from entity_metadata_wrapper()?

You can get the information about user picture indirectly as follows:

$user_picture = $user_wrapper->value()->picture;

I said indirectly, since the picture object itself is not an entity wrapper anymore, so you cannot chain it further using entity_metadata_wrapper functions. However, it should have all the information you need about the user picture, like the fid, filename, uri, filemime, filesize, metadata, and any other fields that could be attached to a file, for instance using File Entity module.


How do I add a webform to my Event content type View

Could you use a node reference field on the event?

Example:

Create your registration webform and save it.
Create your Event node, and in the node reference field select the Webform that will book your event.
In your table view you should be able to link to this referenced node.


Does Drupal detect if the user register email could not be delivered and removes the account?

Drupal doesn't know about the status of the email. I'm not sure how Drupal 5 does it, but it would be possible to setup Drupal to delete accounts older than X that has never logged in.


Drupal private messages database table design

In general with Drupal you want to avoid directly querying the database if you didn't create the tables yourself. Instead try to use functions provided by core or the module to get the data for you. The table structures are often complicated and may change without notice, but the functions for accessing those tables generally adapt to the changes (this is more true of core than contrib modules, but is frequently true of both).

In the case of Privatemsg the Drupal 7 version (and probably 6) provide several useful functions to pull the message data (see the main module file).  For example you can load an entire thread with privatemsg_thread_load:

/**
 * Load a thread with all the messages and participants.
 *
 * This function is called by the menu system through the %privatemsg_thread
 * wildcard.
 *
 * @param $thread_id
 *   Thread id, pmi.thread_id or pm.mid of the first message in that thread.
 * @param $account
 *   User object for which the thread should be loaded, defaults to
 *   the current user.
 * @param $start
 *   Message offset from the start of the thread.
 * @param $useAccessDenied
 *   Set to TRUE if the function should forward to the access denied page
 *   instead of not found. This is used by the menu system because that does
 *   load arguments before access checks are made. Defaults to FALSE.
 *
 * @return
 *   $thread object, with keys messages, participants, title and user. messages
 *   contains an array of messages, participants an array of user, subject the
 *   subject of the thread and user the user viewing the thread.
 *
 *   If no messages are found, or the thread_id is invalid, the function returns
 *   FALSE.

 * @ingroup api
 */
function privatemsg_thread_load($thread_id, $account = NULL, $start = NULL, $useAccessDenied = FALSE) {

There are also several functions that generate the query objects for pulling the module's data like privatemsg_sql_list:

/**
 * Query definition to load a list of threads.
 *
 * @param $account
 *  User object for which the messages are being loaded.
 * @param $argument
 *  string argument which can be used in the query builder to modify the thread listing.
 *
 * @see hook_query_privatemsg_list_alter()
 */
function privatemsg_sql_list($account, $argument = 'list') {


Setting link target through views programatically

Your problem is that you need to define the target under attributes, so

array('target'=>'_blank', 'html' => TRUE)

should instead be:

array('attributes' => array('target' => '_blank'), 'html' => TRUE)


Is there a live backend demo of drupal commerce?

Go to https://simplytest.me
Fill in "commerce kickstart"
Select the latest version: 7.x-2.41
Click "Launch sandbox"
Follow the step-by-step on-screen instructions, including the database configuration screen. You will notice that all fields are already filled in so you can just press "Next".


This is a known bug, and is being fixed: https://www.drupal.org/node/2592325. The fix is already present, it just needs test coverage now.


DrupalDefaultEntityController invalid argument supplied for foreach

The 2nd argument for node_load_multiple() is an array of conditions; currently you're providing a boolean so when the buildQuery function tries to iterate over the variable you get a warning.

The 3rd argument is to reset the cache (I guess that's what you're trying to do), so the call should be:

$nodes = node_load_multiple($subscription_nids, array(), TRUE);


Are you using the Draggable Views module? If so, you can set the child table to use the sort order of the dragged table, and possibly trigger an ajax refresh when the order of the master table is saved.


how to use cookie to protect other node pages in Drupal

Sounds like a case for user authentication?

The problem is the first page request will never have a server-side set cookie as it will be set on the subsequent request and you don't want to deny access on your homepage.

You could set the cookie with javascript, but then you risk blocking users with js disabled.

Requiring user login would be the easiest solution.


How do I pull a field value from a form field in to my inline entity form?

Just want to share my solution to this problem. Turns out I didn't need another function, I had all the variables available in my MYMODULE_inline_entity_form_entity_form_alter function in the $form_state array.

I targeted: $form_state['input']['field_group_reference'][und]

And that got me the value of the field in my parent entity.


_drush_file_private_path()
_drush_file_public_path()

in the end were just wrapper functions of

\Drupal\Core\StreamWrapper\PrivateStream::basePath()
\Drupal\Core\StreamWrapper\PublicStream::basePath()

And you probably get the same from

\Drupal::service('file_system')->realpath('private://')
\Drupal::service('file_system')->realpath('public://')


Node reference solution for a content type which referenced to two fields. (company, product & review)

Try entityreference_prepopulate

This will allow you to create a link with query string to pre-fill selections on an entity reference form field.


How to call/submit Form from another page in custom module?

You can do it with the FormBuilder::submitForm() function.

To register a new user (taken from the docs):

// register a new user
$form_state = new FormState();
$values['name'] = 'robo-user';
$values['mail'] = 'robouser@example.com';
$values['pass']['pass1'] = 'password';
$values['pass']['pass2'] = 'password';
$values['op'] = t('Create new account');
$form_state->setValues($values);
\Drupal::formBuilder()->submitForm('user_register_form', $form_state);

You might have to include the namespace for the FormState class before this code if not done already.


How do I include tax and discount in computed field?

Surprising I did not find this function before, but this is what I needed:

commerce_product_calculate_sell_price($product, $precalc = FALSE)

Returns a price field data array as returned by entity_metadata_wrapper().


Please check if you are using the correct username (you can see that
in the database).
Try to use the "Forgotten password" function to reset your password
Check the last entries of the watchdog table to see if you can get
more information from there
Check your server logs to see if you get any error there (under Linux
this would normally be somewhere under /var/logs).
Install drush and use that to very easily log in
(https://drushcommands.com/drush-7x/user/user-login/)


Add user points to author for every up vote received to content using Rate module

I recommend to go for a combination of these often used modules to add (or subtract) user points when some node is voted up (or down):

Voting API.
Rules.
Voting Rules (attention: alfa version only).
User Points.

It's also the approach used in the Answers module (disclosure: I'm a co-maintainer of it), i.e. within its submodule "Answers Userpoints". If you agree, read on ...

Required Rules

To handle all variations of voting, you need 4 rules (only!), which cover these 4 cases:

a node is upvoted.
an upvote for a node is canceled (= no longer upvoted).
a node is downvoted.
a downvote for a node is canceled (= no longer downvoted).

Below are the required rules, for each of these cases (use the Rules UI to import them in your own site, after you enabled the required modules mentioned above). These rules are enhanced versions of the rules included in the 7.x-4.0-rc2 version of Answers (and are expected to be committed to its dev version also). They use a content type with machine name answers_question (adapt this name to fit your own machine name).

Have a close look at how user points are added (or subtracted), and also who gains (or looses) those points. Obviously, then actual amounts of userpoints can be adapted in those rules to fit your own needs.

Upvote a node

The rule below will grant +5 user points for an upvote (to the author of the node):

{ "rules_voteup_question" : {
    "LABEL" : "voteup_question",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "5",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Receive upvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionUpvoteReceived",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

Cancel the upvote a node

The rule below will grant -5 (= remove +5) user points for a cancelled upvote (to the author of the node):

{ "rules_voteup_question_cancel" : {
    "LABEL" : "voteup_question_cancel",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_delete_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "-5",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Unupvote [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionUpvoteCancelled",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

Downvote a node

The rule below will subtract -2 (grant -2) user points for a downvote (to the author of the node) ... AND also -1 user point for the voter:

{ "rules_votedown_question" : {
    "LABEL" : "votedown_question",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "-1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "-2",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Receive downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteReceived",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "-1",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Issue downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteIssued",
          "reference" : "From uid=[node:author:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

Cancel the downvote a node

The rule below will grant +2 (= remove -2) user points for a cancelled downvote (to the author of the node) ... AND also +1 user point for the voter:

{ "rules_votedown_question_cancel" : {
    "LABEL" : "votedown_question_cancel",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_delete_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "-1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "2",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Cancel downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteCancelled",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "1",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Withdraw downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteWithdrawn",
          "reference" : "From uid=[node:author:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}


Remove drag table in field collection module drupal 7

To removing ajax dag and drop table widget for multiple value field you need use "hook_theme_registry_alter" to override theme registry function. Here you can find all information regarding your question.


Views simply won't output HTML at all for me in any content types, what to do?

"node" is registered menu path by node module
You should not set a page path "node" which already exists.
Create a block view using views instead of page view
Enable the block on home page


my articles publish even when I deselect publish

This is what I did to fix the problem:

I disabled all except the core modules.
I then tested to see if I could unpublish content, and I could.
I then re-enabled each module until I found the culprit. In this case, it was the "rules" module.


How do I stop a node submission programmatically?

You can hide the form submit button using hook_form_alter() and show a link Save and Publish on form. And include a jQuery snippet to show message, which will be triggered when user clicks on a link Save and Publish.


Is there a way to add a wrapper class to my blocks?

If I understand you correctly, you can use the Theme Developer module to inspect the block itself.  You will be able to take the default block template out of the main theme directory, rename it accordingly, and then edit it to have your class.  This is not the best way to achieve this result, but it will work. Make sure to disable the module when you are done using it.

In addition to that, the block themselves will have their own independent ids "#block-block-17".  A little more painful to work with, but if you don't have that many it could be another solution for you.


Unknown top and bottom padding in panels

leftpane {
margin: 0px;
padding:0px 20px !important;
background:#17532E;
border-radius:17px;
float: left;
}

Add !important rule to override existing padding


How to enforce edit suggestions of a post to require approval from the author of the post?

Try User Points

  This module provides an API for users to gain or lose points for
  performing certain actions on your site.

  In conjunction with other modules, such as the Userpoints Nodes and
  Comments users can accumulate points for actions such as posting
  nodes, commenting or moderation duties.

  Use one of the many contributed modules to extend the functionality of
  the module to include point accumulation on page views or votes,
  upgrade roles based on point balance, or purchase goods from your
  store.

And if you need to do states of content, try Workflow

  This module allows you to create arbitrary Workflows, and assign them
  to Entities.

  Workflows are made up of workflow states. Transitions between states
  can be allowed per role. For example, a workflow with the states
  Draft, Review, and Published could be assigned to the Story node type.
  Only users with role 'chief editor' can set Stories to the published
  state. You can set up the Workflow to alter states from form, page,
  comment and a special workflow tab.

  Transitions between workflow states can have actions assigned to them.
  In our example, we could assign an action so that when the story moves
  from the Draft state to the Review state an email is sent out. Another
  action could be assigned to the transition from Review to Published so
  that the node's status is set to Published (and becomes visible on
  your website).


Install Internationalization module and enable Menu translation sub module. Now it allows users to select a translation mode for each menu.


If I add $this->argument->argument = '1'; to the above code, it works:

<?php

namespace Drupal\my_module_validation\Plugin\views\argument_validator;

use Drupal\views\Plugin\views\argument_validator\ArgumentValidatorPluginBase;

/**
 * Validate the New boolean.
 *
 * @ingroup views_argument_validate_plugins
 *
 * @ViewsArgumentValidator(
 *   id = "my_module_validation",
 *   title = @Translation("MYMODULE Validation")
 * )
 */
class MyModuleValidation extends ArgumentValidatorPluginBase {

  public function validateArgument($argument) {
    if($argument == 'new' || $argument == 'New' || $argument == '1') {
      $this->argument->argument = '1';
      return TRUE;
    }
    return FALSE;
  }
}


As popular Drupal 7 modules like Taxonomy CSV import/export and Taxonomy Manager are not ported to Drupal 8, I recommend a very simple but functional module called term_csv_tree_import.

After installing, go to /csv-tree-import and paste your taxonomies into the form. It assigns parent values from right to left, empty intermediate elements are allowed. You have to convert your CSV into the following format:

"element","subelement","subsubelement"


Core Update to 8.9.4 Removed Block Visibility Options?


How do I implement the autocomplete functionality in Webforms?

Autocomplete is implemented in Drupal through AJAX. When users type
  into a textbox, code on the client page dynamically loads new data
  from the server (a Drupal website) and uses this data to update the
  user display (provide a drop-down list of matching options, which the
  user can select from).

Available autocomplete functions (D6):

user_autocomplete() - Use this function to load matching user names.
taxonomy_autocomplete() - Use this function to load matching taxonomy terms.

If you want to have your own autocomplete function it is also possible.
Please see a full article on this subject on drupal.org "Textfield that uses autocomplete"
to see how to build a custom autocomplete function.


Cannot modify header information following page not found error

Please note that there are a lot of things that can cause this, and it's very hard to say what goes wrong depending on your system. But the following seems the most plausible:

The page is deleted, so drupal immediately serves a cached 404 page (with 404 header). Some other module which perhaps invokes a wrong hook, then tries to alter the output or output header. Which it can't because the page is already compiled.

You could try to read the headers of a regular page and one of a 404 page to find out what header is missing (and thus what module might be causing it) I use Fiddler to post such requests and read the server's response, but there are plenty of other tools.
You could also try to read the issue queues of the modules you use, try to find if someone else ran into this problem earlier.

As a last resort you could start disabling your modules and try to find when it stops. Or use 'find in files' to see if there are modules calling 'drupal_send_headers'.

But then again, it might not even be a module...

Please note that a theme is also capable of editing output, and thus might be causing this.


You can use theme layer to override the views output , if you want only theme a certain field you can use this template file :views-view-field.tpl.php

for more information check this tutorial : Theming a single field in a Views


Pre-populate an entity reference field (media image) when creating a node

It's much easier to prepopulate field values on entity level rather than on form level:

/**
 * Implements hook_ENTITY_TYPE_create() for 'node'.
 */
function mymodule_node_create(\Drupal\node\NodeInterface $node) {

  if ($node->getType() == 'my_content_type') {
    $media = \Drupal::entityTypeManager()->getStorage('media')->load(38);
    $node->field_image[] = $media;
  }

}


Display form errors on each field instead of at the top of the page using form_set_error

You can use the Inline Form Errors module for that

  IFE or Inline Form Errors allows you to place form submission error inline with the form elements. Three options are provided for setting your inline error behaviour. You can configure the default behaviour or override the behaviour on a per form basis. You can add as many forms as you like.

Or alternatively the Inline Messages module:

  The Inline Messages module allows you to move form messages (error/status/warning) from the top of the page to just above where your form appears.

The former would appear to be the more actively maintained of the two.


Get selected value from Dropdown list of views

Not sure I fully understand the issue it would help if you asked a direct question. Here are some thoughts though.

To get a list of applicalbe view checkout this funciton form the node reference module:

function references_get_views_options($entity_type) {
  // Filter views that contain a 'references' display. This actually returns a
  // list of displays (the same view appears several times).
  $displays = views_get_applicable_views('references display');

  // Filter views that list the entity type we want, and group the separate
  // displays by view.
  $entity_info = entity_get_info($entity_type);
  $options = array();
  foreach ($displays as $data) {
    list($view, $display_id) = $data;
    if ($view->base_table == $entity_info['base table']) {
      $options[$view->name . ':' . $display_id] = $view->name .' - ' . $view->display[$display_id]->display_title;
    }
  }

  return $options;
}

The key function here is the "views_get_applicable_views(&display_type)". The rest of the function just filters the list for an entity type (node, taxonomy term, comment, or user are the common defaults). Then formats the data as an options list.

You can embed this list in a form as so (I wrote this code to do a similar task to what it sounds like you are doing:

$views_options = references_get_views_options('node');
if ($views_options) {
  $views_options = array('' => '<' . t('none') . '>') + $views_options;
  $element['view_and_display'] = array(
    '#type' => 'select',
    '#title' => t('View used to select the nodes'),
    '#options' => $views_options,
    '#default_value' => $default_view,
    '#description' => 'description',
  );

In the submit handler you save the view option. Something like:

$view = $form_state['values']['views_and_display'];

Then in the view hook of the content type you run an embed.

$view_info = explode(':', $display['settings']['view_and_display']);
$result[0]['#markup'] = views_embed_view($view_info[0], $view_info[1], $args);

Hope that helps. I wrote a module that did something similar for a client not too long ago so this is all working code form that module. It actually registers a display handler to output a node reference field as a view so it would give me a list with exactly the correct fields desired.


Filter |raw doesn't show entity media image

This output from the body field

<drupal-entity data-embed-button="media_browser" data-entity-embed....

is the raw data stored in the database. The tag <drupal-entity> gets replaced by the text filter "Display embedded entities" when the field is rendered.

If you access the field data directly from the entity #paragraph you bypass this rendering process.

Instead of the raw filter, which doesn't help in any way, it only makes your site vulnerable to the content of the body field, you can apply the text format in a render element processed_text:

  {% set paragraph =  content.field_tabs.0['#paragraph'] %}

  {% set body = {
    '#type':   'processed_text',
    '#text':    paragraph.field_body.value,
    '#format':  paragraph.field_body.format,
  } %}

  {{ body }}


You can get all services from the container by using the kernel method getCachedContainerDefinition():

$container = \Drupal::getContainer();
$kernel = $container->get('kernel');
$services = $kernel->getCachedContainerDefinition()['services'];
foreach ($services as $service_id => $value) {
  $service_definition = unserialize($value);
}

Now you can output a list, for example containing the service id and the class name in $service_definition['class'].


Sign out not working properly in OpenID Connect

The openid_connect module is great for authenticating/adding users via external identity providers. However, it does not provide single sign out capabilities.

You will have to implement them yourself.

A viable way of doing so is to implement hook_openid_connect_post_authorize() to add information about the used identity provider/tokens to the user session/database, and e.g. hook_user_logout() to invoking the sign-out endpoint of your identity provider, if the above saved information is present when the user logs off your Drupal.


Create directory in file system per organic group

It looks like the Filefield Paths module will do what you ask, in particular there is an over view on how to Mix public and private files with Organic Groups and File (Field) Paths

The part I can see it doing is copying the file - but you may not want that behavior as it will quickly bloat your storage.


How can I create special search with check/uncheck image field in filter criteria of views

You will need BEF module to get exactly what you want, but it's not ready yet.

The workaround:
Although Drupal still has a query checkbox value bug (pretty ugly:(), there is a workaround and you can come up with the following close solution:

Create a new filter criteria
Choose your image field "target_id" property.
Configuring the filtering critera check "Expose this filter to visitors"
Choose "Grouped filters"
Mark "Optional" checkbox.
Widget type: radios.
Allow multiple selections.
Mark the first grouping (Grouping 1), give it a label and choose operator "Is not empty(NOT NULL).

You are now half way through. Altough it's working like this in view preview mode, it won't on the real page (because of the bug above).

Now you need to write a hook_form_FORM_ID_alter in one of your .module file, mine's looks like this:

function base_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-search-page-1') {
    $request = \Drupal::requestStack()->getCurrentRequest()->query->all();
    $filter_identifier = 'field_image_target_id';
    if (!$request[$filter_identifier]) {
      $user_input = $form_state->getUserInput();
      unset($user_input[$filter_identifier]);
      $form_state->setUserInput($user_input);
    }
  }
}

WHERE:

"views_exposed_form" => form_id (you will get the same, but check it)
"views-exposed-form-search-page-1" => is the '#id' parameter of your form. (this will be probably different)
"field_image_target_id" => This is your filter identifier, which can be found (also renamed) in when clicking on views this filter criteria.


You will not be able to add an id or class attribute to the block in your hook_block_view implementation. At this stage you are not yet dealing with the markup of the block itself but only the markup for its content. In order to set the id or class of the block markup, you will need to use hook_preprocess_block() or hook_process_block() to add a usable variables to the block.tpl.php template. Then you will need to actually use the variables in the template itself.

Fortunately, the default block.tpl.php file already provides variables for both the id  and class attributes of your block ($block_html_id and $classes). Actually, template_preprocess_block already sets the id to 'block-' . $variables['block']->module . '-' . $variables['block']->delta. So in your case, using the default template, your block will have block-contact-contact-block as id. But it can be changed if needed. In any preprocessor functions, you can add and remove CSS classes by manipulating $classes_array variables. Both are illustrated in the following code.

function MODULE_preprocess_block(&$variables) {
  if ($variables['block']->module == 'contact' && $variables['block']->delta == 'contact_block') {
    $variables['block_html_id'] = drupal_html_id('your-id-here');
    $variables['classes_array'][] = drupal_html_class('your-class-here');
  }
}


Is it possible to show 403/404 messages on the front page?

You can make this with the following configuration and using Rules module.
1. create a page with a custom path ex, "404" and set this page as 404 on configuration -> site information
2. create a rule, if the request page its "404" then
 2.1 system page redirect
 2.2 system show a message


Limit currency for one product in Drupal Commerce

I'm afraid there's no custom module for this, you'll need to alter the product form add/create to adapt to your settings/conditions (simplified logic below):

/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_commerce_form_commerce_product_ui_product_form_alter(&$form, &$form_state, $form_id) {
  // Calculate the currency for a given product.
  $currency_code = 'USD';
  $form['commerce_price'][LANGUAGE_NONE][0]['currency_code']['#type'] = 'value';
  $form['commerce_price'][LANGUAGE_NONE][0]['currency_code']['#default_value'] = $currency_code;
  $form['commerce_price'][LANGUAGE_NONE][0]['amount']['#field_suffix'] = $currency_code;
}

A more complex and customizable option would be to use hook_field_widget_info_alter and modify the settings form to add whatever conditions you want for selecting a currency on a product form.


How to adding our own sorting to a view on Drupal?

You could alter your view query with hook_views_query_alter to add your custom sorting.

<?php
/**
 * Implementation of hook_views_query_alter
 * @param type $view
 * @param type $query
 */
function mymodule_views_query_alter(&$view, &$query) {

  //simple example: change the order of the master display
  //if you want to do it only  on a certain display add something
  // like  "&&$view->current_display == 'panel_page_1'"
  if ($view->name == 'VIEWNAME') {

    //to find out what the fieldname ist: use devel and add your desired field as
    //first filter ( =>orderby[0]). install devel and uncomment the next line
    //dpm($view->query->orderby)

    $view->query->orderby[0]['field'] = "CASE FIELD_NAME WHEN 'apple' THEN 1 WHEN 'zebra' THEN 2 WHEN 'banna' THEN 3 ELSE 4 END";
  }
}
?>


Try using File Path Module

  Adds the ability to use node tokens in destination paths and
  filenames.


User Role creation in module overridden by configuration import

Docs for installing default configuration in a custom module
However, putting a role in the configuration of a module is probably a bad idea.  I can't think of an example of a major contrib module that does this.
Imagine this situation: you install the module, and then the role gets enabled.  Next, the user adds some other permissions to the role (created by the module) unrelated to your module.  Then the user uninstalls the module.  Now what should happen?  Usually, the expectation is that module config will be cleaned up on uninstall, but this won't happen for roles.
What you probably want to do is add some permissions and allow the user of the module to add those to the role of the user's choice.


How do I avoid hard coding the links in a custom made navigation bar?

You should create a menu for this (drupal menus works with system paths, no need to "hardcode" the links) and display this menu in a block where you want.


How to resolve my error when uploading files?

You can try the Pack & Upload module for this. This module can be used to upload the zip file.


Sometimes clearing the cache twice in a row helps, for whatever reason.


Run hook_init on every page except AJAX page executions

You can check if you're processing an AJAX request or not in your hook_init() and skip your code if you need it.

function uc_cba_init(){
  if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    // Is an AJAX request...
  }
  else {
    // Is not an AJAX request...
  }
}

Hope it helps!