Views single field themeing with custom variables

I think it's just that there are two similarly-named theme implementations: views_view_field and views_view_fields (trailing s). Generally you can take the name of the template file before the first double-dash to find the theme implementation name, so if the template starts with views-view-field-- you'd expect the preprocess to be hook_preprocess_views_view_field(). (That naming pattern's not guaranteed though.)


Send mail notification when node of given type gets created

Answering the "what do I put in the 'type' box?" question, the answer appears to be the same as for D7 - that is, the same status you'd pass to drupal_set_message().

This gives you options of:

status
warning
error

As to the state of D8 and specifically D8 rules, I share your pain - and it's nine months since you asked the question!


Composer module doesn't contain a .info file

The project you linked to is a Drush extension, not a module, and only compatible with Drupal 8.

So it makes sense that you can't install it as a module into a Drupal 7 site ;)


Undesired toggle effect with #states and checkboxes

Form API states act in both directions. Suppose you set an element to be unchecked if a condition X is true. Then it gets unchecked when X becomes true, and gets non unchecked (i.e. checked) when X becomes false. See the example code and its demo at drupal.org.

You need some custom jQuery in the case.


You can use the Void Menu module to achieve this.

  Void menu allows you to configure special values to tags for use in the Drupal 7 menu system. You can customize up to 10 different void tags with any value you wish and use them freely inside the Drupal menu system.

For example, to link to a block with an id of #about, go to the Void Menu configuration page (admin/config/user-interface/void_menu), and set one of the "tags" to your block id (including the #).

Then set your menu link path to the tag name.

For smooth scrolling you can use the Scroll to destination anchors module.

  This module modifies the default behavior of destination anchor links...so that users will be smoothly scrolled to the destination instead of immediately being jumped.

You will need jQuery to use the Scroll to destination anchors module.


Product View does not show for Anonymous user

It turns out for every product type created there is permissions that need to be enabled for every user roles including anonymous users

'people-permissions-roles'


how to get the url to usefor a private path

You can't call PrivateStream::getExternalUrl() directly because it's not a static function; it needs an instantiated stream before you can call getExternalUrl() on it.

You can retrieve it via the stream wrapper manager's getViaUri() method:

$stream = \Drupal::service('stream_wrapper_manager')->getViaUri('private:://somefile.txt');
$stream->getExternalUrl();


OK, a better answer in the context of forum signatures only ( assuming D6 forum_signature module ) could be

Preprocess the signature.tpl.php template file and add the spam check

in template.php, function sig might be THEME_preprocess_signature, so try both, if first doesn't work.

function THEME_preprocess_signature_forum(&$variables){
  $content = $variables['signature'];
  $test = spam_content_is_spam($content, 'signature_forum');
  if (!empty($test['is_spam']) && $test['is_spam']){
   $variables['signature'] = t('This signature has been removed by our spam filter, please contact the site administrator for assistance');
  }

}

Then clear theme registry cache.

I don't use those modules myself, but such an approach, with a little tweaking, could work.


A MergeQuery just runs a SELECT and INSERT internally - there isn't a single query string available, so the __toString() method doesn't make sense (which is probably why it's short-circuited).

SelectQuery and InsertQuery both implement __toString() fully, so your best bet for debugging would be to temporarily add some code to MergeQuery::execute() to dump the $select and/or $insert query before they're run, so you can inspect the query string.


Multilanguage setup breaking View results layouts

Turns out this was due to an error in the logic of a custom template not taking in to account variable languages.


Create and expose filter in the view. This is not a full blown search but might be sufficient for your needs. If you need more advanced functionality, try Apache Solr Search Integration.


Drupal callback :: Less CSS file with variable_get()'s

It may appear like a file to the browser if you were to directly request that path in the browser, but drupal_add_css() and the LESS module deal with the file system directly and does not attempt to resolve file paths through Drupal's menu system.

drupal_add_css() will not add files that do not exist on the file system.

If you are attempting to have programmatically assigned variables within a .less file I would suggest checking out the Variables functionality that is available within the latest version of the LESS CSS Preprocessor module, documentation here: https://drupal.org/node/2139603

If you are truly trying to create a dynamically composed .less file, you first need to create the file in the files directory of the drupal install and then add that file with drupal_add_css().


Using a contrib module:
You can use the conditional_fields module.

Doing it programatically:
You can use the #states property in a custom form or form_alter hook.

You must add this to field A, B and C:

'#states' => [
  'invisible' => [
    [':input[name="field-name"]' => ['filled' => TRUE]],
    'or',
    [':input[name="field-name-2"]' => ['filled => TRUE]],
  ],
],

Of course you have to replace "field-name" and "field-name-2" with the two field names that are not the one adding the states to, hope it makes sense.

If you can’t find the name of the field you can look in the browser inspector to get the name of the input field.


You could define your query fields first, then set your field values in a loop before executing the query.

Example (not tested):

$query = db_insert('HDD')->fields(array(
  'HDDDAYS',
  'AL',
  'AR',
  ...
));

for ($s = 0; $s <= $cnt; $s++) {
  $query->values(array(
    'HDDDAYS' => $time,
    'AL' => $output1[$sts[0]][$dts[$s]],
    'AR' => $output1[$sts[1]][$dts[$s]],
    ...
  ));
}

$query->execute();


Try to switch to Garland theme to see if the problem still occurs, if not, it maybe a theme problem.


user pictures not showing up in posts & comments

comment.tpl.php is the template file which controls the view of comments in a page. You may search for this template file in your theme and edit it according to your requirement.

If you would like to customize the comments display for a specific content type the template file would be comment--node-[type].tpl.php


How to write SQL Statements With Spaces In Column Names

You can use ` try with:

$query = \Drupal::database()->select('Product_Details', 'n');
$query->addField('n', 'S.No.');
$query->condition('n.`Product type`', 'Irons');
$results = $query->execute()->fetchAll();

According to this post https://stackoverflow.com/questions/14190798/how-to-select-a-column-name-with-a-space-in-mysql you can use also [].


There are a few 'read more' link modules, like this one: http://drupal.org/project/read_more

There is also the 'teaser' display mode, as on the front page.


Quote from services.versions.api.php

  For clients that want to request a specific version they need to pass a certain header

  services_RESOURCE_METHOD_version = version
  as an example, services_system_set_variable_version = 1.2
  @see ServicesVersionTests for code examples

Make sure to use set acceptable Content-Type.

Content-Type: application/x-www-form-urlencoded

GET /v1/status HTTP/1.1
Content-Type: application/x-www-form-urlencoded
API-KEY: AAAAAAA
TOKEN: VVVVVVV
services_status_index_version: 1.1
Host: local.mywebsite.com
Connection: close
User-Agent: Paw/3.0.16 (Macintosh; OS X/10.11.6) GCDHTTPRequest


Aliases stop working after composer install

Drush has undergone some change in behavior to simplify the implementation and increase maintainability ahead of the stable release.

Rename [site].alias.yml aliases to [site].site.yml
Spit apart [sites].aliases.yml (no longer supported) into multiple [site].site.yml files
Run drush init if you would like to maintain global alias files.

If $ROOT/../drush/sites is not working, perhaps you do not have a Composer-managed site. The actual supported locations for aliases is __DRUPAL_ROOT__/drush/sites and __PROJECT_ROOT__/drush/sites. The project root is where the composer.json file is located, which is usually at $ROOT/... It might be clearer if the documentation were updated to describe the supported locations in terms of the Drupal root and Project root, as this is now the basis for finding these directories.


I didn't find a way to do it with Rate or Five Stars.

My solution is pretty simple : webforms. You can allow only one "vote" per ip with this module and you can create a view / block to display it on each node.

It does everything I needed !


How Can I send full content body field by simplenews_content_selection?

I have found my solution.

In content type manage display setting , for simplenews content selection view mode the body field must be visible .


"It is not safe to rely on the system's timezone settings."

This is a php setting, put this into php.ini:

date.timezone = 'Europe/Dublin'

All timezones:

http://php.net/manual/en/timezones.php


How to convert subset of users into a content type?

Content types are not optimal for this use case. Use entities instead.

Create an appropriate user entity to map. You can have several bundles within it to represent any relevant different types of users.

Then you will need to relate the user entities to the actual users. It's up to you how you do the relating. You can use entity references or the relation module.


After careful rereading of the user module, i realize that 2 more hidden form values need to be added so  the same delete_multiple_server_confirm_form will get called again after confirming action,otherwise the display_server_form will be rendered.

$form['table'] = array('#prefix' => '<ul>', '#suffix' => '</ul>', '#tree' => TRUE);
$form['operation'] = array('#type' => 'hidden', '#value' => 'delete');

 foreach($servers as $id) {

    $form['table'][$id] = array(
         '#type' => 'hidden',
         '#value' => $id,
         );
   }


This sounds like a perfect job for Flag module.

From the module description:

  Flag is a flexible flagging system that is completely customizable by
  the administrator. Using this module, the site administrator can
  provide any number of flags for nodes, comments, or users. Some
  possibilities include bookmarks, marking important, friends, or flag
  as offensive. With extensive views integration, you can create custom
  lists of popular content or keep tabs on important content.

For your use case, I would create a new flag for your image content type. Add the flag operation to your current views of images. Create a new view that uses that flag as a filter.


Create an Action on 'node_insert' or 'node_presave'

yeah,

for some reason, my variable needed to be initiated first.

$myvar = 0;
$myvar = $node->nid;

that's it. works now.
Problem/solution applies for Drupal 6 or 7.


Ajax validation only works when I am logged in as an administrator

These kind of errors often happen when you have not attached the proper library to your form. So one thing to check is if you have $form['#attached']['library'][] = 'core/drupal.dialog.ajax'; in your form's buildForm().


Notice: Undefined index: field_brand_image in include() in views field template

One way of doing that is using a empty to check the field as following:

<?php print (!empty($fields['field_brand_image'])) ?
  $fields['field_brand_image']->content : ''; ?>


Organic groups chat - what are my options?

I think DrupalChat might integrate with Organic Groups. According to Issue#871238 the patch in comment#2 adds this functionality.

The patch looks like it was committed to the dev branch on January 21, 2012. With the release dates of the beta11 version and the latest dev version, it looks like it might already be in those respective releases. If not, try the patch mentioned above.


How to change the price componnents order in the order total field view

Implementing hook_commerce_price_component_type_info_alter hook you can change weight of price components to change sequence. Check following example:

<?php
/**
* Implements hook_commerce_price_component_type_info_alter()
**/

function <MODULE_NAME>_commerce_price_component_type_info_alter(&$components) {
  if (!empty($components['tax|tax_on_shipping'])) {
    $components['tax|tax_on_shipping']['weight'] = 30;
  }
}


Automated backreferences between taxonomies

Disclaimer first: I am one of the relation maintainers. That said, the very reason we came up with relation is because backreferences were too hard.


db_query not returning anything (or empty) - drupal 7

The return from db_query() is a resource that you can iterate over, it's never a single value.

The way to get a single field from a query is with the fetchField() method:

$result = db_query('SELECT name FROM {users} WHERE uid = 1')->fetchField();

If you've got more than one result then you can iterate over it like so:

foreach ($result as $row) {
  // Do something with $row...
}

or, you can make use of one of the helper methods to get data directly from the query into a local variable. These include:

fetchObject()

  Fetches the next row and returns it as an object.

fetchAllAssoc()

  Returns the result set as an associative array keyed by the given field.

fetchAllKeyed()

  Returns the entire result set as a single associative array.

fetchAssoc()

  Fetches the next row and returns it as an associative array.

fetchCol()

  Returns an entire single column of a result set as an indexed array.

fetchField()

  Returns a single field from the next record of a result set.


The title can be defined from the Main views form.  Each column of the table is associated with a field.  If you select the field you can "add label" by selecting the checkbox and providing a name.  The Label will appear in the header of the table.


The details for how to implement a hook varies from one hook to another.

One of the easiest examples though, is hook_init(). Hook init is a generic way of saying "Do something on every un-cached page load". The _un_cached part is important, if you are logged out when testing this, probably nothing will happen.

In a module file named "my_module.module", one would implement hook_init like this

<?php
my_module_init() {
}

To make something actually happen, we can add a call to drupal_set_message().

<?php
my_module_init() {
  drupal_set_message('Hello Drupal!');
}

If you have Devel installed, a common way to do debugging could look something like this:

<?php
my_module_init() {
  dpm(menu_get_item());
}

For more details and examples, see What is the basic concept behind hooks?


How do I update core to only include security patches?

If you use Drush you can update all security issues with your site via (this is Core and 3rd party modules):
drush up --security-only

if you want to see what it will do, but not do any of the actual changes you can issue:
drush up --security-only --simulate

If you want an easy way to update Drupal Core to the newest release you can use a patch site such as:
http://fuerstnet.de/en/drupal-upgrade-easier


I was on the right track and made a really stupid mistake and don't know why I didn't notice it. I was deleting the correct way but I was deleting the wrong thing. I was in a loop since there are multiple addresses.

// Empty the address and location arrays if the fields were blank
if (!$found) {
    unset($node->field_micro_address[LANGUAGE_NONE][$k]);
}


Installation error in Ubuntu - The settings.php file does not exist

go to the folder where you installed drupal. Ex:

cd /var/www/drupal

then

sudo chown www-data -R sites

Now try installing again.


Basic pages are being rendered incorrectly do they differ at all to the article or custom content types in any fundamental way?

Is there something fundamentally different to basic pages that explains/ helps me to troubleshoot why the markup is different?

No, content types are completely generic. Drupal core processes them identically, but of course, custom and contrib code can heavily affect how they work.

You're going to need to check your theme, templates and custom modues, and maybe even contrib modules (depending on what you have installed and how you have them configured). The problem is with one or more of them, not with the content type itself.


Does having too many content types negatively affect site speed and performance?

The number of content types does not affect the performance of a Drupal site.

Sharing fields among the content types does affect the performance. This is because of the way CCK stores fields.

If the field is not shared and allows only one entry, it is stored along with other such fields in a table designated for that content type. That way, all such fields can be loaded in a single query.
If the field is shared or allows multiple entries, the field is stored in its own table, making an extra query (or join) per field necessary to load the field.


Show block if user has never completed Ubercart checkout

I've got it figured out, at least for my own use-case:

I use a webform to collect info on the newly-signed-up user. That webform then redirects to the checkout page with the product in the cart. I used the Webform Rules module to auto-assign a "pre-customer" role to the user when they finalize the webform. Then, when they complete the cart checkout process, that user role is removed and the "customer" user role is assigned to their account.
I've got a block that is visible only to users with the role "pre-customer". That block is the one where they will be prompted to click a link to finalize their order/payment info.

Hope this can help someone else at some point! :)


Click on the field you want to add a css class to, select style settings, and customize field html and check create a css class. Give it a name and simply add the class to the css file of your theme


Drupal 7 "The form has become outdated. Copy any unsaved work in the form below and then reload this page."

The reason you get the "The form has become outdated." error is because the token fails validation (meaning the old string doesn't match the new string). The token is determined by running a hash on several things including the session_id(). When you call user_save(), the session is changed/invalidated/whatever. Hence, when the token is tested next time around, it generates a different token because you have a different session_id() and therefore fails, thinking you were using an old form.

I have the same issue after calling user_save() from within my form processing. The way I fixed it feels like a pretty big hack, but I don't know that there's a clean way around it. The form code doesn't seem to expect that you would ever change/invalidate the session whilst in the middle of handling a form (in this case, a multi-part form).

Once you call user_save you must modify the form state manually to insert the updated token. Then, when it checks tokens your new token will match since you generated it after the 'session_id()' was updated.

So the resulting code looks like this. Notice that the input element is changed for $form_state to pass by reference so that the modification gets propagated up.

function _upload_users_phone($form, &$form_state, $operation, $returns) {
  global $user;
  // load user

  $existingUser = user_load($user->uid);

  if($operation == 'add') {
    $existingUser->field_user_phone['und'][]['value'] = $form_state['values']['phone']['prefix'] . ' ' . $form_state['values']['phone']['number'];
    $user = user_save((object) array('uid'=>$user->uid), (array) $existingUser);
    $form_state['input']['form_token'] = drupal_get_token($form['#token']);
  }
    // edit field-data
  foreach ($existingUser->field_user_phone['und'] as $key => $value) {
    $val_list[] = $value['value'];
    $key_list[] = $key;
  }

  return $val_list;
}

You might also need to set $form_state['values']['form_token'], but I'm pretty sure it's unnecessary. Again, don't forget the & in front of the declaration of the function variable $form_state or the value won't make it into the real array.


It sounds like you have something misconfigured. With the Marketplace module, you'll actually have 3 orders created. One is a Marketplace Order and one is a Store Order. It appears that your Store Orders are being displayed instead of the Marketplace Order. Check your pane configuration and ensure that you've enabled the proper marketplace modules and that your Views are showing the Marketplace Order.


Adding custom functions PHP to use in a views template

You can use a preprocess function in your template.php file. For example:

function YOURTHEME_preprocess_views_view_fields__field_name(&$vars) {
  // Do your changes for the field here
}


How do you make the list of Organic Group (OG) members of a group visible only to group members?

I would suggest you to go in Views under Block Settings > Access and try OG Permissions


I would suggest using two entity reference fields rather than one. One for storing the speakers and another one for storing the keynote speaker.

The you could place these two fields side by side and then hide the label of the keynote speaker through css.

You could also achieve this in a module using the form alter function to alter the style of the form.


The thing I didn't understand is how are you updating the nodes? you said in a single page edit? what does this mean? do you mean vbo? or is it in node page view?

Because your code seems right and should run on every node and if you are using vbo so it would be an issue related to it!

if you can explain more I'd be happy to help


Easy Solution 1

As it turns out the accordion blocks does work. However if you're just using it for a single block it won't automatically because the default jQuery accordion only works with multiple objects.

Install Accordion blocks and open the accordion_init.js file. It'll look like this

(function($) {
  Drupal.behaviors.accordion_blocks = {
      attach: function() {
        $('.accordion_blocks_container').accordion({header: "h2", autoHeight: false, });
      }
  };
})(jQuery);

You need to add the property, collapsible: true, as shown below. I've also removed the animation and made it start closed by default.

(function($) {
  Drupal.behaviors.accordion_blocks = {
      attach: function() {
        $('.accordion_blocks_container').accordion({header: "h2", autoHeight: false, collapsible: true, active: false, animated: false});
      }
  };
})(jQuery);

Possible Other Avenue

I also managed to get jQuery accordions working, it has to have a certain HTML structure (see the UI documentation) which is difficult to implement around blocks thus why I took the easy route.

But if you fancy trying it the following code will enable jQuery accordions on your website for your theme at a basic level. This code goes into the template file.

function themename_preprocess_page (&$vars) {
    drupal_add_library('system', 'ui.accordion');
    drupal_add_js('jQuery(document).ready(function(){jQuery("#accordion").accordion({ collapsible: true, active: false, header: "h3", animated: false});});', 'inline');
}


Views Contextual filter for matching taxonomy names

Yes try different "Provide default value" for this case "Taxonomy term ID from URL"

When it's available specify "Taxonomy name converted to ID"


user.routing.yml -- What is the significance of "_entity_form: user_role.default"?

In short, it means that route shows an entity form to edit the user role entity; in particular, it shows its default form.

In details, user_role is the ID for the Role class, which implements the user role entity.

@ConfigEntityType(
  id = "user_role",
  label = @Translation("Role"),
  handlers = {
    "storage" = "Drupal\user\RoleStorage",
    "access" = "Drupal\user\RoleAccessControlHandler",
    "list_builder" = "Drupal\user\RoleListBuilder",
    "form" = {
      "default" = "Drupal\user\RoleForm",
      "delete" = "Drupal\Core\Entity\EntityDeleteForm"
    }
  },
  admin_permission = "administer permissions",
  config_prefix = "role",
  static_cache = TRUE,
  entity_keys = {
    "id" = "id",
    "weight" = "weight",
    "label" = "label"
  },
  links = {
    "delete-form" = "/admin/people/roles/manage/{user_role}/delete",
    "edit-form" = "/admin/people/roles/manage/{user_role}",
    "edit-permissions-form" = "/admin/people/permissions/{user_role}",
    "collection" = "/admin/people/roles",
  },
  config_export = {
    "id",
    "label",
    "weight",
    "is_admin",
    "permissions",
  }
)

user_role.default is referring to the default form the annotation for that class describes.

"form" = {
  "default" = "Drupal\user\RoleForm",
  "delete" = "Drupal\Core\Entity\EntityDeleteForm"
}

In this case, it's the form implemented from the RoleForm class.

When you see _entity_form in a route, it always mean the route is showing a form implemented from an entity.


When to share fields between content types?

Generally if you happend to have same Field settings (Cardinality etc) you can re-use the same field. But if you want different Field settings (Not widget settings) you have to use different field.

If you have huge number of users(couple of millions) or contents it'll not be a best solution to re-use same field, because field_date_* and field_revision_* tables will end up having a lot of data and that might give you a bottleneck on performance.


How to specify the numbers of characters for teaser for views block?

I would use TRIM to achieve that. Go the desired field in the View, click "Rewrite results", there "Trim this field to a maximum length", and insert a number value.


I had a similar problem, the solution I found was here: https://drupal.org/node/1340010

If you are using webform v3.x, then you will need to apply patch #19.

If you are using webform v4.x, patch #22 (I have not tried this one).

For me, to apply the patch (on a Linux system), I did the following (adjust the first line to match where your webform module is):

cd /etc/drupal7/all/modules/webform
wget https://drupal.org/files/webform-1340010-19.patch
patch < webform-safe_key.patch

Then I had access to a new token called "%safe_key" that did exactly what I wanted (e.g. "%safe_key[field]" gave me the value of the safe_key in the email, rather than the display value.


Good. I hope you are using D7.

So lets start with the finding the machine name of the permission which get saved with the user_role when you enable the permission for particular user type.

These are them -

administer services,
get any binary files,
get own binary files,
save file information,
get a system variable,
set a system variable,
perform unlimited index queries.

Get you RID from the table ROLE by searching your NAME.ROLE

Get the list of PERMISSION from table ROLE_PERMISSION by RID.ROLE_PERMISSION

List anywhere and do what you want...

Enjoy :)


How to set proper permissions for drush rsync

The easiest solution would be to set 'remote-user' => 'vu2003', and set up the ~/.ssh/authorized_keys for that user to allow the rsync to run.


Yes, if style.css is a CSS file that's loaded into your page (either by a module or, more likely, your theme) then that's probably a good place for your custom styles.

If you'd rather have your own file for custom styles though, you can just create a file (e.g. custom.css) in your theme folder, and add a line like this to the theme's .info file:

stylesheets[all][] = custom.css

Once you clear Drupal's caches you should see the new stylesheet included in all pages using that theme.


Sorting by linked node/entity reference fields

Since you haven't been able to see the new fields for ordering (which is odd), you will probably have to perform a query alter on the views query and do some modifications:

<?php
function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'myviewname') {
    $view->query->somecodetoselectfields
    $view->query->somecodeforleftjoin
    $view->query->orderby[0]['field'] = "FIELDNAME";
    $view->query->orderby[0]['direction'] = "ASC";
  }
}
?>

What I usually do is just add a tag on the views query so that I can modify it using the standard Drupal query interface, which is much easier to use IMO.

<?php
function mymodule_views_query_alter(&$view, &$query) {
  if ($view->name == 'myviewname') {
    $query->tag[] = 'mytag';
  }
}
?>

Then

<?php
function mymodule_query_mytag_alter(QueryAlterableInterface $query) {
  $query->blablabla;
}
?>

Take a look at:

https://www.drupal.org/node/310077
https://api.drupal.org/api/views/views.api.php/function/hook_views_query_alter/7
https://api.drupal.org/api/views/plugins%21views_plugin_query_default.inc/class/views_plugin_query_default/7

Apologies if the solution is not straightforward enough.


Drupal 7 update.php Notice: Array to string conversion in update_results_page() when running custom module update

Per the docs, the return value should be a string (the message to show to the user after the update) or null.

Currently you're returning an array, hence the notice.


I think your code is good but you forget save entity .I hope this get clue to you to achieve your job.

$No=$form_state["values"]["code_NO"];
    $type_id=$form_state["values"]["type"];
    $record['type']='discount_coupon';
    $record['code']=commerce_coupon_generate_coupon_code($type_id);
    $record['commerce_discount_reference']['und']['0']['target_id'] =$type_id;
    $record['commerce_coupon_conditions']['und'][0]=Array('condition_name'=>'commerce_coupon_usage_evaluate_usage',
            'condition_settings' =>Array( 'max_usage'=> 1),
            'remove_condition'=> 'Remove',);
$entity=entity_get_controller('commerce_coupon')->create($record);
commerce_coupon_save($entity);


How do you force Drupal login to encrypt the credentials

You can't really do that.

Drupal 8 hashes and salts the password on the server side.Both the form and the authentication API require the plain password which is then validated. You should use HTTPS to protect the password during submission.

To be able to do something like this, you'd either need to use encryption, so you can decrypt again on the server or bypass the API somehow, but that isn't really possible since Drupal's hashing implementation has a dynamic salt and each hash has its own salt that you do not know in JS. Also keep in mind that anyone can read/debug the JS and figure out your salt or encryption key if you have it in JS.


Convert timezone value from seconds to W3C hour format

Ended up this this function...

// Convert timezone from second in Drupal to WC3 standard
function timezoneConvert($val, $toSeconds = false) {
  if(!$toSeconds) {
    // Starts like: "-28800" and becomes: "-08:00"
    $sec = substr($val, 1);
    $hours = intval(intval($sec) / 3600);
    $minutes = intval(($sec / 60) % 60);
    $w3cTZ = substr($val, 0, 1) .
      str_pad($hours, 2, "0", STR_PAD_LEFT) .":".
      str_pad($minutes, 2, "0", STR_PAD_LEFT);
    return $w3cTZ;
  }
  else {
    $seconds = 0;
    $units = explode(':',$val,2);
    $seconds += $units[0] * 3600; // Hours
    $seconds += $units[1] * 60; // Minutes
    return $seconds;
  }
}


I'm not familiar with the term "upstream caching / caches." I'm assuming it has something to do with edge caching... which I definitely suggest you look into; regardless of host service.  I've seen many odd occurrences because of edge caching.

Also try any of the following:

check file permissions for the ability for your web server to write the JS/CSS that it's generating.
Look in your sites/default/files or site/[site]/files directory for css and js subdirectories.  Check the permissions on those two AND delete the .css, .css.gz, .js, and .js.gz files in them.
truncate (with discretion - backup your database) all tables with a _cache at the end of them.


Where to render? Preprocess or template?

Drupal isn't consisting in this matter either I guess... In the default node.tpl.php variables are rendered while in other default templates (like html.php.php), variables are just printed.

That's not quite right. If you look at template_preprocess_html() you can see that nothing is run through render()/drupal_render(). So quite simply the variables in html.tpl.php are printed rather than rendered because they don't need to be rendered. All the vars are already strings, and no render arrays were used to build the template.

Conversely, the node content in node.tpl.php is a render array. So any parts of it that need to be rendered have to be run through render() and not just printed.

I would be tempted to follow core's example of using render() in templates, not in preprocess functions, unless you have a specific reason to do it differently.

From a performance point of view the difference would surely be negligible, but profiling the code in the context of your site and hardware is the only way to be certain.


You will have to set up multi site with the domain access module and also domain content type


Logging into Drupal from a non-Drupal site

Use Token authentication

Token Authentication provides a token for use in the URL to authenticate users to your site. It only works on paths configured in the settings page.
Originally this module was intended to offer simple authentication for RSS feeds to allow feed readers to pull customized content listings. You can now use it to provide a simple browsing experience of any Drupal content.

You would need to code a bit behind the scene - namely inject new token to proper table on successful off-site login, but it should be possible.
But maybe for your case opposite approach would be better? You can add custom submit handler to Drupal's login form to get arbitrary PHP code executed.


How to aggregate document.ready actions?

In Drupal, $(document).ready() is not used. The Drupal API uses Drupal.behaviors.

You didn't mention your version of Drupal. But you can read about the Drupal 7 JavaScript API here: https://www.drupal.org/node/756722

Here is Drupal 8: https://www.drupal.org/node/2269515

And here is a pretty comprehensive breakdown/tutorial I wrote on using the D7 API: http://www.jaypan.com/tutorial/high-performance-javascript-using-drupal-7s-javascript-api


So that means it will become the active revision shown to users. So if a revision is published its got to become the default revision as it will be shown as the page content for normal users

When you select "Archived" for a piece of content you'd want that to become the default revision too so that when users look at the page they'd see access denied. But you wouldn't have the published option ticked for "Archived"

And draft you wouldnt want to become the default revision because it's not supposed to be shown to users in that state


Custom module files written in Windows aren't being recognized when migrated to Linux

I believe I've figured it out. This issue may not be consider specific to Drupal but Drupal does seem to be a little more particular about files copied over from a Windows dev site.

To get the files to work I had to do two things and in this order:

Recursively convert all files in "/path" from Windows format to Linux format.

  find /path -type f -print0 | xargs -0 dos2unix

Even after doing step #1 Drupal didn't like the files. I ran this to build a new directories.

  rsync -r /input-path /output-path


If I'm not mistaken, Features doesn't delete fields it only synchronizes the configuration and creates new fields if they are not present. So, deleting obsolete fields is one of the processes you have to do by hand (or write an update function in a custom module).

Features is a handy tool, but certainly has some limits (for instance when you want to synchronize blocks).


Removing potentially malicious code from template

The script may be included from any of the files involved in the build and render pipeline of Drupal as it outputs a page so it's tough, as you say, to pinpoint the single file (it may also affect multiple files). It may also be stored in the database via something included on every page.

So, instead of spot cleaning it's recommended that you start fresh with known-to-be safe Drupal files by importing your database and custom code over a new Drupal install. Drupal provides documentation for handling a hacked site that details why this is a better strategy.

You may have been hacked via the SA-CORE-2014-005 Drupal core vulnerability but even if not this detailed rollback blog post may also help http://befused.com/drupal/drupalgeddon


How to change the number of Administration Views results in the Drupal back end?

To my knowledge, there is no such thing as a "global setting" within Drupal administration (what you call "back end") to set such "how many results".

The only way to do so (assuming you use Drupal 7), is to perform these steps for each of the individual views where you want to set "how many results" you want:

Use the Views UI to edit the view.
In the 2nd column, within Pager:

Use pager:  use the options "Display a specified number of items".
Pager options: set the "Items per page" to "how many results" you want.


Text Resize but with defined font sizes?

You can use Text Size. It provides 3 buttons and also has settings for increment/decrement step.

step 1: go to admin/config
step 2: User interface -> Text Resize click
step 3: tick Add Reset Button then save


How can I count a multivalue field's values in twig?

{{ node.field_mytext.count }} => faced with error

This does not work, because the method count is not allowed in twig policies:

  core/lib/Drupal/Core/Template/TwigSandboxPolicy.php

{{ content.field_mytext | length }}?

This does not work, because content is a render array with a lot of additional keys.

This works: Convert field to array and count

{{ node.field_mytext.getvalue | length }}


"You need to be logged in to view that page" alert for authenticated user

First off, checking access as user 1 or Administrator is not a test because no permission checks are done for user 1, and in most cases Administrators have all permissions.

Two, your permission is mixed case, change it to all lower case and clear the cache.

Three, in order to access anything under /admin, user will also need access administration pages permission as well - or whatever permission is assigned on that menu item (I think that’s the one).


Download Update's fail (Unix File Permissions on /tmp directory)

You probably have your own tmp directory, which is not /tmp but /some/path/to/your/directory/tmp. You wouldn't be allowed to create /tmp2 for sure :)

To find that out, go to admin/reports/status/php and look for _SERVER["DOCUMENT_ROOT"], that will tell you where Drupal is located and from there, you should be able to build the path to your tmp directory.

Then set the temporary directory to that.


How to theme the table view mode which is showing entities in inline entity form

Most simple solution should be to override the table.html.twig template. You can simplify it to your needs in your theme's template directory. Use the core/themes/classy/templates/dataset/table.html.twig file as source to start your theming.

If you don't want to "re-theme" all tables, add "suggestions" for other templates to your tables and create template files accordingly.


Remove module dependency in multi-site D7 setup?

Try this.  Without disabling the module, remove the code for your local video module, leaving the code you want in sites/all/modules. Next, run drush registry-rebuild followed by drush updatedb.  See: http://drupal.org/project/registry_rebuild

IMPORTANT NOTE: Your globally installed video module is 7.x-2.2, but your local module is 7.x-2.7.  You can't go backwards in version numbers in Drupal, so you'll have to upgrade your global video module to 7.x-2.7 and run updatedb on all other sites that use it before following the instructions above. If you can't upgrade the global module, you'll have to keep them separate until you can.


it is no right at all, this is the right way to make an OR:

$form['problem'] = array(
  '#type' => 'textarea',
  '#title' => t('Problem'),
  '#states' => array(
    'visible' => array(
      array(
        ':input[name="product_type"]'=> array(
          array('value' => 'b'),
          array('value' => 'c'),
        ),
      ),
    ),
  ),
);

Regards


How do I change the HTML surrounding a particular node?

Enable theme_debug mode, once it is done you can find which .tpl file the particular section in the firebug. For enabling theme debug mode drush vset theme_debug 1

In the firebug, you can find which .tpl file the section is using.


Custom content type which is a check list

Looks like you are looking for Checklist module:

  Allow administrators on sites to create checklists that must be completed by users of the site.


Show a view of Related Terms to a given Taxonomy term

I have done the same thing through Panels. I was stuck with views for a long time. All you have to do is to override the "Taxonomy Term Template" in panels. Add a new Variant with settings of your choice (default ones would be fine too). Go to 'content' section and add new one. Choose 'list of related terms' and inside it you would find the related terms you need. Make sure you give it a valid path and there you have it!

I don't know how this could be done in views but for me this is more than fine.. :)


Rendered Webform has no Javascript attached

Now you return bare HTML without any attached meta data for caching, libraries and so on.

Also Webforms provides a render element, so this is all you need to build a webform:

$build = [
  '#type' => 'webform',
  '#webform' => $machineName,
];

The important part though is that the filter you put the token in handles the attached metadata correctly. It needs to do it similar to Entity Embed:

    $result = new FilterProcessResult($text);
    ...
    // We need to render the embedded entity:
    // - without replacing placeholders, so that the placeholders are
    //   only replaced at the last possible moment. Hence we cannot use
    //   either renderPlain() or renderRoot(), so we must use render().
    // - without bubbling beyond this filter, because filters must
    //   ensure that the bubbleable metadata for the changes they make
    //   when filtering text makes it onto the FilterProcessResult
    //   object that they return ($result). To prevent that bubbling, we
    //   must wrap the call to render() in a render context.
    $entity_output = $this->renderer->executeInRenderContext(new RenderContext(), function () use (&$build) {
      return $this->renderer->render($build);
    });
    $result = $result->merge(BubbleableMetadata::createFromRenderArray($build));

https://cgit.drupalcode.org/entity_embed/tree/src/Plugin/Filter/EntityEmbedFilter.php

Edit: Improved bubbling of metadata:

    $render_context = new RenderContext();
    $entity_output = $this->renderer->executeInRenderContext($render_context, function () use (&$build) {
      return $this->renderer->render($build);
    });
    $meta_data = BubbleableMetadata::createFromRenderArray($build);
    if (!$render_context->isEmpty()) {
      $meta_data = $meta_data->merge($render_context->pop());
    }
    $result = $result->merge($meta_data);

If you are looking for an easier solution you could for example add the webform to $variables in preprocess to render it in a node template. Then the attached libraries bubble up in the right place automatically.


Hierarchical select as radio buttons and checkboxes

For drupal 6 you may want to check out the module https://drupal.org/project/conditional_fields which basically lets you control which form elements depend on other form elements. It also has a handy GUI for doing this.

FYI drupal 7 has completely changed the game here and has implemented 'states api' - here is an example of what can easily be achieved - http://api.drupal.org/api/examples/form_example--form_example_states.inc/function/form_example_states_form/7


how to create views with month and day in contextual filter

I achieve this with below solution,
create birthday field filter in views and set it to something fix =2000-02-02(not important later it will bypass),
then in my custom module  I implement hook_views_query_alter and change condition to what I want  "DATE_FORMAT(field_data_field_birth_date.field_birth_date_value, '%m%d') = :field_data_field_birth_date_field_birth_date_value"; and work correctly,and views page path is sbirthdaymd/% ( as example link will be something like sbirthdaymd/0524 )

/**
 * Implements hook_views_api().
 */
function mymodule_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'mymodule'),
  );
}

/**
 * Implementation of hook_views_query_alter
 * @param $view
 * @param $query
 */
function mymodule_views_query_alter(&$view, &$query) {
    if($view->name == 'search_cast_by_birth_and_death') {
//        ym($view->query,'message');
        $url = parse_url(current_path());
        $temp = explode('/', $url['path']);
         if(!intval($temp[1]))
             $temp[1]="0406";
        if($view->current_display=='page_2'){
        $view->query->where[1]['conditions'][2]['field']="DATE_FORMAT(field_data_field_birth_date.field_birth_date_value, '%m%d') = :field_data_field_birth_date_field_birth_date_value";
        $view->query->where[1]['conditions'][2]['value'][':field_data_field_birth_date_field_birth_date_value']=$temp[1];
        }

     }
    }


How to extend a view plugin style implemented by another module?

First you need to have a my_module.views.inc, which can have basically the same contents as http://drupalcode.org/project/leaflet.git/blob/refs/heads/7.x-1.x:/leaflet_views/leaflet_views.views.inc, but with changed names.

You can leave the handler the same, in which case you need to leave the path the same too. Otherwise you can create your own hadler in my_module_views_plugin_style.inc along the lines of

class my_module_views_plugin_style extends leaflet_views_plugin_style {
   // ...
}

You then only need to define any methods that you want to modify:

function option_definition() {
  $options = parent::option_definition();
  // your changes here
  return $options;
}

You also need a theme file. If you are modifying the display at all, you probably need to just copy the theme file over from the dependency, and change the 'theme' line in my_module.views.inc.


How to create dependent dropdown in drupal 7 content type?

you need to create a tour and location used Node reference module. And automatically change the drop down  option value of location based on tour option value that you can use ajax .  following url help to u

Dynamic select list in the form (dependent dropdown)

https://api.drupal.org/api/examples/ajax_example!ajax_example.module/function/ajax_example_dependent_dropdown/7


Entityform - "The form has become outdated." error

It looks like you may have a hook namespace collision with hook_form().

Although that might only be called if you're defining a node type, it's probably worth using a more specific function name for your form builder (e.g function foiagen_generator_form). Also make sure you're returning the form build array (array of elements), and not the rendered form in your form build function.


Using Contextual filter in Filtering attached view

The contextual filters belong to the first filter group so if you click the little arrow besides the Filter "add" then choose "and / or" then you can switch the operator of the first group to OR.


Form Submit Handler not firing on Page Reload with GET parameters

The correct way to change the method to be used by a form is to use the #method element rather than by setting the attribute, as otherwise the form API will still expect to be triggered by a POST.

https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#method


Drupal 8: Upload Validation form alterations ignored

Clive was spot on. Turns out I wasn't passing my variable by reference. I was thrown off by (what is now old hat in Drupal 8) returning the form variable at the end of the form_alter hook.


How to use hook_views_query_alter to add field with no table in Drupal 7 Views 3

I had the same problem. And I've solved it.

    function ModuleName_views_query_alter(&$view, &$query) {
  if ($view->name == 'my_view' && 'my_block_name' == $view->current_display)) {

    $formula = "3956 * 2 * ASIN(SQRT(POWER(SIN(($postcode_lat - abs(lat))*pi()/180/2),2) + COS($postcode_lat * pi()/180) * COS(abs(lat) * pi()/180) * POWER(SIN(($postcode_lng - lng) * pi()/180/2),2)))";

    // Sets the formula's alias.
    $query->add_field(NULL, $formula, 'distance');
    $query->add_where(0, "$formula < 500", array(), 'formula');

    // Sets the order by reference
    $query->orderby = array(
      array(
        'field' => 'distance',
        'direction' => 'ASC',
      )
    );
  }
}

See http://roldanarts.com/2013/11/22/diego-f-roldan/blog/using-formulas-views-hook-views-query-alter for more details.


To set the status you can use the setPublished() method:

  public function Node::setPublished

  Sets the published status of a node..

  Parameters

  bool $published: TRUE to set this node to published, FALSE to set it
  to unpublished.

In your case:

$node = \Drupal\node\Entity\Node::load($nid);
$node->set("body", 'New body text');
$node->set("field_name", 'New value');
$node->setPublished(TRUE);


When is it appropriate to run a drupal_bootstrap?

In order to bootstrap Drupal from another PHP script, you can use below code:

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

When ever you would like to call Drupal Functions or features outside of Drupal root you can use above code..


View page not filtering content according to its language

Click "Add" on "Filter Criteria" on the left column. Then add a filter called Content: Translation language and set it to Content language selected for page


Exclude content referenced by content whose author is current logged in user

Try this,

Add a contextual filter of Content: Author uid.
Under "WHEN THE FILTER VALUE IS NOT AVAILABLE", select "provide default value", and then select "User ID from logged in user".
Under MORE, select "Exclude".
Save.

P.S. This should work. Haven't tried myself.


Calendar with multiple content types on multiple field types

You're not going to get Views to add the 2nd content type (and only the 2nd content type) in this way, at least not through the Views UI. You could do this by programmatically altering the view's query or something like that, but it would be no fun.

I would recycle the "date" field from content type a into content type b and set the default value = now; that way when a new node is created it will have that value by default.


Ldap group configuration - Derive from attribute

I've handled this by calling a update user account function during validation against the AD.

First fetch the attributes of that account:

$filter = "(sAMAccountName=" . $username . ")";
// This is where you will need to add in extensionattribute14.
$attributes = array('sAMAccountName', 'givenName', 'sn', 'description', 'telephoneNumber', 'userAccountControl', 'distinguishedName', 'memberOf', 'proxyAddresses', 'Mobile', 'facsimileTelephoneNumber', 'mail', 'employeeNumber');
$result = ldap_search($conn, $ldap_base_dn, $filter, $attributes) or exit("Unable to search LDAP server");
$entries = ldap_get_entries($conn, $result);
$entryid = ldap_first_entry($conn, $result);
$attrs = ldap_get_attributes($conn, $entryid);

And then then call the update account function ($attrs from above is passed in as $values):

/**
 * Makes updates to the users account based on values passed from the AD
 * @param  object $account
 * @param  array $values
 */
function update_user_account($account, $values) {

    // ...
    // Code here to update other values from the AD
    // ...

    if(isset($values['memberOf'])) {

        // Loop over groups.
        foreach($values['memberOf'] as $k => $group_dn) {

            switch($group_dn) {
                case 'CN=GRPHO Intranet Editor,OU=Groups - Restricted,DC=universe,DC=int':
                    $updates['roles'][8] = 'Editor';
                    break;
                case 'CN=GRPHO Intranet User Editor,OU=Groups - Restricted,DC=universe,DC=int':
                    $updates['roles'][9] = 'User Editor';
                    break;

                // etc. etc.

            }

        }
    }

    // add back in any roles that this user had that are not controlled from the AD
    if(isset($account->roles[3])) $updates['roles'][3] = 'administrator';
    if(isset($account->roles[15])) $updates['roles'][15] = 'site admin';

    user_save($account, $updates);

}


One way to accomplish this would be by using a service tagged with the path_processor_outbound service tag.
Your service should then implement the processOutbound() function in order to modify all links on a page, if the request delivers a node object of the type you want.

This is an example service definition using the described service tag:

services:
  dummy.link_modifier_service:
    class: Drupal\dummy\DefaultService
    tags:
      - { name: path_processor_outbound }
    arguments: ['@request_stack']

This is an example implementation of such a service:

<?php

namespace Drupal\dummy;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Render\BubbleableMetadata;

/**
 * Class DefaultService.
 */
class DefaultService implements DefaultServiceInterface, OutboundPathProcessorInterface {

  /**
   * Symfony\Component\HttpFoundation\RequestStack definition.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;
  /**
   * Constructs a new DefaultService object.
   */
  public function __construct(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
  }

  /**
   * {@inheritdoc}
   */
  public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {

    if (empty($request)) {
      $request = $this->requestStack->getCurrentRequest();
    }
    $node = $request->attributes->get('node');
    if ($node && $node->bundle() === 'product') {
      $options['query'][] = [$node->bundle() . '_id' => $node->id()];
    }
    return $path;
  }

}

This code will now be modifying all Drupal-handled URLs and adding a product_id=XX parameter to them.

Hope this helps, good luck!

@see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21PathProcessor%21OutboundPathProcessorInterface.php/function/OutboundPathProcessorInterface%3A%3AprocessOutbound/


Is there a way to search for instances of hook_views_query_alter() in my database?

Views field output can also be rewritten under the view's fields setting in the views interface using "rewrite the output of this field" using tokens from previous rows or arbitrary HTML. That's the likeliest place.

If not there, the next candidate for views output modification is in the theme template files. People will stick any kind of logic in views theme template files. To see if custom template files are in use, see "Theme: Information" in the views and the template file in use will be in bold.

Generally, hook_views_query_alter is not the normal way of modifying a view. But a hook_views_query_alter would be added in the code rather than the database. Drupal does cache a list of implemented hook functions in a the theme registry table, but that's not very readable nor informative. Not where you should be looking. Your best bet is to search your code for "_views_query_alter" and see what you turn up. There will be a lot of results, but likely you'll recognize any custom modules.

I might also turn on Show SQL Queries in under Views->Settings to see the output of the views query as views reports it as it's being run in the Views preview interface below the view builder interface. Then you can see the query being run to see if it matches your expectations.

There is also a setting in views under Advanced -> Query to turn off SQL rewriting for a view. This will disable access checks as well as some query rewriting (but not all) so use sparing.


if ($form_id == 'register_node_form'){
    global $user;
    if(isset($form_state['build_info']['args'][0]->field_event_ref[LANGUAGE_NONE][0]['nid'])){
       $nid = $form_state['build_info']['args'][0]->field_event_ref[LANGUAGE_NONE][0]['nid'];
    }  else {
    $nid = $form_state['build_info']['args'][0]->field_event_ref[LANGUAGE_NONE][0]['nid'] = arg(3);
    }
     $form_state['build_info']['args'][0]->field_event_ref[LANGUAGE_NONE][0]['nid'] = $nid;


How to add nodes inside admin area, e.g. for admin documentation

This can be done using Administration theme module:

  The Administration theme module allows you to use this theme on more pages like :

  batch processing pages
  devel node load and render pages
  coder code review pages
  pages you define yourself in the provided textarea

Emphasis mine.


Try this:

# only if a particular domain
RewriteCond %{HTTP_HOST} ^mysite\.domain\.org$ [NC]
# rewrite the URL
RewriteRule ^((?!Library).*)$ http://otherdomain.org/$1 [R=301,L]

The (?!Library) should look ahead, and the match should fail if "Library" is present. Hope this works for you.


Creating a "scrapbook" node type using an entity reference field

Personally, I'd move the entity relationship field to the press clipping content type, so you get the convenient dropdown there, and use the reverse relationship, or contextual filter when building a view


Paragraph's fields value loaded in a custom controller are in the default language instead of the current language

Based on the comments I changed $game->get('field_stages')->getValue(); for $game->get('field_stages')->referencedEntities();. This allow me to greatly simply a part of the code.
To load the correct language I added $paragraph = \Drupal::service('entity.repository')->getTranslationFromContext($paragraph); inside the loop. Using getTranslationFromContext on the $game didn't works for the paragraph.
I'm not 100% satisfied as I feel translation should be loaded directly when all the fields are loaded with referencedEntities(). But it works and perhaps caching do some magic behind the scene.
This answer helped a lot https://drupal.stackexchange.com/a/269493/1761
// Load the game
$game = \Drupal::entityTypeManager()->getStorage('node')->load($gameID);

$stages = [];

// Get all the stage of the game
$paragraph_field_items = $game->get('field_stages')->referencedEntities();

if (!$paragraph_field_items) {
    throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException('This game has no level');
}

/** @var \Drupal\paragraphs\Entity\Paragraph $paragraph */
foreach ($paragraph_field_items as $paragraph) {

  // Get the translation
  $paragraph = \Drupal::service('entity.repository')->getTranslationFromContext($paragraph);

  $description = [
      '#type' => 'processed_text',
      '#text' => $paragraph->get('field_description')->value,
      '#format' => 'basic_html',
  ];

  $stages [] = [
      'title' => $paragraph->get('field_title')->value,
      'image' => $paragraph->get('field_image'),
      'description' => $description,
      'east_lv95' => $paragraph->get('field_east_lv95')->value,
      'north_lv95' => $paragraph->get('field_north_lv95')->value,
  ];
}


Unexpected Entity Reference Autocomplete behaviour

I think you might have not specified the "label" column in the entity definition. That goes within the 'entity keys' array, like the 'id' key.

$entity_info = array(
   .....
  'entity keys' array(
    'id' => 'primary key column...',
    'label' =>  'column holding the label'
  ),
)

Otherwise entityreference will not know which column to use for searching in the DB. That still makes it possible to show the label  (as you're experiencing) after you reference the entity, because 'label' key is not mandatory, and you may have specified a "label callback" instead, which the Entity API will use when entity_label() is called to get the label of a specific entity.

If adding the 'label' column and flushing all caches doesn't solve your problem, I think I'd need the entity definition to be able to help!


"fwrite(): supplied argument is not a valid stream resource"

You should not run drush.php directly.  It is preferable to define DRUSH_PHP, like this:

export DRUSH_PHP='/usr/local/bin/php'

Then you may continue to use the drush script as usual.  This is documented in the README.


Yes, you can do it by clicking the execute link in your components tab.

OR, you can click the schedule link and schedule something to run 1 min from now. Just remember that your scheduled action will only run after cron runs. So if you have set cron to run once a day or every 1 hour, it won't happen until then. So will have to manually run cron, by clicking the run cron button to see if it gets delivered after 1 min from now.


Url adds zero at the end and duplicate contents appearing

This is a common way how url aliases are generated - if there are nodes with the same title, it appends the "0" (and "1", "2" for more duplicates).

So if you really need nodes with duplicate title, you can edit the path alias manually on node edit form to something else. But from the seo point of view, its not a good practice to have multiple pages with same title.

The best option in my opinion is to avoid such duplicates completely. For your situation, you can use Remove Duplicates module to delete duplicate nodes based on the node title.
(For drupal 6, you have to do some coding - here)

One more idea: if the case is that you have multiple content types and you need two nodes of different types to have the same title, change the alias rules so that different types have different urls (e.g. blog/my-title and article/my-title)


How to change dropdown field function to buttons in privatemsg module

You can implement hook_privatemsg_thread_operations_alter(&$operations) (unfortunately not documented but called in _privatemsg_action_form()) to change the mark as read and mark as unread operations to use a button, as does delete. They are defined in privatemsg_privatemsg_thread_operations().

Something like this:

<?php
function yourmodule_privatemsg_thread_operations_alter(&$operations) {
  $operations['mark as read']['button'] = TRUE;
  $operations['mark as unread']['button'] = TRUE;
}
?>

Note: This requires Privatemsg 6.x-2.x


Why with new bootstrap 3x-3.13 it doesn't work?

First of all, bootstrap is a theme not module.
You were using following code to above the main container(outside the image area as soon in your attachment):

function mytheme_preprocess_block(&$variables) {
  $block = $variables['block'];

  // Create css id attribute based on the block's administrative name
  if ($block->module == 'block') {
    $custom = block_custom_block_get($block->delta);
    $id = strtolower($custom['info']);
    $variables['block_html_id'] = $id;
  }
}

If you were using this code in bootstrap theme's template.php, instead of a child theme, than after updating the theme the custom code will be no more there as the old files are replaced by new updated files.

So you need to add your code in new template file updated.


Drupal Webform Select 2 options instead of unlimited

You can do client-side checking for the number of items selected, and if greater than 2, you can add your desired behavior, such as clearing the selections and/or alerting the user.

Example with jQuery:

var selectID = '#your-select-ID'; // change this to your selector
$(selectID).change(function () {
  if ($(selectID + " option:selected").length > 2) {
      $(selectID).val([]); // clear the selections
      // do other stuff if you want, like alert('Can only select 2 options');
  }
});


How do I apply a custom set of blocks to a custom content type

This depends on the information you would like to show in the sidebar. If you want to show some static information like for example a help text, then you can create a block in admin / structure / blocks. After you added a new block, you can modify the visibility settings of this Block (and many other settings). For example set the block to to show only on a specific path, content type or whatever.

The other way or case you might have, is to show dynamic data which has a relation to the content you're currently looking at. These dynamic blocks can be built for example with Views or you can create them programmatically in an own module.

The placement of the blocks works like on the first case. But there are other ways to place a block (e.g with Context).


Render a custom region inside node template

You should load your menu yourself inside node, use:

hook_node_load
hook_node_view
hook_preprocess_node


Form API: Autocomplete Field in Chrome and Safari

If it works on Firefox, I suspect that the issue is with the javascript.  Here, the question you should be asking is: do you really need to write your own.

In Drupal 7, there's a default implementation of the javascript you need for this in misc/autocomplete.js.  In fact, by defining your callback via '#autocomplete_path', you are likely asking for trouble: both your javascript handler from your .js file and the javascript from misc/autocomplete.js may well be completing with each other to handle the textfield. I would not be in the least surprised if the behavior you saw was browser dependent.

Unless there's a specific reason you need the javascript you've written, I'd just use the default javascript, which will get automatically loaded for you when you use the '#autocomplete_path' Form API key.  AFAICT, your callback and your hook_menu definitions are just fine.

However, you can find a nice sample in the Examples Module (https://www.drupal.org/project/examples). Where your implementation differs, the simpler implementation in the Examples code may well be more cross-browser compatible.


indexing first letter of items to make an A-Z type glossary, using solr backed and search api

OK, it's a little late. But yes, you can index a glossary. I've build an A-Z-Filter in SOLR based on custom entity-fields like surname here http://www.autorenwelt.de/verzeichnis/menschen My filter based on the following description: https://drupal.org/node/2069005

I need only this functions to build a field in the SOLR index:

/**
 * Apachesolr index name for this module.
 *
 * Dynamically creates name as expected by Solr.
 */
function _MODULENAME_search_index_key($key) {
  $index = array(
    'name' => $key,
    'multiple' => FALSE,
    'index_type' => 'string',
  );
  return apachesolr_index_key($index);
}

/**
 * Implementation of hook_apachesolr_index_document_build()
 *
 * Alters what is sent to Solr in $document.
 */
function MODULENAME_apachesolr_index_document_build($document, $entity, $entity_type, $env_id) {
    $glossary_key = _MODULENAME_search_index_key('custom_glossary');
    // We want to index the first letter of the title for use in our glossary
    $key = strtoupper($entity->title[0]);
    // Build a custom glossary of profile2 entities
    if ('profile_main' == $entity->type) {
        $key = strtoupper($entity->field_profile_surname['und'][0]['safe_value'][0]);
    }

    $indexed = '0 - 9';
    switch ($key) {
        case 'A':
        case 'B':
        case 'C':
        case 'D':
        case 'E':
            $indexed = 'A - E';
            break;
        case 'F':
        case 'G':
        case 'H':
        case 'I':
        case 'J':
            $indexed = 'F - J';
            break;
        case 'K':
        case 'L':
        case 'M':
        case 'N':
        case 'O':
            $indexed = 'K - O';
            break;
        case 'P':
        case 'Q':
        case 'R':
        case 'S':
        case 'T':
            $indexed = 'P - T';
            break;
        case 'U':
        case 'V':
        case 'W':
        case 'X':
        case 'Y':
        case 'Z':
            $indexed = 'U - Z';
            break;
    }
    $document->{$glossary_key} = $indexed;
}

And I use hook_facetapi_facet_info_alter to register this facet:

/**
 * Implementation of hook_facetapi_facet_info_alter().
 **/
function MODULENAME_facetapi_facet_info(array $searcher_info) {
    $facets = array();
    // Facets are usually associated with the type of content stored in the index.
    if (isset($searcher_info['types']['node'])) {
        $facets['ss_custom_glossary'] = array(
            'default widget' => 'links',
            'name' => 'ss_custom_glossary',
            'label' => t('A - Z Glossar'),
            'dependency plugins' => array('role'),
            'description' => t('Glossar basierend auf dem ersten Buchstaben des Node-Titles.'),
            'field' => 'ss_custom_glossary',
            'field_alias' => 'ss_custom_glossary',
            'weight' => -50
        );
    }

    return $facets;
}

Ciao
Ralf


Workbench moderation repeats "Save and " in the button labels

Save and has been hardcoded in the Workbench Moderation module.


I suggest you, use this module https://www.drupal.org/project/pdf_to_imagefield since colorbox is designed to display images.

If you still want to show the complete pdf. You could embed it in a basic page:

        Download file

You can then reference the page by node id.

 Link name


How to show loader image before popup screen of color box module in drupal 7

Hope this will help you,

You can use Colorbox Callbacks

onOpen : Callback that fires right before Colorbox begins to open
onComplete : Callback that fires right after loaded content is displayed

jQuery.colorbox({
........
  onOpen:function(){
    //show loader
  }
  onComplete:function(){
   //hide loader
  }
});


Bugs bugs bugs.

    'entity class' => 'Drupal/myentity/class/MyEntity',
    'controller class' => 'Drupal/myentity/controller/MyEntityController',

This should be

    'entity class' => 'Drupal\myentity\class\MyEntity',
    'controller class' => 'Drupal\myentity\controller\MyEntityController',

And:

namespace Drupal\myentity\class\MyEntity;

This should be

namespace Drupal\myentity\class;

(and btw, is "class" really a valid namespace part? Won't PHP complain?)

And:

sites\all\modules\myentity\lib\Drupal\controller\MyEntityController.php

This should be:

sites\all\modules\myentity\lib\Drupal\myentity\controller\MyEntityController.php

EDIT: One more:

class MyEntity extends Entity {

should be

class MyEntity extends \Entity {

Because class Entity is in root namespace.


CKEditor simple image upload functionality

If you ever get to D7, this module does exactly what you're looking for:

One Click Upload module

  Button for BUEditor and CKEditor which allows upload files in one click.

  Features

  Upload images and insert into editor image code
  Upload files and insert into editor link code
  Multi-upload files and images
  Integration with image styles
  Editable html templates


I think you do it  in  the right way, but instead of using this

$block['content'] = 'Добавить ' . variable_get('content_type_name', false) . '
';
$block['content'] .= 'Выход';

you should use l function

  This function correctly handles aliased paths, and adds an 'active'
  class attribute to links that point to the current page (for theming),
  so all internal links output by modules should be generated by this
  function if possible.

like this:

$block['content'] .= l(t('Выход'), '/logout');


How to load into a normal page instead of the (blog-like) front page?

it is a bit confusing your question. But I try help you.

First, did you create a view called 'NEWS' (in Structure -> Views)? OK great, make this view accessible by url '/news'. (if not, make this sentence true).

Check if your 'HOME' view is set to < front> (url '/home', same url that you set in Site information page - with '/home') and make it accessible.

Then, edit the 'main content' block (in Structure -> Block Lay out) to only appear in NEWS page.

This is for drupal 8, but seems to be almost the same for drupal 7 (same modules, Block and Views).
PS: Edit your question and add a tag with your drupal version.


After Update to 8.5.6, "Add" Links Missing From Page but still are in router

Thank you everyone for your feedback.

We ended up wiping the whole server and starting over.  I had done various updates manually by dragging and dropping. We re-installed Drupal and this time around used composer and drush.  That solved the issue. I was not able to ever FINALLY diagnose what happened.


Display content having the taxonomy of the logged in user

Create a view to display the article content, then add as relation for user and  add a contextual filter for UID for logged in user.

Add new filter for content taxonomy and it must be equal to user taxonomy.


Calling ajax function from jquery on change event

Can I attach an ajax call to an on change event that will reload the
  text field without reloading the page?

If that's your question, then the answer is yes, you can.

If you meant to ask how to do that, then please refer to Ajax Forms documentation for Drupal 8 or Drupal 7.

If you hit any problem when implementing it, then come back giving us the details of specific issue as provided information does not describe what the problem is.


What you get currently is what you asked for: leftJoin.

To get only the single object you're looking for, you must use join instead (which is default and equivalent to innerJoin).

BTW you may simplify your code using the short notation, like this:

$query = db_select('node', 'n')
  ->fields('n', array('nid', 'title', 'type' ))
  ->fields('b', array('body_value'))
  ->fields('ttd',array('name'))
  ->join('field_data_body', 'b', 'b.entity_id = n.nid')
  ->join('taxonomy_index', 'ti', 'ti.nid = n.nid')
  ->join('taxonomy_term_data', 'ttd', 'ttd.tid = ti.tid AND ttd.vid = "5"');


How do I create a simple breadcrumb with pathauto?

I guess easy_breadcrumb module would be good to use for this scenario.

  The Easy Breadcrumb module provides a plug-and-play block to be embedded in your pages, typically at some place near the page's header. Easy Breadcrumb uses the current URL (path alias) and the current page's title to automatically extract the breadcrumb's segments and its respective links.

Example: URL like gallery/videos/once-a-time-in-cartagena, Easy Breadcrumb will automatically produces the breadcrumb as

  Home >> Gallery >> Videos >> Once a time in Cartagena

or

  Home >> Videos >> Once a Time in Cartagena

Again, the breadcrumb presentation will vary depending on your module's settings.


Is it possible to write test against the current database?

The testing environment is by default completely separated from your website, so module testing is in no way affected by the environment. However you might be able to switch the database. There is this article about testing on the live database: http://www.codesidekick.com/blog/break-out-simpletest-sandbox. Basically you override some variables during setup and teardown in a class extending DrupalWebTestCase:

/**
 * @file
 * Common testing class for this Drupal site.
 */
abstract class SiteTesting extends DrupalWebTestCase {

  /**
   * Overrides default set up handler to prevent database sand-boxing.
   */
  protected function setUp() {
    // Use the test mail class instead of the default mail handler class.
    variable_set('mail_system', array('default-system' => 'TestingMailSystem'));
    $this->originalFileDirectory = variable_get('file_public_path', conf_path() . '/files');
    $this->public_files_directory = $this->originalFileDirectory;
    $this->private_files_directory = variable_get('file_private_path');
    $this->temp_files_directory = file_directory_temp();

    drupal_set_time_limit($this->timeLimit);
    $this->setup = TRUE;
  }

  /**
   * Overrides default tear down handler to prevent database sandbox deletion.
   */
  protected function tearDown() {
    // In case a fatal error occurred that was not in the test process read the
    // log to pick up any fatal errors.
    simpletest_log_read($this->testId, $this->databasePrefix, get_class($this), TRUE);

    $emailCount = count(variable_get('drupal_test_email_collector', array()));
    if ($emailCount) {
      $message = format_plural($emailCount, '1 e-mail was sent during this test.', '@count e-mails were sent during this test.');
      $this->pass($message, t('E-mail'));
    }

    // Close the CURL handler.
    $this->curlClose();
  }
}

Then in the test, make sure to extend your newly created class:

class SiteTestingHomePageTest extends SiteTesting {
  ...
}

I have never tried this, and please be aware that depending on the test, they might alter the live database (if you add a node in the test, it will show up on the site), but it might be what you are looking for. Make database backups and remove all created entities in the end of the test.

If you do not want to affect live data, you will have to add the content types and taxonomy terms manually.


Login form - hook_form_alter destinations broken

I think in D7 you can also use the redirect property, this would be in your form_alter:

  $form_state['redirect'] = array('http://www.example.com/my-external-path', array('external' => TRUE));

$form_state['redirect'] takes the same values as drupal_goto(), which itself uses url() to generate its destination path. It is possible to add an array of options including 'external=TRUE' to your redirect value if redirect is external.

Not sure if this will help in your case though.


Using custom author name in a node instead of author field

There is a module for it. You can choose which custom user field to use. This module only works for drupal 6 and drupal 7 https://www.drupal.org/project/realname


For the field template there is by default no suggestion with the specific display mode.

You can add this suggestion in a hook:

function MYTHEME_theme_suggestions_field_alter(&$suggestions, $variables) {
  $suggestions[] = 'field__' .
    $variables['element']['#field_name'] . '__' .
    $variables['element']['#view_mode'];
}

Put this into MYTHEME.theme in the theme directory.


Defining hook_menu() paths for specific base URLs

If you want to use base url, you should first declare it as a global variable and then use it as $base_url. You should also note that $base_url will include the url scheme (i.e) http or https.

If you have a development or staging environment setup, your base url will probably differ between dev, stg and prod environments. In most of the cases, the production environment will be SSL enabled. So you may have to consider this as well while writing code.

In my opinion, as you have mentioned, you may use a different module and enable it only for the specific site. Or if you deliberately want it to be in a common module, consider using access arguments and define hook_permissions.


Getting the original form with error message in drupal ajax call back

For Drupal 7 you can use the below code

    /**
     * Implements hook_menu().
     */
    function hook_menu() {
        $items['test_ajax'] = array(
            'title' => 'test ajax',
            'page callback' => 'drupal_get_form',
            'page arguments' => array('demo_form'),
            'access callback' => TRUE,
            'type' => MENU_CALLBACK,
        );
            ....
    }

    /**
     * Implements hook_form().
     */
    function demo_form($form, &$form_state) {
        return array(
            'email' => array(
                '#type' => 'textfield',
                '#title' => t("Join our Newsletter"),
                '#required' => TRUE,
                '#attributes' => array(
                    'placeholder' => t("mail@example.com")
                ),
            ),
            'submit' => array(
                '#type' => 'submit',
                '#value' => t('Subscribe'),
                '#ajax' => array(
                    'callback' => 'demo_form_ajax_submit',
                    'wrapper' => 'demo-form',
                    'method' => 'replace',
                    'effect' => 'fade',
                ),
            ),
        );
    }

    /**
     * Ajax callback function.
     */
    function demo_form_ajax_submit($form, $form_state) {
        drupal_set_message();
        $message = '';
        if (!empty($form_state['input']['email'])) {
            if (valid_email_address($form_state['input']['email'])) {
                $message = "subscription successful!!!";
                $status = 'status';
            }
            else {
                $message = 'Please enter valid email ID!!';
                $status = 'error';
            }
            drupal_set_message($message, $status);
        }
        $form_state['rebuild'] = TRUE;
        return $form;
    }


How can I access profile fields with a % variable in Drupal Actions?

You could try using the Realname module together with Token and Token Actions.


I tried on my local with

drupal 7.30-dev
views 7.x-3.7
better exposed filter 7.x-3.0-beta4

Added term reference field in article content type. Created a view, added this term reference field as exposed filter i was able to get the checkboxes for tid.

Make sure the term reference field setting is set to "Dropdown" and Use Ajax options is set to "yes".

After setting term reference field setting to "Dropdown" i was able to see the "Checkbox/radio buttons" options in better exposed filter setting.


Unwanted  tags inserted before and after a rendered $item

There can be some better solution of this question but as you are facing of this extra html tag issue inside href, here is solution for this.

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item):
    $phone_link_data = render($item);
    $phone_link = strip_tags(html_entity_decode($phone_link_data));
    ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><a href="tel:<?php print $phone_link; ?>"><?php print render($item); ?>

    <?php endforeach; ?>


The Taxonomy Term Permissions module is what you are looking for.

From the project page description:

  This module allows taxonomy administrators the ability to restrict
  setting individual terms on nodes by user or role.


Automatically turning a profile to unpublished if membership is unpaid and v.v

How do I automatically render the member profile invisible to other members once the payment due date has passed?

By blocking the user you can stop access on expired user.

  Is it possible to automatically render the same invisible profile visible should they renew their membership by paying and if so, how?

For making it automatic so that a user can activate its account himself, you have to write a custom interface for that. (e.g. A block user tries to login, redirect to a page for user to enter his email address, then process his/her payment against his identity and unblock user)

$user = user_load('mail'=>$email);
user_save($user, array('status' => 1));


Are there any hooks for the event when an user navigates the verification URL?

Finally figured it out.

function my_module_lists_form_alter(&$form, &$form_state, $form_id)
{
    // Trigger when at password reset form
    if ($form_id == 'user_pass_reset')
    {
        // If $account has not been defined, define it from $user
        if (empty($account))
        {
            // Loads the user using the user id argument
            $account = user_load($form_state['build_info']['args'][0]);
        }

        // Log something
        watchdog('DEBUG MESSAGE:', 'We are there, user : ('.$account->mail.')!');
    }
}

If anybody has a better method, please do share.


Try the Views Calc module

This module adds simple calculations to a views table. Requires the Views module.
You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).

Image from module page


Programmatically show field in different regions depending on content

"I have some pages with three regions in the content zone, I want to
  output a field in all three regions so they can be shown & hidden at
  different screen sizes with CSS..."

If this is the case, you could solve this entirely in CSS, by using media queries to show / hide areas -or your field -depending on the browser size. And you don't even need to have the same field in all the three regions.

However, if what you want is to show / hide columns inside your content depending on a field value, you might be looking for the Display Suite module, which allows you to easily create different layouts and view modes. For example, you could:

Create one view mode with 2 columns and another one with 3 columns.
Add the fields you want to display in each one of those view modes.
If you want to switch the view mode, depending on whether a field has a value or not, you could use hook_entity_view_mode_alter() like this:

function YOUR_MODULE_entity_view_mode_alter(&$view_mode, $context) {
  // If viewing a node in the two_columns view mode...
  if ($context['entity_type'] == 'node' && $view_mode == 'two_columns') {

    // If your field 'something' has a value, change the view mode to 'three_columns'.
    if (!empty($context['entity']->field_something)) {
      $view_mode = 'three_columns';
    }
  }
}

Or you could also use the Contextal View Mode module to change the view mode for a node based off of a context.


How to remove overlay hashtag and trailing menu from the parent overlay

If you remove the "#overlay=node/25/edit%3Fdestination%3Dnode" part from the module, you disable the overlay for that page.

if that is what you want to do, then you need to implement hook_admin_paths_alter() in a module, using code similar to the following one (change "mymodule" with the effective short name of the module):

function mymodule_admin_paths_alter(&$paths) {
  $paths['node/*/edit'] = FALSE;
}

The result returned from hook_admin_paths() is used from the Overlay module to decide when a page is rendered in an overlay. The implementation of that hook done by the Node module is the following one:

function node_admin_paths() {
  if (variable_get('node_admin_theme')) {
    $paths = array(
      'node/*/edit' => TRUE,
      'node/*/delete' => TRUE,
      'node/*/revisions' => TRUE,
      'node/*/revisions/*/revert' => TRUE,
      'node/*/revisions/*/delete' => TRUE,
      'node/add' => TRUE,
      'node/add/*' => TRUE,
    );
    return $paths;
  }
}

The module that implements the hook I reported in the first code snippet should be enabled when the  Overlay module is enabled; alternatively, that hook implementation should check if the Overlay module is enabled.

function mymodule_admin_paths_alter(&$paths) {
  if (module_exists("overlay")) {
    $paths['node/*/edit'] = FALSE;
  }
}

The information returned from hook_admin_paths() could be used from another module to render those pages in a different way, such as using an administrative theme; if the purpose is just to avoid the overlay is used to render that page, then the module should change the information returned by hook_admin_paths() only when the Overlay module is enabled.


Disable pathauto for nodes created with migrate module

You basically need to make sure the $node object is passed in with pathauto set to false when it is saved.

In your migration class:

function prepare(&$row) {
  $row->path['pathauto'] = 0;
}


Disable vertical tabs by content type or user role

There are few ways to do this:

You can use the Renderable Elements module (as you mentioned above). It enables you to register any piece of build on your installation and manage the display through Field UI. It will make (additional) elements available of existing entities on the manage forms/display screens or you can for example register the contact form and rearrange the fields through Field UI. Works currently fine on forms, support for other is coming in a second iteration.
Or add the following to your custom module:

$config['yourcontenttype_node_form'] = FALSE;
variable_set('vertical_tabs_forms', $config);

A sandbox module that disables vertical tabs

Here is this core issue that refers to this.


Ubercart doesn't store that information by default, and there's no way to do it without patching the uc_stock.module file.

The reason is that the uc_stock_set() function updates the uc_product_stock database table, but doesn't invoke any hooks to allow other modules to act on that information.

If you create a patch that changes the uc_stock_set() function to this:

function uc_stock_set($sku, $qty) {
  db_query("UPDATE {uc_product_stock} SET stock = %d WHERE sku = '%s'", $qty, $sku);
  $stock = db_fetch_object(db_query("SELECT * FROM {uc_product_stock} WHERE sku = '%s'", $sku));
  module_invoke_all('uc_stock_set', $stock);
}

then you'll be able to write a custom module that implements the new hook_uc_stock_set() hook to save timestamp data to a custom table. That would look something like this:

function MYMODULE_uc_stock_set($stock) {
  db_query("INSERT INTO {MYMODULE_table} (sku, stock_level, datestamp) VALUES ('%s', %d, UNIX_TIMESTAMP())", $stock->sku, $stock->qty);
}

The uc_stock module works with the sku rather than the node id so it would be best to store that in your custom table.

The other hook you'll need to implement is one already provided by the uc_stock module, hook_uc_stock_adjusted(). Your module's implementation would look like this:

function MYMODULE_uc_stock_adjusted($sku, $prior_stock_level, $qty) {
  $stock_level = $prior_stock_level + $qty;
  db_query("INSERT INTO {MYMODULE_table} (sku, stock_level, datestamp) VALUES ('%s', %d, UNIX_TIMESTAMP())", $sku, $stock_level);
}


Create first rule "After saving a new user account" action "Add user role" to user and set its priority first(by set its weight 0 in SETTINGS of rule) and create one another rule for the same and set condition for role is(Reffereal source) and action send a HTML mail, set its priority down (by set its weight 1 in SETTINGS of rule) will work for you.


How to theme the PAGE template for user account?

it can be override with user-profile.tpl.php file.

  Default theme implementation to present all user profile data.

  This template is used when viewing a registered member's profile page,
  e.g., example.com/user/123. 123 being the users ID.

REF here


How to add a tooltip to a Form API field?

Solution is to use #attributes attribute to provide form element with HTML title attribute, like that:

'name' => array(
  '#title' => t('Name'),
  '#type' => 'textfield',
  '#size' => 30,
  '#maxlength' => 45,
  '#default_value' => $item->Name,
  // '#description' => t("Item's name, no longer than 45 characters."),
  '#attributes' => array(
    'title' => t("Item's name, no longer than 45 characters."),
  )
),


You cannot since colorbox calls the image directly and not through a node page to register the hit. Your going to have to custom code in a js script. when an image is clicked it would report back to the server via ajax to record that hit per image.


Export node display with Features not taking in account format of fields

The format and other settings of the field in a DS display are exported as part of the field instance element containing an array of settings per DS display.
So, except from the DS display you have to track all the Field instances (from the related Feature section) in your feature.

An example of an exported field instance of a text field field_location with format Plain text in the Full DS view mode in feature file my_module.field_instance.inc is:

// Exported field_instance: 'node-image-field_location'.
  $field_instances['node-image-field_location'] = array(
    'bundle' => 'image',
    'default_value' => NULL,
    'deleted' => 0,
    'description' => '',
    'display' => array(
      'default' => array(
        'label' => 'inline',
        'module' => 'text',
        'settings' => array(),
        'type' => 'text_plain',
        'weight' => 42,
      ),
      'full' => array(
        'label' => 'above',
        'module' => 'text',
        'settings' => array(),
        'type' => 'text_plain', // This is the exported format
        'weight' => 0,
      ),
      'teaser' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => 0,
      ),
      'token' => array(
        'label' => 'above',
        'settings' => array(),
        'type' => 'hidden',
        'weight' => 0,
      ),
    ),
    'entity_type' => 'node',
    'field_name' => 'field_location',
    'label' => 'Location',
    'required' => 0,
    'settings' => array(
      'entity_translation_sync' => FALSE,
      'text_processing' => 0,
      'user_register_form' => FALSE,
    ),
    'widget' => array(
      'active' => 1,
      'module' => 'text',
      'settings' => array(
        'size' => 60,
      ),
      'type' => 'text_textfield',
      'weight' => 21,
    ),
  );


How to add block to a single page that is not included in the allowed content type list?

With Drupal 8 you can have multiple instances of a block.  So, the easiest way to have this block show on the article page would be to do the following:

In the structure->block layout page, go to the region you already have the block created.

Place a new block and select your description block again.

In the configuration settings, set the page restrictions to use:  /node/<nid> where  is the article you want the block to be displayed.  You can use aliases here but the nid is best because this supports alternate languages if you need them.

Note: I assume you already have a block instance set up limited to the other content types.  If not, repeat and use the content types restriction to limit it.


#validate not overriding the submit function

Like Clive said resetting $form_state['input'] is the solution, however I'd rather handle both actions in the submit function:

function mymodule_myform_submit($form, &$form_state) {

  if($form_state['clicked_button']['#value'] == $form['clear']['#value']) {
    $form_state['input'] = array();
    $form_state['rebuild'] = TRUE;
  } else {
    $values = $form_state['values'];
    die('the value you submitted: '.$values['title']);
  }

}


Render user login form with custom theme

You can use drupal_get_form() to get the rendered form:

$form = drupal_get_form('user_login');

To override the default theme for the form have a look at Theming the contact form in Drupal 6 which goes through all the necessary steps very thoroughly.


How do I repack an existing site into Open Source repo with bundled content and configuration?

You can anonymize some content using drush and the sql-sanitize command found in Drush by default:
https://drushcommands.com/drush-8x/sql/sql-sanitize/

If that doesn't clean up enough of your content to be suitable for Open Source release, you can use the underlying hook drush exposes for this task and implement it for your site as seen in this blog post, https://www.codeenigma.com/support/blog/doing-more-drush-sql-sanitize, found on google. An excerpt of the additional sanitation examples you could do from the blog post are:

/**
* Implements hook_drush_sql_sync_sanitize.
*/
function my_module_drush_sql_sync_sanitize($source) {
  // The query to sanitise field_data_field_profile_linkedin_page
  $linkedin_page_query = "UPDATE field_data_field_profile_linkedin_page SET field_profile_linkedin_page_value = CONCAT('http://uk.linkedin.com/user-name/', FLOOR(100000 + (RAND() * 900000)));";

  // The query to sanitise field_revision_field_profile_linkedin_page
  $linkedin_page_query .= "UPDATE field_revision_field_profile_linkedin_page SET field_profile_linkedin_page_value = CONCAT('http://uk.linkedin.com/user-name/', FLOOR(100000 + (RAND() * 900000)));";

  drush_sql_register_post_sync_op('sanitise_linkedin_page', dt('Sanitise field_profile_linkedin_page'), $linkedin_page_query);

  // The query to sanitise field_data_field_profile_telephone_number
  $telephone_number_query = "UPDATE field_data_field_profile_telephone_number SET field_profile_telephone_number_value = CONCAT('+44', FLOOR(1000000000 + (RAND() * 100000000)));";

  // The query to sanitise field_data_field_profile_telephone_number
  $telephone_number_query .= "UPDATE field_revision_field_profile_telephone_number SET field_profile_telephone_number_value = CONCAT('+44', FLOOR(1000000000 + (RAND() * 100000000)));";

  drush_sql_register_post_sync_op('sanitise_telephone_number', dt('Sanitise field_profile_telephone_number'), $telephone_number_query);

  // The query to sanitise field_data_field_profile_twitter_handle
  $twitter_query = "UPDATE field_data_field_profile_twitter_handle SET field_profile_twitter_handle_value =  SUBSTRING(MD5(RAND()) FROM 1 FOR 8);";

  // The query to sanitise field_revision_field_profile_twitter_handle
  $twitter_query .= "UPDATE field_revision_field_profile_twitter_handle SET field_profile_twitter_handle_value =  SUBSTRING(MD5(RAND()) FROM 1 FOR 8);";

  drush_sql_register_post_sync_op('sanitise_twitter_handle', dt('Sanitise field_profile_twitter_handle'), $twitter_query);
}

If you dont want to attempt to delete revisions manually yourself, in packing the site for git (make a backup first), I would look at the following module: https://www.drupal.org/project/field_sql_norevisions

Once the above steps are done. I would simply provide a drush archive-dump (or the contents thereof) in a GIT repo and instruct users to use Drush and the provided zip (or place the contents of the git repo into a zip) to use drush archive-restore to install the site. The only gotcha with this approach is to assure they use the same database engine on their system as the live site expects (that I can think of).