Which files do I need to edit to alter webform #states with hook_form_alter?

Ok, if you need to rely on custom dev, you can indeed use hook_form_alter().

It would work if you set it in your mytheme.theme file but for unrelated theme issues I prefer to rely on custom modules.
To create your module:

Create a mymodule.info.yml file in the folder /modules/custom/mymodule of your Drupal website. See this page for providing your file with the minimal content to have your module detected by Drupal.
With only this file you should be able to enable your module
Create a mymodule.module file at the same level as your .info.yml file
In your .module file (or mytheme.theme if you chose not to create a module), add the following:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  // Target your form
  if($form_id == "your_form_id") {
    // Use Devel Kint module to display the architecture of your form and make it easier for you to find the elements you wish to alter
    kint($form);
    // Now you can access the elements of your form and edit the desired ones

    // Hide checkbox "my_checkbox_name" if checkbox "my_other_checkbox" is checked
    $form['my_checkbox_name']['#states'] = array(
      'invisible' => array(
        ':input[name="my_other_checkbox"]' => array('checked' => TRUE),
      )
    );
    // Make field "some_input_text" required if input field "some_other_input" is filled with value 'hello'
    $form['some_input_text']['#states'] = array(
      'required' => array(
        ':input[name="some_other_input"]' => array('value' => 'hello'),
      )
    );
  }
}

I recommend you to have a look at this page for the list of available #states and some examples as well.

Happy coding!


Is there a way this can be done without needing to use drush?

If you create a custom module with a migration group you don't need to run drush migrate-upgrade --config-only, but if you screw up, you'll have to uninstall and re-install, a bit annoying.

  I also need their order history from drupal commerce.

Custom migration is the way to go.


Printer, email and PDF - can I use this module to print Views?

It should be the same idea, but instead of using nid in the URL use Views page path.

Examples:

print view page: http://www.example.com/print/view-path
pdf view page: http://www.example.com/printpdf/view-path
email view page: http://www.example.com/printmail/view-path


How to list Taxonomy Terms with Pictures in View?

When you create the view, you need to create a view of taxonomy terms instead of of content/nodes like you have done in your SS above. Then you have all the fields etc available that you have on your terms.


Regarding Master/Master (High availability) is possible to do load-balancing when no master is down.

The following will make all writes go to master1 and all reads go to master2. If master1 fails, all queries will go to master2. If master2 fails, all queries will go to master1.

'master' => array('master1', 'master2')
'slave' => array('master2', 'master1')

The following will make all queries go to master1. If master1 fails all queries will go to master2:

'master' => array('master1', 'master2')
'slave' => array('master1', 'master2')


Drush: --yes-if-newer behavior with pm-download?

I'm afraid there is no easy way: as the command version isn't stored in any file, there is nothing to compare with. If you really want to do it, you can download the command and run a diff with the version you have, and install it if it differs, but I doubt the efficiency of such a check compared to install it in any case


Make sure the selected authentication methods are enabled for the server, e.g:

admin/structure/services/list/rest_api


White screen of Death after clearing cache, can't find a way to get the site back up

If you have Drush, I would try doing another cache-clear. If that doesn't work, I would also try a registry rebuild.

Other than that, just make sure that file exists and that function exists.


Create Related Terms Block Showing Terms on Taxonomy Term Page

First off, I wanted to let you know that this is not necessarily intuitive, and there's very hacked methods of doing this. Another thing that I want to mention is that I did this in Drupal 7 with Views 3. However, one of the things that I think is most different is the UI. So text descriptions should be able to guide you. :)

The way that I went about doing this is as follows:

In Views, I created a block which is to display the content type of the related items (mine was recipes). I added the fields which I wanted to appear, which were just pictures and titles. Then in Contextual Filters (I think D6/Views2 calls this arguments), I added two.

The first is "Content: Nid" and I configured it as follows:
When filter value is not available => Provide default value => Type: Content ID from URL. Under "more" (not sure what V2 calls it), there's an option called "exclude", which if selected, the numbers entered for the filter will be excluded rather than limiting the view. This is great because it essentially says, "Return me the list of everything of this content type EXCEPT this one that I'm on."

The second filter is "Content: Has taxonomy term ID". This one was a bit trivial because I want to provide relationships on multiple vocabularies of taxonomy terms. So it's configured as follows: When the filter value is NOT available => Provide Default Value => Taxonomy term ID from URL => Load default filter from node page => Limit terms by vocabulary => Selected my vocabularies => Multiple-value handling -> filter to items that share any term.

When the filter value IS available or a default is provided => Specify validation criteria => Validator = Taxonomy term, with my previous chosen vocabularies selected again => Filter value type => Term IDs separated by , o + . Under "more", I checked "allow multiple filter values to work together."

This was the way that I was able to get the related content. I specified the amount of results that I wanted in the pager.

Hope that this helps!


Solr ignoring NOT but works with "-" and "!"

Issue was with my implementation. Before the query was posted to Solr, I was doing following:

$query = strtolower($query);

This made the NOT to not hence it wasn't working as expected.


You can use this module http://drupal.org/project/om_maximenu then create parent menus and its child menus .Even you can create blocks inside with the sub menus.


Alternatives to Messaging and Notifications

A project that is similar in scope to Notifications and is actively supported for Drupal 7 is Subscriptions.

You may also want to look at some of the more lightweight notification modules. The project Notify is designed to send out notifications whenever new content of a certain content type appear (Disclosure: I am the maintainer of Notify).

There is a Notifications via e-mail comparison at Groups.Drupal.org. This gives you a good idea of what is available for Drupal 7.


Passing field value to #autocomplete_route_name in custom form

You need to define #autocomplete_route_parameters. I'm not sure if the form gets rebuilt during autocomplete queries (most likely not!) so you might need to define a #ajax on the vocabulary selector in order to rebuild the form and return the taxonomy_terms field with correct parameters set. This way you're defining a clear dependency, that field 2's available values depend on field 1's value. Below code is untested, but hopefully pushed you in the right direction:

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['taxonomy'] = [
    '#type' => 'select',
    '#title' => $this->t('Select Taxonomy'),
    '#options' => $taxonomies,
    '#ajax' => [
      'callback' => 'Namespace\To\Your\Entity::vocabulary_callback',
      'event' => 'change',
      'wrapper' => 'term-wrapper'
    ],
  ];

  // Initially return a disabled field.
  $form['taxonomy_terms'] = [
    '#type' => 'textfield',
    '#disabled' => TRUE,
    '#prefix' => '
',
    '#suffix' => '
',
  ];

  // If someone's chosen a vocabulary, rewrite the field.
  if ($vid = $form_state->getValue('taxonomy', false)) {
    $form['taxonomy_terms'] = [
      '#type' => 'textfield',
      '#prefix' => '
',
      '#suffix' => '
',
      '#autocomplete_route_name' => 'unido_drupal_admin.get_taxonomies',
      '#autocomplete_route_parameters' => ['vid' => $vid],
    ];
  }

  return $form;
}

public function vocabulary_callback(array &$form, FormStateInterface $form_state) {
  return $form['taxonomy_terms'];
}

You also need to define this as a route parameter in your route's path element:

unido_drupal_admin.get_taxonomies:
  path: '/path/to/your/autocomplete/{vid}'

And also accept the parameter in your autocomplete function:

public function get_taxonomies(Request $request, $vid) {

There might be better ways to do this though, but with my limited D8 knowledge, this is how I'd approach it.


The very same thing happened to me after transferring my website to another hosting company.

You must run update.php.

Since I was logged out, the way I resolved this is as follows: I typed in the url box www.example.com/update.php (www.example.com being your site's name. If it's on your local machine, I guess it is something like localhost/update.php.)

If your settings.php file is properly configured, you should get an access denied message.

In that case, go to the directory (sites/default) and open the settings.php file. Look for the line $update_free_access = FALSE; and change it to TRUE.

Run update.php again. You will find a link at the bottom of the result page sending you to the front page. Click on it and your site is back in business. :)

CAUTION. Very important: Go to your settings.php file again and change the TRUE back to FALSE.


Preprocess function for targeting the home page

To target the front page in a preprocess function you need a condition, because for preprocess you can't use name suggestions:

function mytheme_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    // your code
  }
}


Conceptual Question...Link to an exposed filter result created by a view in Drupal 7

You could disable ajax, and then set your exposed filter to the relevant values for each link, and then save the url of each page.

Then re-enable ajax however use the links you previously saved to create hard coded links to the view with specific filters.

This works because even if ajax is enabled you can still pass in arguments via the query string.


How do I create custom content types in drupal?

Yes this can be done.

For the processing you'll need a custom module. Here's a tutorial to get you started with modules.

As for the specific functions you'll need all revolve around hook_nodeapi (d6) or node api hooks (d7).


how to make cron run once at specific time per day?

I think you've covered the options well in your question.  However, your combinaton of requirements - i.e.:

no poking of cron.php from crontab;
settings kept in database to be migrated along with the site ("done from within a module");
the management module must not be Elysia.

is a problem. This combination excludes all the possible answers. There is no solution that will satisfy all three requirements.

If you want to use a module, that module is Elysia cron.

You seem to think Elysia cron is overkill for this.  I happen to agree.  Besides, Elysia does not work too well when triggered by the built-in default poorman's cron.  You really want to use an external crontab poke together with Elysia to get the type of fine-grained control you seem to be after, with Elysia.

So while your first requirement rules out poking of cron.php from crontab, that is my suggested solution.

Actually, since the crontab entries for all your sites can be kept in a single file on a single server, I do not see how this set-up should be considered too difficult to maintain.


Getting the entire index of nodes from REST API

The index actually sends 20 results per page. I highly recommend you check out the ServicesResourceNodeTests.test file in the services module for a better explaination but basically you can pass the page number you want to get each page of results.

The test file shows how it checks to see if the next page is empty:

// The n+1 page should be empty.
    $responseArray = $this->servicesGet($this->endpoint->path . '/node', array('page' => $page_count + 1));
    $this->assertEqual(count($responseArray['body']), 0, t('The n+1 page is empty'));

Another (my preferred) option would be to use the Services Views module instead and that way you can get all the nodes in whatever format you wish!


Duplicate home / front page - available on two urls

It's normal Drupal behavior to have front page accessible by it's original path.

What I would recommend in the case is installing the Global Redirect module and configuring it to 301 redirect from /front to /.


Drush makefile downloading 7.x Dev instead of stable

To always specify the latest major version of Drupal, just use

projects[drupal][version] = 7

For modules and themes, just omit the version. For example:

projects[views][type] = module


From where comes $scheme argument in image_style_deliver callback?

Drupal passes on extra portions of the URL as parameters by default. So for example, a URL might look like this:

http://example.com/sites/default/files/styles/style_name/public/foo/bar.jpg

Which resolves in image_style_deliver to

$style = 'style_name';
$schema = 'public';

The function then goes on to extract the rest of the unnamed arguments, and reconstitutes them to form the eventual path to the file.


Practical solution to get an overview of input formats in use

This is stored on a per-field basis.

Take a look at your database,  any field_data_*  table.  In those tables, the field_X_format column will contain the input format.


Configuration Management is broken between two site environments, I have no idea how to fix it

Aaaaaargh! After banging my head against the wall I found the issue. I checked the yml output (either single export tab; the /sync folder; or in the compressed export file) and found the 'broken' line:

dependencies:
  config:
    - core.entity_view_mode.node.teaser
    - node.type.leistungen
  module:
    - null
    - node
    - user

I removed the '- null' entry and retried the import - it worked fine.

MegaDoh!


Random::string isn't a static function, so you can't call it statically.

Well, you can (PHP is, erm, interesting like that), but it will throw a fatal error in future versions of the language, hence the warning now. To clarify, you're not being warned that Random::string itself is deprecated, just the method you're using to invoke it.

Get an instance instead and use that:

$random = new \Drupal\Component\Utility\Random();
$string = $random->string();


drupal_get_path('theme', 'mymodule') should be drupal_get_path('module', 'mymodule').


Adding conditional css to view or display type

You could try this but may depend on your 'favourite' field output

If you click on "Format > settings" when editing your view you'll see a "Row class" field. In there you can put the replacement pattern for your favourite field.

So if its populated it will add the field value as a class to the view-row div. And you can use this to know if the field has content

If that's not going to work because the field content isn't suitable as a class then you could preprocess the node view and add a class yourself in the attributes array


Is there a way to globally redirect taxonomy paths -- on a pattern?

As i understand - you want to show some view on taxonomy term page. This view will take term as argument (contextual  filter) and display list of nodes related to it.

For this purpose you can use module Taxonomy Views Integrator:

  The TVI (Taxonomy Views Integrator) module allows selective overriding of taxonomy terms and/or vocabulary with the view of your choice. Using TVI you can easily create custom views to output all terms in X vocabuarly.


Why does deleting a translation on my custom entity delete the entire record?

TL;DR: Extend ContentEntityDeleteForm instead of ContentEntityConfirmFormBase.

The solution was to pattern my approach after the way Node and Taxonomy Terms create their delete forms. I changed my delete form to extend ContentEntityDeleteForm instead of extending ContentEntityConfirmFormBase. Look at ContentEntityDeleteForm::submitForm

// Make sure that deleting a translation does not delete the whole entity.
if (!$entity->isDefaultTranslation()) {
  $untranslated_entity = $entity->getUntranslated();
  $untranslated_entity->removeTranslation($entity->language()->getId());
  $untranslated_entity->save();
  $form_state->setRedirectUrl($untranslated_entity->urlInfo('canonical'));
}
else {
  $entity->delete();
  $form_state->setRedirectUrl($this->getRedirectUrl());
}

It explicitly takes care not to delete the whole entity when you are deleting a translation.

ContentEntityConfirmFormBase inherits the ContentEntityForm::submitForm method, which in turn executes the EntityForm::submitForm method. The entity never gets deleted anywhere in that process. Thus, I needed to override the submitForm method in my class. I hadn't included the necessary logic to account for translations, though. Rather than reproducing the necessary logic in an overridden submitForm method, it made more sense to change the class that I was extending.


Add a condition, Entity has field: webform>field. I have to do that with entityforms.


Is it possible to declare option inside drupal_add_js?

You can try something like

$external_js = array(
  '#markup' => '<script type="text/javascript" src="//platform.example.com/api.js">
    api_key:   [key]
  </script>',
);

drupal_add_html_head($external_js, 'my_module');


Create relation N:N and specify properties for each relation

If there is an existing contrib module for that, that would be Relation. It works at the level of Entities. It should provide a generic API/framework that can be used for what you describe.

If Relation doesn't fit your needs or is not ready for you, then writing a custom module would be the only option. For a custom module, I would work at the Entities level (with the help of the Entity API module), not directly in SQL. While Drupal doesn't provides scaffolding for Entities, it provide helper functions such as field_attach_form() or field_attach_insert() to deal with fields on entities. Unfortunately, the documentation on how to properly use entities is still scarce. The Model module is an attempt to help there since it aims to provide a model entity and entity administration interface to kick-start your entity development.


How to select a particular user role which could be flagged

You can achieve your requirement by following below steps.

Create a view of type User.

Add a relationship to Flag.

Now add Flags: Flag link field + extra field you want to display
Finally add a FILTER CRITERIA i.e. User: Roles and select Artist user role.


Turned out that after a complete wipe and restore of my site the upgrade worked without that error.

Sorry, no idea what caused this in the first place!


how to name templates for same content types

By default page.html.twig won't work content type specific pages, you'll have to assign a template file name manually. Check the example below which create a new template name for content type:

function [THEME_NAME]_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  // Add content type suggestions.
  if ($node = \Drupal::request()->attributes->get('node')) {
    array_splice($suggestions, 1, 0, 'page__node__' . $node->getType());
  }
}

With help of above code, you can use page--node--aktionsblock_oben.html.twig template file as your content type template file.


Why arn't changes I am making in CSS appearing?

I'd turn off CSS aggregation temporarily to see if that makes any difference. The settings are in admin/config/development/performance

That way you can see which CSS files are being used directly. This sounds like it might be a configuration problem with the server itself and not something with Drupal.

Also, check the response headers for the CSS. That will give you more info about whether it's serving cached versions and if there's something like a reverse proxy serving old versions of the files.


I am facing a similar problem and am developing a custom module to act when the specific content type is generated (hook_node_presave).  My concern is that the more they are required to do to generate the format, the more things will go wrong. All the user has to do is enter the cell contents as delimited rows and the module determines the size of the table and generates all the HTML and class content to match up with the css I have developed for its display.


How to get user current location and display node attached with current location?

You might want to use SmartIP to get the ip/location of the visitor. Or enter a location in the user profile.

Then in the leaflet view, as filter use proximity. This way you can select the distance from the user to the node you want to filter on.


Organic groups automatic audience selection

You can use the prepopulate module to pass the group's gid to the node add form.
For example, the link will looks something like this:

node/add/discussion?edit[group_audience][und]=4

You could then hide the group selection box with css so the user cannot change it.
For a more robust solution you would code a form hook. Here is an example.


How to display specific blocks for specific roles alone w.r.t domains and subdomains

Hope this will help you,

In Drupal 7 you can use these modules

Domain Context - It allows administrators to set specific settings for each of their domains that are using the same code base.
Domain Blocks - Enables domain specific visibility settings for blocks.
And for specific roles for each block you can select the roles. Go to your specific BLOCK configuration and select the ROLE in BLOCK VISIBILITY SETTINGS


Where can I find the upcoming DrupalCamps and DrupalCon?

I have always enjoyed http://www.drupical.com/
It takes a direct feed from http://groups.drupal.org/events


Add additional fields in Drupal 8 node edit form

You can add fields to nodes both utilizing the UI and programatically.

To do it over the interface, go Structure > Content Types (in the admin menu) - you will see a list of all node types currently available to your site. Find the node type you want to add fields to and hit 'manage fields' (preselected in the dropdown button to the right).

Now you can use 'add field' to add fields of any type you have enabled/downloaded from drupal. (If you don't have a whole lot of field types to select from, check if their modules are enabled under 'Extend'.)


Best practice for caching CSS libraries?

At the same time if you have many different files to load for each page this will slow down the speed for each page load.

You don't need to worry about this in Drupal, as Drupal will aggregate the CSS files when you have CSS aggregation turned on, and you should always have this enabled on a production site.

As such, you should ensure that only the relevant CSS is attached to an element/page to which it belongs.

For example, I'm creating a site right now that has a booking page. This page has a chart-like schedule on it, showing what time slots are available. It's not unthinkable that this could be swapped out at some time in the future. So I have all the CSS for that chart in a single file, and the chart is attached to that element of the render array. Therefore if anyone ever removes that element, or sets the access on it to FALSE, the CSS will not load.

Drupal will handle the aggregation in the background and serve an aggregated file that contains my file when the user is served the schedule, and serve an aggregated file that does not contain my file, when the user is not served the schedule.

So to sum it up, don't worry about having too many CSS files in Drupal. On the contrary, it's better to have your CSS modular, so that each file contains CSS to a specific element/page, and attach that file to that element/page. Drupal will handle the rest.

  And how does the D8 caching system work; will each library be cached
  in a separate css file? If I have page X and Y where i only need some
  css library on page Y, will both of them share CSS file A and then the
  other also have CSS file B? Or will these pages have only 2 different
  CSS files?

Aggregates are created as needed. If a page needs file X, Y and Z, it will create an aggregate that contains those files. If another page only needs X and Y, it will create an aggregate with those files. If that same page is visited by a loggeed in user that needs file A, then an aggregate will be created with those files.


Twig template variable not displaying value

The issue was that Drupal didn't like that the variable names had hyphens in them.
When switching from header-text to header_text it worked fine.


How do I create an invoice without product?

I would take a look at the Commerce Billy module

Features

Thread safe invoice number generation
Three invoice number generation methods: monthly, yearly, infinite
Configurable pre- an suffix values for invoice numbers
Arbitrary start value for invoice number
"invoiced" status on order entity (thus avoiding separate invoice entity)
Automatic or manual invoicing:
    Automatic: order moved to status "invoiced" on order completion
    Manual: admin moves order to status "invoiced" (VBO possible, Rules components already included)
PDF Generation (commerce_billy_pdf module)
Customizable PDF template
Views integration for PDF download link
Handling of credit memos (canceled orders)


Would using hash_pbkdf2() be more secure than the actual code used from Drupal 7?

If you take a look at user_hash_password, you can see that the hashing algorithm being used is SHA512. This is something different than the encryption algorithm though, which in its own could use a hashing algorithm.

The way Drupal 7 encrypts passwords actually is PBKDF2, using SHA512.

From Wikipedia:

  PBKDF2 applies a pseudorandom function, such as a cryptographic hash,
  cipher, or HMAC to the input password or passphrase along with a salt
  value and repeats the process many times to produce a derived key,
  which can then be used as a cryptographic key in subsequent
  operations.

Since lots of passwords can be generated in the blink of an eye by modern hardware, it's all about making an algorithm slow. This means generating rainbow tables becomes more expensive.

The problem with SHA-algorithms is that they can still be generated quite fast on GPUs. Some algorithms, like bcrypt are slow by design, which, in my opinion, means it would be a better fit.

  When the standard was written in 2000, the recommended minimum number
  of iterations was 1000, but the parameter is intended to be increased
  over time as CPU speeds increase.

In Drupal 7: assuming DRUPAL_HASH_COUNT is being used in the default encryption algorithm, 32768 iterations (1 << 15) would be used to encrypt a password. This means encrypting a password is quite slow, hence more secure (compared to just 1 iteration). You can adjust the count with the password_count_log2 variable, with a maximum value of 30 (1073741824 iterations) and a minimum value of 7 (128 iterations).

It's not worth it to change encryption algorithm; just let Drupal do its job.

Update: how it's done in D8: https://drupal.org/node/1850524


Add language switcher in section where i need

Move the print render($content['links']); up, as this outputs the alternative language links (among others).


Taxonomy filters don't display results - Drupal 7

So far I've found the right solution to this issue. I will write down it as who will have the same problem can sort it out.

To solve this problem I was just needing to create again the panel-page that I've used to create the taxonomy pages.

Why I was needing to do it? - It's simple, because when there's a new update if you have any entity that is pointing to a module's variable or whatever about that module and something is obviously changed in its implementation after the update, then this entity is pointing to the old representation of that variable/whatever of that module, so obviously drupal will show you an empty set as a result of a normal query.

I hope that this can help someone on the way in the future.

Have a good day drupalers!!
See ya next time ;)


Waiting something similar, I wrote this small script I called "drall" you may adapt:

#!/usr/bin/php
<?php

// Path to sites.php file.
include('web/sites/sites.php');

$done = [];
$argv = $_SERVER['argv'];

array_shift($_SERVER['argv']);

$parameters     = implode(' ', $_SERVER['argv']);
$commandPattern = "drush --uri=:key $parameters";

foreach ($sites as $key => $site) {

  if (count($argv) > 1 && !in_array($site, $done)) {

    $command = str_replace(':key', $key, $commandPattern);
    echo "Executing command `$command` on $site\n";
    `$command`;
    $done[] = $site;
  }
}

Use example:

$ ./drall cc render
Executing command `drush --uri=xxxxxxx cc render` on default
 [success] 'render' cache was cleared.

Hope there will be some @sites behaviors later, that was helpfull.

Although from this issue it doesn't look like it:

  Drush 9 no longer supports executing a single command on multiple sites with alias lists (@A,@b,@c) or @sites. Neither of those syntaxes are available in any context. You may still use drush sa @group to see all aliases in a group; that is the only context in which Drush recognizes alias lists.


How to set alias pattern of node's source alias?

I think you can set the alias to not be translated in the the content language settings (Admin->Config->Regional->content language.

Under each content type there should be a url alias option. Unchecking this should make the alias the same for all languages.


Organic Groups - Group members list (with content profile) with views

In the view add a new relationship
1.) Select node and then content profile->corresponding content type, which creates a relationship.
2.)Now in the fields add your content profile fields u want to display. here select the relationship content profile.
Now you should have your profile fields coming from content profile.


Commerce Sale Price provides per-product sale prices. Someone offered to provide exactly what you want but they haven't actually done so yet. The only thorny thing about achieving this is being able to work with Commerce's precalculated price system (you'll find some links on the Commerce Sale Price project page). At first you'd think this could all be done using Rules, but as I understand it, the system requires that a discount rule either be related to some global condition such as the date (which can get checked when a View is executed) or related to the product itself (such as an on sale field). The problem with your requirements is that the price is related to something external (the date) and something attached to the product. The only way I can see around this is by having a cron run that switches on/off the normal sale price flag based on the schedule fields (and causes the precalculated prices associated with that product to be updated).

For any of the precalculated stuff to work you'll need to follow the instructions on Sale Price's project page (you need to patch Commerce and use a sandbox module).

Addendum: Having said all that, if you don't ever need to use the precalculated price as a field in a View then I think you can do things entirely with Rules.


How can I programmatically reindex Commerce products to AWS Elastic Search?

So I have some updates answer relies in search_api.module file
function search_api_entity_update.
So I am able to achieve for one product. Can loop & do for multiple.
use Drupal\commerce_product\Entity\Product;
use Drupal\search_api\Plugin\search_api\datasource\ContentEntity;

$entity = Product::load(1); // Replace 1 with your product id.

$indexes = ContentEntity::getIndexesForEntity($entity);

if (!$indexes) {
  return;
}

foreach ($indexes as $index) {
  $index->trackItemsUpdated('entity:commerce_product', ['1:en']);
}

It works like a charm :)


How to auto-submit a form using Drupal Form API?

This one is a pretty easy method by adding 'onChange' to the '#attributes' array:

/**
 * Custom form handler.
 */
function FORM_EXAMPLE($form, &$form_state) {

  $form['complete_projects_radios'] = [
    '#type'          => 'radios',
    '#title'         => t('Project status'),
    '#default_value' => 0,
    '#options'       => [
      0 => t('Current'),
      1 => t('Complete'),
    ],
    // Define the onChange like so:
    '#attributes'    => [
      'onChange' => 'this.form.submit();',
    ],
  ];

  $form['complete_projects_submit'] = [
    '#type'       => 'submit',
    '#value'      => t('Apply'),
    // The submit itself is necessary, but now it can be hidden:
    '#attributes' => [
      'style' => ['display: none;'],
    ],
  ];

  return $form;
}


SQL query to count comments for node type

You can use this helper function

function mymodule_get_comment_count_by_node_type($node_type) {
  $query = new EntityFieldQuery();
  $result = $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', $node_type, '=')
      ->execute();
  $nids = array_keys($result['node']);

  $comments = db_select('comment', 'c')
      ->fields('c', array('cid'))
      ->condition('nid', $nids, 'IN')
      ->execute();
  $comments_count = $comments->rowCount();
  return $comments_count;
}


file upload broken on node form on custom page

Yeah, apparently you should add these line to the menu item array:

'file path' => drupal_get_path('module', 'node'),
'file' => 'node.pages.inc',

it is not enough to just add module_load_include('inc', 'node', 'node.pages'); before printing the form.


Showing Warning for viewing adult classified content

Do you want to implement the age verification for Anonymous users or for logged in users? If you are doing it only for the logged in users maybe a better option would be to just add a birthday field to the user and just verify the age on that, so you won't have to request the age all the time, or only the first time, and then store it in the birthday field.

If not, for the actual confirmation page, you could just use *hook_node_view* and if the user has not confirmed his age for that node, replace the content with the verification form. For the way you can store whether someone has confirmed his age for a node depends, as I've said above, on how you want things to work, for authenticated users, for anonymous users.


Drupal: on node save, redirect user to homepage?

The Rules module will help you.

If you found a problem with using this module and you want to know how to do this technically, just tell me and I will explain in detail.


How to hide the comment form label (not title)?

You can easily do this with CSS. Looking at dev tools, I see that the label is called edit-comment-body-und-0-value (yours might be different). So what we need to do is, simply edit the CSS file and put in the line label[for*="edit-comment-body-und-"] { display:none; } and clear the cache at /admin/config/development/performance.

That's all there is to it.

K.


View AJAX Refresh causing multiple refreshes

This is not really an answer, but I put it here so I could format my code.

This seems to me like it may be a bug.

I have been playing around with this for about an hour and a half now and could not get it to work as expected when I had more than 1 view on a single page.

To test I made a view called 'testing' with 2 blocks with the names 'block_1' and 'block_2'. I placed both of these blocks on a single page and added the code below to refresh them via ajax when clicking the heading.

code:

(function ($) {
  Drupal.behaviors.myAjax = {
    attach: function (context, settings) {

      jQuery.each(Drupal.views.instances, function(domid, view){

        if(view.settings.view_name == 'testing' && view.settings.view_display_id == 'block_1' ||
           view.settings.view_name == 'testing' && view.settings.view_display_id == 'block_2') {

          jQuery('#block-views-'+view.settings.view_name+'-'+view.settings.view_display_id.replace('_', '-')+' h2', context).once().click(function(){
            jQuery(view.element_settings.selector).triggerHandler('RefreshView');
          });
        }
      });
    }
  };

})(jQuery);

This ended up with the same behavior as the OP.

I think you should file a issue report in the views module issue queue


How to create a "wall" with Drupal Commons?

Flag
To implement "a trusted contact"? you could use the Flag module, whereas a user can "flag" another user as "I trust that user".
Views
Create some view using the Views module, in the format of a block, whereas you use the userid as a filter for such view. The actual content of such view should match with the "activities" you have in mind.
Rules block visibility
Use the Rules block visibility module to control the visibility of such block. Here is a quote from its project page:

The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:

Need to show a block only for users registered more than a month ago?

Perhaps you have a block that must be shown only between 8am-5pm on weekdays?

What about displaying or hiding a block based on current weather conditions?

All of this can be done by using Rules block visibility.

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to creating a Rules Component to verify if the "current user" has flagged the user of the profile being viewed as a trusted contact. As per the great integration of the Flag module with Rules, that should really be like a "Getting started with Rules" exercise.


Create a custom module, implement hook_cron(), it is nothing but a function which will be called whenever cron runs.

Here is an article explaining what are hooks.

For code reference install examples module.

Implement hook_cron()
Load all the instance of the computed field, where you store the expiry date

Either you can directly query the database using db_select()
Or, use field_attach_load() to load only that field instances, instead of loading whole user object. Here is an example of how to use field_attach_load().

Check the expiry date.

Send a mail using drupal_mail() if the role is going to expire.

Note: You probably want this cron to run only once a day, for that install Elysia Cron and configure this hook to run once everyday by 12:00 am.


Checkout FileField Sources for this problem. It lets you use remote file transer.


To store/get the version information for a module use the global functions:

drupal_set_installed_schema_version()
drupal_get_installed_schema_version()

For example set a new version for mymodule with drush:

drush ev "drupal_set_installed_schema_version('mymodule', '8123')"

Print the version with drush, in this example for the module comment:

drush ev "var_dump(drupal_get_installed_schema_version('comment'))"

The functions are defined in schema.inc. Here you can see how to access the key_value table through the keyvalue api, if you want to use your own code:

/**
 * Updates the installed version information for a module.
 *
 * @param string $module
 *   A module name.
 * @param string $version
 *   The new schema version.
 */
function drupal_set_installed_schema_version($module, $version) {
  \Drupal::keyValue('system.schema')->set($module, $version);
  // Reset the static cache of module schema versions.
  drupal_get_installed_schema_version(NULL, TRUE);
}


How can I hide or show fields using states with hook form alter

It seems you re using the Drupal 7 syntax. For Drupal 8 this is slightly different.

You can implement hook_form_alter() as follows to change the visibility state of a form element as follows:

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'node_article_edit_form') {
    $form['field_other']['#states'] = [
      'visible' => [
          'select[name="field_reason"]' => ['value' => 'other']
      ]
    ];
   }
 }

This will make the field_other field visible if the other option is chosen in the reason select list.


This is really hard to answer with the information provided, but why not try adding a filter to your Filter Criteria in your View?  In that filter make sure that you set the Relationship Field to the correct Entity Reference Field, the set the Operator to "Is empty (null)".  That would filter Nodes which have no reference.


Yes, there is a theme hook that will let you alter every instance of a checkbox. The two theme hooks you'll want to look at are:

theme_checkbox() - https://api.drupal.org/api/drupal/includes!form.inc/function/theme_checkbox/7
theme_checkboxes() - https://api.drupal.org/api/drupal/includes!form.inc/function/theme_checkboxes/7

Sample Code

Here's some sample code, available in the API doc links I provided above.

function theme_checkbox($variables) {
  $element = $variables['element'];
  $element['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name','#return_value' => 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element['#checked'])) {
    $element['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-checkbox'));

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

You can override the markup returned by implementing this theme hook.


As I understood it, Drupal.behaviors attach would allow the .click to fire on an element created at anytime. But just in case, I would try using .delegate(), as in

$('body').delegate('div.user-alert-close a', 'click', function() {
  alert(1);
});


How to download webform data to an Excel file?

Above the Download button,you can select range option from here.


how to optimize inline images in ck-editor

As you can see in the image below, you only have these settings to optimize your image via upload in CKeditor. Using it you can for sure set the image dimensions, file size and path for images.

The below screenshot is from Drupal 8. You can get the same settings at www.example.com/admin/config/content/formats/manage/full_html


If you're having trouble with the Geshi Filter, you could try the alternative http://drupal.org/project/syntaxhighlighter module.


How does one theme a panel (or add a style)

When you add a CSS class using the "CSS Settings" for the pane, Panels will tag the panel html with the classes you have identified.  You can then specifically change the css styling attributes by defining your class style using the local.css file found in the active theme directory (set in admin/appearance) to modify your targeted content.

IF you are not familiar with working with css , I suggest you get an intro level book on Drupal and theming, a basic primer on css coding, and upload firebug for Firefox browser to help you see which css styles are currently rendering any content you display on the site.

I have not found a good out-of-the-box solution for what you want to do. I hope this helps get you started on the 'custom route'.


Rules: How to access field values by language

Use foreach loop for field_name['und']['value']


You need to create a custom module and also you need a .info file change 20 to the number you want

function custom_tweaks_menu_alter(&$menu) {
  if (isset($menu['nodereference/autocomplete'])) {
    $menu['nodereference/autocomplete']['page callback'] = 'custom_tweaks_nodereference_autocomplete';
  }
}

function custom_tweaks_nodereference_autocomplete($field_name, $string = '') {
  $fields = content_fields();
  $field = $fields[$field_name];
  $match = isset($field['widget']['autocomplete_match']) ? $field['widget']['autocomplete_match'] : 'contains';
  $matches = array();

  $references = _nodereference_potential_references($field, $string, $match, array(), 20);
  foreach ($references as $id => $row) {
    // Add a class wrapper for a few required CSS overrides.
    $matches[$row['title'] ." [nid:$id]"] = '
'. $row['rendered'] . '
';
  }
  drupal_json($matches);
}

Taken from this source


How can I bypass the Minimum cache lifetime when programmatically clearing the cache?

First, a couple contextual comments on all this:

You are probably getting a 403 (Access Denied) message instead of a 404 (Not Found) message when visiting a previously unpublished page that was cached.
The method call that you referenced (entity_get_controller('node')->resetCache(array($node->nid))) within node_save() does not have anything to do with the page cache, and is instead related to the static entity cache, which only has an impact on the current request. However, you are certainly correct that Drupal makes an effort to clear the page cache upon a node save, but that happens in node_form_sumbit() when it calls cache_clear_all() at the end.
The cache clearing methods in Drupal are very strange and non-intuitive. I've seen entire threads erupt in passionate arguments and misunderstandings over the workings of cache_clear_all() and DrupalDatabaseCache::clear().

If cache_clear_all() is called without any arguments, as is the case on a node update, only the page and block cache bins will be targeted for clearing. That's fine as it's presumably the page cache that matters in your case, but as you noted the "Minimal Cache Lifetime" will be respected. The exact logic used to respect this "Minimal Cache Lifetime" (in DrupalDatabaseCache::clear()) might make your mind melt... but that's an aside.

As indirectly noted in another answer, you can call cache_clear_all() with a specific node URL to force the needed page_cache entry to be cleared. This will do the job independent of the "Minimal Cache Lifetime" which, IMHO, is quite non-intuitive. Thankfully there are tools that account for all this non-intuitive logic for us, like the Expire module. Not only does it have the ability to target certain actions in Drupal (such as a node update), and clear the cache when they happen, but it will do it in such a way that the "Minimal Cache Lifetime" is factored-in and bypassed as needed. There is an old issue thread here that seems to talk about this a little more.

Also, if you have another page cache active (Varnish, Boost, etc.) they may be suspect too, and may be returning a previously cached version of the request independent of the local Drupal page cache. If you have an external cache like this in place you should check its own settings along with the the core "Expiration of cached pages" setting (just below the "Minimal Cache Lifetime" setting). Once again, the Expire module can help here as it also integrates with external caches to sync their expirations with Drupal updates.


How to migrate nodes from a dev site to a production site?

Sounds like Node Export to export your nodes from dev and then re-import them on your live site.

Node Export provides several ways to export nodes:

Through a tab that appears on the node page.
Using update options on the Content page.
In a command line using Drush.
Using the Features module.
Using the Views Bulk Operations module.

and the Node export package comes with the following formats:

JSON
Drupal var export
Node code
CSV
Serialize
XML


Trigger Crop API programatically after node is created

The solution is using Image Style Warmer


Reset Password Form does not let user enter their new password

Solved it by installed the Simple Password Reset module:

  Without this module enabled, core Drupal prompts the user to log in
  via a one-time login form. After clicking "Log in", the user is
  brought to their profile edit form where at long last they can change
  their password.

  With this module enabled, the user skips the one-time login form.
  Instead the password reset link brings them right to the profile edit
  form where they can immediately change their password and log in. So
  what core Drupal does in two steps, this module does in one.


Getting Drupal to work with Mercury Mail Server on Local Machine

When I used to test sending mail from a localhost (I don't remember the mail server program though), I used to use the SMTP Authentication Support module for its configuration.

  This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.


Can I conditionally call a library based on HTML element?

hook_element_info_alter won't suit in this situation because you are trying to do something based on the value of a body field, which is just 'text' as far as Drupal is concerned. Element in the Drupal world is different. But here is an approach to your problem.

You can implement hook_preprocess_node and check if the body field value contains <table - and if there is a hit, then attach the library:

use Drupal\Component\Utility\Unicode;

function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];
  $match = Unicode::strpos($node->field_body->value, '<table');

  if ($node->field_body->value && $match !== FALSE) {
    // next line is just an example
    $variables['#attached']['library'][] = 'mytheme/libraryname';
    $variables['#attached']['library'][] = 'mytheme/datatables';
  }
}

This will only attach the library to a node being rendered IF the node body field has a value, and within it, there is a match for an opening table tag.

The use statement should go at the top of your mytheme.theme file.

strpos has a caveat:

  Note that a return value of 0 is not the same as FALSE.

So if you plan on using this a little more elsewhere, take note.


Control access to node by entity reference on User record

The Node Access User Reference module is probably what you want. From the module page:

Gives content access permissions to users for content that references the users with User reference or Entity reference.
This is great if you want your content authors to be able to choose additional authors, or choose who can view their content, as well as being able to display the list of authors or viewers within your content, or in views displays.


How to wrap a fields or other elements in div block?

In case you want a simpler answer with no coding needed just use Views Fieldset.
So install the module, add your row class on the view (Format > Settings > Row Class).

Then add a fieldset (Fields > Add > Global: Fieldset), in the settings of the fieldset choose div and to the HTML classes add the column classes. Don't forget to to go to Fields > Rearrange and put your fields in the fieldset group.

That's it.


Hover over image and display above like EBAY and AMAZON

Hi You can use combination of Views Slideshow & Views Slideshow JCarousel to make such effect.

See this video also:

http://buildamodule.com/video/advanced-site-building-in-drupal-7-building-a-slideshow-using-views-slideshow-how-to-create-a-pager-of-thumbnail-images-in-views-slideshow


Performance and loading times of theme like Zen vs building a theme from scratch?

Although I have used Fusion, instead of Zen, my personal experience is probably applicable.  You can run some comparisons using Zen vs. Stark, which is very stripped down to get an idea how they compare.  There are, of course plenty of other factors that can contr5ibute to the equation.

Regardless of the performance issue, there is also the development question.  Styling one of these themes can be a challenge especially if you include panels, views, superfish menus, or any other module that may also affect appearance.  I had a full head of hair when I started.

I found it much easier to use Panels-Everywhere and Panels to bypass the them system and create my own display formats. This removes a lot of inherited CSS and made styling much easier.


How can I edit all nodes of thier dates at once?

In this case, you could update the field in the db, much faster than node_loading and saving all the nodes with batch update etc.. backup db first.

Fields are:

node.created
node.changed
node_revision.timestamp (same as node changed)

e.g

$created = strtotime('2013-01-01 00:00:00');
$changed = REQUEST_TIME; // now

$query = db_update('node');
$query->fields(array('created' => $created, 'changed' => $changed));
$updated = $query->execute();

$query = db_update('node_revision');
$query->fields(array('timestamp' => $changed));
$updated = $query->execute();

drupal_flush_all_caches(); // clear cache


Remove RSS feed icon and create custom RSS feed

For your first question, I found the RSS Permissions module, which allow you to disable the RSS feeds based on roles. I haven't tested this out, but it seems to be actively developed. (NOTE: This is for Drupal 7.)


Add a Drupal site wide contact form to the maintenance page

I would try to override the default template file through maintenance-page.tpl.php and then use template_preprocess_maintenance_page to alter the variables stack and basically add the rendered form as a variable. But I don't know what would happen if you submit the form while in maintenance.


Adding taxonomy term list to another taxonomy term's overview

In this case you need to a create view that displays block on top of the collection page.
The view should display taxonomy terms in the "collections" vocabulary filtered by a contextual filter (taxonomy term id) so that only the desired taxonomy term is display.
Next you should add a relationship using the field reference you're using on that term.
Finally you can use the relationship to display fields or taxonomy terms to the display.

I tried to explain it briefly, let me know if you need further explanation.


use drupal_add_js after external js scripts have already been loaded

I was able to resolve this issue by encapsulating the inline js in a jQuery(document).ready function. Like so

<?php
drupal_add_js("
    jQuery(document).ready(function(){
        jQuery('.row').equalize();
    });
", "inline");
?>


How to add a filepath to a file uploaded in form API

Whenever I use a file field in the submit handler I use:

$validators = array('file_validate_extensions' => array('csv'));
if ($file = file_save_upload('upload', $validators)) {

You can add an optional argument to file_save_upload after $validators which is $destination, take a look at https://api.drupal.org/api/drupal/includes!file.inc/function/file_save_upload/7 for more details


Where is saved the value of the 'help text' of field of content type?

It's in the field instance settings (stored in the field_config_instance table). The preferred API method to use is field_info_instance():

$info = field_info_instance('node', 'field_foo', 'article');
$help_text = $info['description'];


How to use AJAX for an exposed filter form of a Views block?

You must install the Better Exposed Filters module:

  What else can I do with BEF?

  Add help text for each exposed filter
  Tame long lists with scrollable checkbox/radio button lists or select all/none links
  Provide instant feedback by updating the View using AJAX whenever an exposed filter is changed
  Use the jQuery Slider widget for greater-than, less-than or in-between types of filters

You can read more about this in Views exposed filters without "Apply" button


How to use user profile fields location fields in a rules component?

Install Countries module add field in your registration page.
when user register you can value of its location by selecting user country use this value in rules


How to pull node reference into view on a search index?

A search API based view can just take fields and information which are put into the index. Go to the index settings page and add the reference field. Then you can add addtional fields and relations connected to the reference.


How to create a rule that loops the line items of a completed order and do a data comparison on a custom field that's on a product?

First things first ...:

Your "AND" (in your rule, and in your component) appear to be redundant. If you doubt/wonder about that, have a look at my answer to the question "Which is the difference of combining rules with AND or just leave them follow one each other?".
So I'll ignore those already.
The list_item in your Rule (within the loop) is a variable name you get out-of-the-Rules-box. But to improve readability of your Rule, I suggest to rename that to something like current_line_item (and description like "Current line item").
While building (developing) your Rule (and component), I find it a handy facility to start with a rules action like "Display a Message" (which you can find within the "System" group). And for the actual message to be shown, already include tokens that may be interesting to know more about. Typically some "id" and some "description".
With the above Rule refinements, do some first unit testing, so that at least you get 1 Drupal message for each line item (produced via that Rules Action in your loop).

Remaining refinement(s):

Do some research/experiments to see how, starting from your current_line_item (my suggested new name for list_item!!!) you can find your way to the product the line item is related to.
You should be especially interested in something that smells, sounds and looks like the "ID" of the product the line item is about. If you think you found it, add that token to your message being displayed (to be sure you have what we should be interested in).
Assuming you found the product ID somehow, ADD a subsequent Rules action to perform a "fetch entity by ID", to actually fetch the product, with ID ... you guessed it ... the token you found in the previous step.
From then on, you have everything you need (I think) to add an extra Rules Action to simply perform your Rules Component, passing it the corresponding parameters.
In the end, when everything works as you want, you may want to remove or refine that "Show a message" Rules Action from before.

PS 1: The above is based on the assumption that I don't know "Drupal Commerce" at all ... hm, hm.

PS 2: I'm assuming this is about D7, though it will probably also work in a similar way if some day the question is about D8.


Is there a way to programmatically add questions to a webform grid?

Sure enough there is a way, a very neat one, just found it out myself!

In the following example I use a View's result to get the list of nodes I will use as the questions in the webform grid. This allows even easier management of the questions you want to display in your grid, by setting for example specific filters on your view.

You need to implement the hook_webform_component_render_alter hook. Here is the code you need:

function yourmodule_webform_component_render_alter (&$element, &$component) {
  // Select the right webform component
  if( $element['#type'] == 'webform_grid' &&
      $element['#title'] == 'Title of Webform Component' ) {

    // Override the title of the grid component
    $element['#title'] = "Node Title";
    // and use it as the label of the questions' column
    $element['#title_display'] = "internal";
    $new_grid_questions = array();
    // This is a standard content view that contains at least a nid and a node title field
    foreach( views_get_view_result('my_view', 'my_display') as $res ) {
      $new_grid_questions[$res->nid] = $res->node_title;
    }
    $element['#grid_questions'] = $new_grid_questions;
  }
}

And here is a screenshot of the end result:

Hope this helps!


Thank you JimJamma, that worked!

Here's how my code looks now:

    $form['submit'] = array(
        '#type' => 'submit',
        '#access' => variable_get('node_preview_branschguiden', DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
        '#value' => t('Save'),
        '#weight' => 5,
        '#submit' => array('node_form_submit'),
    );


Rules - After updating / saving user not working

You can use hook_user_insert and hook_user_update to execute your script, which is called after the user has been saved to the database.

Hooks should be implemented in a module. If you are new to module development, the Drupal documentation describes this very well: http://drupal.org/documentation


How to load a internal page content within div?

You can use jQuery $.load() to load a section of a page:

(function($, Drupal) {
  function loadContent(context) {
    $(context).find("#the_container_div").once("arbitrary-key", function () {
      // $(this) refers to #the_container_div
      $(this).load("http://example.com #container");
    }
  }

  Drupal.behaviors.someArbitraryButUniqueKey = {
    attach: function (context) {
      loadContent(context);
    }
  };
}(jQuery, Drupal));

The function loadContent() loads the content of the #container div at the page example.com into your local container of #the_container_div.


You can using like jQuery ajax. Because Drupal.ajax({}).execute() is a function and return the jqXHR.
 /**
   * Execute the ajax request.
   *
   * Allows developers to execute an Ajax request manually without specifying
   * an event to respond to.
   *
   * @return {object}
   *   Returns the jQuery.Deferred object underlying the Ajax request. If
   *   pre-serialization fails, the Deferred will be returned in the rejected
   *   state.
   */
  Drupal.Ajax.prototype.execute = function() {
    // Do not perform another ajax command if one is already in progress.
    if (this.ajaxing) {
      return;
    }

    try {
      this.beforeSerialize(this.element, this.options);
      // Return the jqXHR so that external code can hook into the Deferred API.
      return $.ajax(this.options);
    } catch (e) {
      // Unset the ajax.ajaxing flag here because it won't be unset during
      // the complete response.
      this.ajaxing = false;
      window.alert(
        `An error occurred while attempting to process ${this.options.url}: ${e.message}`,
      );
      // For consistency, return a rejected Deferred (i.e., jqXHR's superclass)
      // so that calling code can take appropriate action.
      return $.Deferred().reject();
    }
  };

source
So in your case:
var ajaxExecute = Drupal.ajax({url: path}).execute();

ajaxExecute.done(function() {
    alert( "success" );
})
.fail(function() {
    alert( "error" );
})


Parameter replacement is done all in one go, and you just need to provide a single associative array of args to db_query() for those replacements:

$args = array(':name' => $existingproductIDfield, ':vid' => 6);

$result2 = db_query('SELECT * FROM taxonomy_term_data WHERE name = :name AND vid = :vid', $args);


Sync local dev site to live best practice

Here are some good ideas to use:

1.) Backup and Migrate module.  Before doing any local changes migrate the production database down to your local environment

2.) Features.  Make all your content type into specific features.  Include content types, views, context, and any other thing that can be put into features.  This will allow you to make content type changes and almost ANYTHING on the site and simply roll it as a feature.  When its uploaded to the production environment you simply revert the features, and bam they are there.

3.) Stongarm and Diff are additional modules to use with features.  They allow to see whats different from the site and the feature, and strongarm allows variable exports into features.

3.) GIT or SVN.  Use git or svn to roll to production and keep your code base on track.  With major features differences use a branch to complete work and merge it into the trunk.  This will allow you to development bigger features, but also give you the ability to make bug fixes that can be sent up in a roll.

4.) RSYNC.  Most of the time sites/default/files or CMS uploaded files are not in your repository.  Use rsync to sync the production files to your local.  Or simply use FTP

5.) Use drush up to update your modules it will keep your subversion or git in tact.  It will also attempt to update your database.


Drupal Leaflet View loading view block through Ajax

You must use the ViewExecutable::buildRenderable function.

Instead of:

$content = $this->renderer->render($view->render());

You must do like this:

$content = $view->buildRenderable('block', $args);


Apparently there is an issue with the CKEditor module.  Once I disabled it I am now able to post content as normal.  I will have to find another WYSIWYG to replace it.


How do I add a view between display fields of a node?

This can be done with Drupal 8's Layout Builder.
Layout Builder is a module in Drupal 8 core that does much of what Panels did in Drupal 7 and before-- it allows you to create arbitrary layouts consisting of fields and blocks for content types and even individual pieces of content.
Since its part of core, this should be a safe long-term solution to rely on.
In this case, the rough steps would be:

Enable Layout Builder.
Go to Structure -> Content types -> MY CONTENT TYPE -> Manage Display.
Under Layout options, check Use Layout Builder and save.
Click the new Manage layout button that appears.
Your fields will be arranged as before.  Now, though, you can click Add block to add any block you want, including Views blocks.  You can then put the Views block between your page body and your comments.

This is just scratching the surface of what you can do but it should get you started.


Checkout the piece of code here. Just copying it here for reference

Create a function as follows in template.php

function get_panel_view(&$node) {
    // Load my task plugin
    $task = page_manager_get_task('node_view');

    // Load the node into a context.
    ctools_include('context');
    ctools_include('context-task-handler');
    $contexts = ctools_context_handler_get_task_contexts($task, '', array($node));

    $output = ctools_context_handler_render($task, '', $contexts, array($node->nid));
    if ($output !== FALSE) {
        return drupal_render($output['content']);
    }
    // Otherwise, fall back.
    return drupal_render(node_view(node_load($node->nid)));
}

Template should be called print--node--.tpl.php and you can print it as

print get_panel_view($print['node']); in place of print $print['content'];

Rebuild theme cache


How to give users access to the header or footer text in a view?

One option is to create a new Views "attachment" display, and give it different permissions than the other view.


How do I programmatically add and fill a field to taxonomy terms of a specific vocabulary?

This is really two questions.

For the first, I would use hook_taxonomy_term_view to alter $build['description']['#markup'], like so:

function custom_taxonomy_term_view_alter(&$build) {
  $build['description']['#markup'] .= '<p> And this is more stuff.<p>';
}

For the second, taxonomy_term_save() can take a description field as described on the API docs page.


Define image cropping in new image style

There are many options to choose from in Drupal for image cropping. Here is a quick comparison.

EPSA Crop

Allows a user to choose coordinates for different presets on an image. If a user defines coordinates EPSACrop will override the Imagecache process and will set new coordinates.
Image Javascript Crop

With this one you define one or more presets in imagecache using the 'javascript crop" action, a new 'javascript crop' link appears underneath the image on the node edit screen, and the resulting popup window will display those presets. This screen shows the original image and initially applies the initial crop settings defined in the preset you select, e.g.: crop 50%-50%, center-center. However, you can then choose a different area of the original picture you want to crop, dragging an overlay box over the image, altering the size etc.
Imagefield Crop

When the user uploads an image, the image is presented inside a cropping area. A cropping box is shown inside, and the user can resize and move it. Upon clicking 'preview' or 'submit', the image is cropped and the result is saved instead of the original image.
Imagefield Focus

This module allows to scale and crop images focusing on their important portions.
Image Editor

Bring Photoshop-like functionality into your Drupal website! Create/edit any images online in the powerful and feature-rich image editors and save resulted images back to your site! This project integrates several popular online image editing services into Drupal:Pixlr editors: Pixlr Editor and Pixlr Express, Picnik, Simple HTML5 editor from Aviary: Aviary Feather, Advanced Aviary editors: Aviary Phoenix; Aviary Raven (vector editor - not working yet); Aviary Peacock; Aviary Falcon, Sumo Paint, FotoFlexer and Open-source HTML5 PaintWeb editor.

On a side note, (this is not what you were really asking, but) anyone coming to read this post looking for similar functionality directly in IMCE can use the IMCE Crop module which adds image cropping functionality to IMCE through its UI. And for kicks, if your looking for the ability for users to be able to do manual cropping on their avatars, use Avatar Crop. Or just to force Image presets on Avatars, use Image Cache Profiles.
Manual Crop


Page title tag translated based on view title

I Actually managed to do it. I'm still not really sure on what did the work, but I tried to handle the taxonomy translation too using entity translation. The view's name was based on a taxonomy name, so it's probable that translating the name of that taxonomy added the title tag translation some way (I hadn't done anything else, so...)


You are looking for Entity External Rating module. Check the site using this module.

  This module can be used to implement a rating system based on external
  sources. What that means is that the actual rating, voting or whatever
  action, happens on an external application (for example on Facebook),
  and the results are fetched into your system. By itself, this module
  is intended for developers to use it like an API.

One key question would be why to use this module and not the Voting API with the Fivestar module for example. Here are the most important reasons:

The main advantage of this module is that your system does not handle now the actual rating process. This now happens on external systems.
You can have many sources from which your rating is fetched. The results will be aggregated from all of them.
If you have a site with mostly anonymous traffic, it will be very easy for your users to rate content through Facebook or Twitter.


Using Drupal console, can I gitignore console folder?

Yes, you can add the console directory to your .gitignore like so:

/console

However, similar to drush, you may want to carry around project-specific configurations in your repository. This allows changing the behavior of Drupal Console on a per-repository basis.

If you do want to have per-repository Drupal Console configurations then do not gitignore the console directory and instead commit it to the project.

See https://hechoendrupal.gitbooks.io/drupal-console/en/commands/init.html for details on how to initialize configurations.


Change .gitignore file for sites/default/files/config

You can do that if you ignore the content in "sites//files/" directory and not the directory itself "sites/*/files/", I think this is not the best way to do it but that is what I have managed to find.

Ignore all the content in "sites//files/" except for the config directory

# Ignore paths that contain user-generated content.
sites/*/private
sites/*/files/*
!sites/*/files/config

or you can only ignore the config/*.inc

# Ignore paths that contain user-generated content.
sites/*/private
sites/*/files/*
!sites/*/files/config
sites/*/files/config/*
!sites/*/files/config/*.inc

remember to replace the default "sites//files" with "sites//files/*" in the .gitigonre file.

Another way is to forcefully add the files you want to commit, this will add the files in the directory and track there changes,  but will not detect new files added in the future.

git add -f default/files/config/


Override taxonomy term display page with panel page

Have you tried this tutorial? http://drupaleasy.com/blogs/ultimike/2010/10/taxonomy-term-pages-steroids-using-panels-views


Progress of a user on completion of a book

My approach here would be flagging all the pages of the book and show a overview of total pages / flagged pages.


select image from existing folder without programming

There is a community module for this purpose which can be paired with a WYSIWYG. It's called IMCE. Alternately, you can look at the Media module in Drupal 7 which can help accomplish a similar thing.

P.S. Have to agree with the commenter. I think you might have answered this searching for "File management Drupal". :) Hint: https://www.drupal.org/node/265416


I am not sure about your control here, whether to move from survey webform to task webform or the vice versa. But this is what I would do.,

On login query the "webform_submissions" table with the logged in user's id and see whether he/she has submitted the webform before.
If he/she has not submitted it before load the webform say task webform.
If he has submitted this before, load the survey webform page.

You can make use of "hook_user_login" to redirect on login, also this can be used to query the "webform_submissions" table.


Views conditional fileds: multiple values

I solved this with a simple solution:

Added custom text field in views and something like:
div class="[field_value]"

The result of the field (blue,green,empty) is the class of the div so I can manipulate the css.

Thank you


How can I check if the current user is accessing his/her own user page?

There are two paths a user could be visiting their own page: "user" and "user/UID" where their UID matches.

There is a global variable $user that stores the currently logged in user.

So in the variable preprocessor for the template you can determine whether or not a user is on their own user page and save it to a variable that you can reference in the template file, like below.
Note the use of $variables['logged_in'], which is an available variable as listed in the page.tpl.php documentation.

/**
 * Override or insert variables into the page templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 */
function THEME_NAME_preprocess_page(&$variables) {
  // If we are on the 'user' page or a sub-page of it.
  if (arg(0) == 'user') {
    $variables['own_account'] = FALSE;
    // If we are on 'user' and are logged in then we are on our own user page.
    if (!arg(1) && $variables['logged_in']) {
      $variables['own_account'] = TRUE;
    }
    // If we are on 'user/UID' then check against the current user.
    else if (is_numeric(arg(1)) && !arg(2)) {
      global $user;
      if ($user->uid == arg(1)) {
        $variables['own_account'] = TRUE;
      }
    }
  }
}

Then you can use the variable $own_profile in your page-user.tpl.php template, which in this case might look something like this:

<?php if ($own_account): ?>
  <div class="own-account-msg">
    Here is some markup for the message a user sees when they are on their own account page.
  </div>
<?php endif; ?>


How can I suppress "CSS file not found" errors on production?

I would first ask, are you logged in as super admin? I believe if you are logged in as super admin the message will display regardless of the setting in development/logging.

If you are not logged in as admin and are viewing the page anonymously did you clear your browser cache. If the messages are still being displayed, is your site being cached via varnish? You may need to clear the varnish cache or simply add an extra query parameter to the end of the url to make certain you are viewing an unvarnished page. Ex: www.example.com/homepage?extraquery

This is generally unadvisable but when push comes to shove and you need to hide something quickly on the production site, you can alway hide the error message box with css until you actually fix the error. AGAIN, i would only use this as a last resort and if deadlines are rapidly approaching and there just is no other option.

You could do something like .error {display:none;} in your global.css file or wherever seems more suitable.

Good luck


Problem rendering paragraphs field - advanced but still not working

I am sorry, there was just a dumb error in the paragraph template that I used in testing. So, never mind...


How do I place connect a template to a certain content type

I think you could use the "without" filter on the {{ page.content }} as below:

{{ page.content|without(field_textblock) }}

and then you should be able to output "field_textblock" as you were before.

There is a good page about twig filters here https://www.drupal.org/node/2357633


Do I use Content Type creator to create new modules?

edit

After a quick google search I found this. Might be useful
-http://drupal.org/project/merci- (couldn't add more links)

I'm sure there is already a module you can download that does something similar to what you'd like to do, but if not then you should probably start like this.

Install the ctools and views module

Things that can be done without code (Drupal creates the tables in the database for you)

Create content type
Add necessary fields to it (sku, description, amount remaining)
Create some nodes of your content type with sample data in order to build/test your module as you go
Create a view to display nodes of your new content type

Now for the code

Get the node id of the product you are trying to alter
Load the node - http://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_load/7
Your code that adds and subtracts inventory should updated the amount remaining field (you can use db_query or EntityFieldQuery for this) http://api.drupal.org/api/drupal/includes%21entity.inc/class/EntityFieldQuery/7 http://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db_query/7

You also mentioned übercart, are you currently using it? If so you can just add fields to that content type and track those with your module and not have to deal with creating content types and views, because ubercart does all of that for you.


Add this to your template.php

function MYTHEME_framework_page_build(&$vars) {
    // Add bootstrap cdn.
    drupal_add_css('http://netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css ', array('type' => 'external'));
}

where MYTHEME should be replaced with the name of your theme in your MYTHEME.info.

Save the file on your server

clear all chaes and reload the page.

now this should be fixred


As reported in the arg() is deprecated and will be removed change record, the Drupal 8 (procedural) equivalent of arg() is the following one.

$current_path = \Drupal::service('path.current')->getPath();
$path_args = explode('/', $current_path);

As the change record makes notice, not all the times that is the correct code to use. Depending from the context, you should use code similar to the following one.

Check if a path is for an administrative page

if (\Drupal::service('router.admin_context')->isAdminRoute()) {
  // Your code.
}

Add CSS or JavaScript conditionally, basing on the page being visited

function mymodule_page_attachments(array &$attachments) {
  if (\Drupal::routeMatch()->getRouteName() == 'my.route') {
    $attachments ['#attached']['library'][] = 'my_module/my_library'; // you'll need to define in mymodule.libraries.yml
  }
}

Load the currently viewed node

$node = \Drupal::routeMatch()->getParameter('node');

Notice that in the first and last case, in Drupal 7 you should not use arg(), but respectively path_is_admin() and menu_get_object(). The typical beginner-Drupal-developer error is using arg() also in those cases.


How to copy address on node translate action

Instead of copying the content of the field you can try the Entity Translation module  and only make some fields translatable. It will be much less messy than any kind of copying, where you'll end up with 2 or more copies of data that should actually just be one piece of data.
If you enable Entity Translation on your site you shouldn't enable Translation for this Address field, but you should enable it for other fields that you want to be translated.

Allows (fieldable) entities to be translated into different languages, by introducing entity/field translation for the new translatable fields capability in Drupal 7. Maintained by the Drupal core i18n team.
This project does not replace the Internationalization project, which focuses on enabling a full multilingual workflow for site admins/builders. Some features, e.g. content language negotiation or taxonomy translation, might overlap but most of them are unrelated.

I'm using this on a multilingual website. I don't want the product status field to be translatable:

But the body should be translatable:


How to find the number of clicks on a flash banner?

I would recommend using Google analytics and attach a click event to the banner. using a module would introduce unnecessary overheads


Rendering a 'google_map_field' when referenced via entity reference field

I would recommend using a view mode to render out the referenced entity.

For instance, A's display settings is set to display B using the 'teaser' view mode. Then, you can configure B's teaser display to show what you want.

I know this doesn't answer your direct referenced entity value question, but this is how I would tackle this problem.

I hope that helps!


Why does drush rsync require a local site?

Drush just performs the following in commands/core/rsync.core.inc:

$exec = "rsync -e 'ssh $ssh_options' $options $source $destination";

This isn't compatible with rsync daemons, as stated in the rsync manual:

  you must not specify the --rsh (-e) option.

Now, if you want to use drush to rsync between two remote environments, you'll need to install Drush on the source, then:

drush rsync @remote.source @remote.target


Generating a random number without duplicates on blog comment

Haven't tested this, but I think this should work. Remove your first two lines of code and place the following in your theme's template.php file (replace MYTHEME with the machine name of your theme):

function MYTHEME_preprocess_comment(&$vars){
    $max = 19;
    $numbers =  $_SESSION['MYTHEME_comment_numbers'] ?: range(0, $max);
    shuffle($numbers);
    $vars['number'] = array_pop($numbers);
    $_SESSION['MYTHEME_comment_numbers'] = count($numbers) ? $numbers : range(0, $max);
}

This makes available a $number variable inside your comment.tpl.php file.

Then, replace your last three lines inside comment.tpl.php with:

print "
";
print "";
print "
";

This will remove already used numbers from your $numbers array until there's none left, and then reset to use the full array again.


Views Rewrite Results Shows "Delete Comment" shows as text to anonymous users

set the permissions for anonymous users that they can't see or delete the comment.


osx 10.7.5 built-in apache 403 forbidden for sites/default/files/styles

This is more likely to be the issue with the update of Drupal core from 7.19 to 7.20.
As per the release notes, the update was only targeted to address the Denial-of-Service attack on the sites powered by Drupal.

You can add:

$conf['image_allow_insecure_derivatives'] = TRUE;

in the settings.php, to negate the effect of the update. As per the side effects, this will remove this security fix. I wouldn't recommend you do this on production.

existing patch:

--- a/modules/image/image.module
+++ b/modules/image/image.module
@@ -993,7 +993,7 @@ function image_style_url($style_name, $path) {
// The token query is added even if the 'image_allow_insecure_derivatives'
// variable is TRUE, so that the emitted links remain valid if it is changed
// back to the default FALSE.
-  $token_query = array(IMAGE_DERIVATIVE_TOKEN =>  image_style_path_token($style_name, $path));
+  $token_query = array(IMAGE_DERIVATIVE_TOKEN => image_style_path_token($style_name, file_stream_wrapper_uri_normalize($path)));

works, and $conf can be removed !

I've answered a similar question here.

Note: I'm making this as community wiki, so that someone working on Drupal security (hopefully from the security team) or anyone who is interested could add more to it.


Pros and Cons of Combining CSS/JS files or loading contextually?

As Drupal documentation says here: Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme,

Drupal uses a high-level principle: assets (CSS or JS) are still only loaded if you tell Drupal it should load them. Drupal does not load every assets on every page, because it slows down front-end performance.

You don't need to worry about loading libraries (CSS/JS) contextually. Drupal can load individual libraries for a certain block, or when a certain node type is being displayed. That's the purpose of the [theme-name].libraries.yml file, you can mention the specific blocks and page in there and tell it load the required library for that part.

You can attach the library to all pages, to specific Twig templates, or to a render element in a preprocess function.

For instance for a maintenance page:

maintenance-page:
 js:
  js/mobile.install.js: {}
 css:
  theme:
   css/maintenance-page.css: {}
 dependencies:
  - system/maintenance
  - thunder_admin/global-styling

Or for certain blocks or part of your page:

vertical-tabs:
 css:
  component:
   css/components/vertical-tabs.css: {}
dropzonejs.widget:
 css:
  component:
   css/components/dropzonejs.widget.css: {}

You can also use hooks like THEME_preprocess_HOOK() function in the .theme file. For instance, if you want to attach JavaScript to the maintenance page, the "HOOK" part is "maintenance_page", and your function would look like this:

function fluffiness_preprocess_maintenance_page(&$variables) {
    $variables['#attached']['library'][] = 'fluffiness/cuddly-slider';
}


How to make "Page specific visibility settings" for blocks more flexible?

If you need to control block visibility then the Context module is the way to it.

(edit) If you use the Context module you won't have to mess around with these types of things and more importantly neither does Drupal which in fact makes it faster. You can read more about Blocks, Context and Panels, another alternative to Blocks, here.


Every five seconds without refresh the new web page

Well it totally depends on what you want to refresh. I think what you are probably after though is Block Refresh which will allow you to refresh blocks every x seconds.


Reference Live Files with Built-In Server

If I understand this correctly, you can just use the Stage File Proxy module. Configure it to point at your production site. It has more configuration associated to it instead of just rewrite rules (which will be overwritten the next time you update core anyway).


Set up Node content 'localization' / site wide region filter - similar to languages idea

There are two 'out of the box' solutions.  The one is to use taxonomies to classify your content in different zones (one for the default zone), and views to decide when to display what.

All you then need to do is allow for your content to be self referencing - in other words add a entity relation field on each content type to itself.

So if you have a content type called basic_page, add an entity relation field in basic_page that can reference basic_page (cardinality of unlimited).   Your default zone node can now have relations to nodes of the other zones.

The other option - the one I would rather consider - is using the entity-translation module.  The module allows you to define 'custom languages'.  Now each zone can be a 'language'.  The fact that you are using languages to implement zones is the beauty abstraction - you are 'interpreting' language as a zone.

Using entity translation, all your node data is automatically 'grouped' as translations of the same entity.

I have done translations on Drupal sites a couple of times: IM me if you have questions.


Add a Computed Field to the content type to calculate the sum of the other fields–stored as an integer–and then you can use it as a Views filter. You will need to re-save your nodes to generate the computed field values.


Set value for new field automatically based on another field

It is possible and the best way to do it is in a custom module. Here's how:

Assume you have a module called mymodule.
Inside mymodule.install create a function called mymodule_update_N where N is a number starting at 7100. See the API documentation for hook_update_N for details but this is what runs when you run update.php
Inside your mymodule_update_7100, load the nodes you want to act on and then iterate over them, setting your newly created field to the value from Event Date.

If you have a lot of nodes, you'll want to look to the Batch API system to batch the nodes one by one so you don't run out of PHP memory or run up against the timeout. If it's not a ton of nodes, you don't need to worry about that usually.

And last, but not least, you should use an EntityFieldQuery to get the nodes you want to act on.

Hope that helps. Good luck!


how to add next and previous link on content full display page on tpl file in drupal 7?

You will have to write this logic yourself in a hook_preprocess_node(). This code should be added to the template.php file of your front end theme.

Here's an example:

function YOUR_THEME_preprocess_node(&$variables) {
  // Perform the logic for selecting prev/next terms here. Install and use
  // the Devel module to see what is available to you and to debug the code.

  // See what's available:
  dpm($variables);

  // Load a sample term. Note: this should be different if your website is
  // in multiple languages. Below is just an example.
  $term = taxonomy_term_load($variables['node']->field_term[LANGUAGE_NONE][0]['tid']);

  // Pass a variable to the node--flower.tpl.php file. Code below will make
  // the $previous_category and $next_category variables available in the
  // node--flower.tpl.php file.
  $variables['previous_category'] = 'Your link here';
  $variables['next_category'] = 'Your link here';
}


For Drupal 8, the code to create a user entity is the following one.

$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$user = \Drupal\user\Entity\User::create();

// Mandatory.
$user->setPassword('password');
$user->enforceIsNew();
$user->setEmail('email');
$user->setUsername('user_name');

// Optional.
$user->set('init', 'email');
$user->set('langcode', $language);
$user->set('preferred_langcode', $language);
$user->set('preferred_admin_langcode', $language);
$user->set('setting_name', 'setting_value');
$user->addRole('rid');
$user->activate();

// Save user account.
$result = $user->save();

The code can be found on Create a user account programmatically in Drupal 8.


Using drupal_http_post() to submit to external site: What am I doing wrong?

Thank you everyone for the pointers.

I realized that my custom module that uses the webform module to submit to an external url (via drupal_http_request) had to be written as two separate functions: one using hook_form_alter and one using a custom submit handler. The code is as follows.

<?php

function webform_to_data_repo_form_alter(&$form, &$form_state, $form_id) {

//I only want form 765 to submit externally //
if ($form_id == 'webform_client_form_765') {
$form['#submit'][] = 'my_additional_submit_handler';
 }
}

function my_additional_submit_handler(&$form, &$form_state) {

$url = 'your.external.url.here'
$headers = array('Content-Type' => 'application/x-www-form-urlencoded',);
$response = drupal_http_request($url, $headers, 'POST', http_build_query($form_state['values'], '', '&'));

}

?>

As a side note, I never got to test the result of using dpm($response) using the Devel module as beth suggested.

I'm using a webform (via the webform module) to test. What I wanted to happen are two things.

The webform validates the submission which in turn would keep a log of the submission through Drupal (webform module by default and by design).
Simultaneously submit inputs from #1 to external url.

For the longest time, only #1 is happening and I can't seem to make Devel look into $response because that variable only exists when there's an attempt on submission. How does one make Devel module load when a successful submission has been made through a Webform? I guess this is another question for another time.


From: https://drupal.org/drupal-7.20-release-notes

In addition, any code which programmatically generates a link to an
image derivative without using the standard image_style_url() API
function will no longer work correctly if the image does not already
exist in the file system, since the necessary token will not be
present in the URL.

Instead you can do something like this;
$image_uri      = $node->field_image[LANGUAGE_NONE][0]['uri']; // or any public://my_image
$style          = 'my_style';
$derivative_uri = image_style_url($style, $image_uri);
$success        = file_exists($derivative_uri) || image_style_create_derivative(image_style_load($style), $image_uri, $derivative_uri);

$new_image_url  = file_create_url($derivative_uri);


The best way to accomplish this is to use a term reference field rather than a list field, for a number of reasons:

The taxonomy module is made specifically for categorizing things, so it's a natural fit for  a "Category" field.
You don't have to edit your Category field every time you want to add options; you can simply add more taxonomy terms. This is better for Features-driven development (assuming you've exported your fields to code).
You can sort by the taxonomy terms' titles in Views by using a Views relationship between the node and the term via the term reference field.

AFAIK, there is no way to sort by value labels in a list field like you're trying to do. I'd definitely recommend going with a term reference field instead.


Select Images from a Multiple Images Field

Use field_collection module to build a field that has an image and a boolean.

Copy existing multi-image fields into the new field_collection like this:

/**
 * Copy a multi-image field into a multi-field_collection with an image field
 *
 * This function requires a patch for field_collection 7.x-1.0-beta7 like this:
 * wget https://drupal.org/files/1937866-field_collection-metadata-setter.patch
 * patch -p1 < 1937866-field_collection-metadata-setter.patch
 *
 * @param $nid  The node to update
 * @param $multi_image_source Name of the existing multiple-images field
 * @param $dest_field_collection Name of the new field_collection that will get the photos
 * @param $dest_field Name of the image field inside the field_collection
 */
function _copy_images_to_selectable_field($nid, $multi_image_source, $dest_field_collection, $dest_field) {

  $entity = entity_load_single('node', $nid);
  $wrapper = entity_metadata_wrapper('node', $entity);

  if ($wrapper->$dest_field_collection->value() != null) {
    drupal_set_message("skipping node with existing destination field ".$nid);
    return;
  }

  $photos = $wrapper->$multi_image_source->value();

  $collections = array();

  foreach ($photos as $photo) {

    $fc = entity_create('field_collection_item', array('field_name' => $dest_field_collection, 'revision_id' => 1));
    $fc->setHostEntity('node', $entity);

    $fc_wrapper = entity_metadata_wrapper('field_collection_item', $fc);

    $fc_wrapper->$dest_field->set($photo);

    $fc->save(TRUE);
    $collections[] = $fc;
  }

  $wrapper->$dest_field_collection->set($collections);

  $wrapper->save();
}

**NOTE: This function requires a patch for field_collection 7.x-1.0-beta7. Download and apply the patch from the field_collection module's folder like this:

wget https://drupal.org/files/1937866-field_collection-metadata-setter.patch
patch -p1 < 1937866-field_collection-metadata-setter.patch


How to implement moderation of data entered through user profile pages?

What I've done in a similar situation was this:

Turn on moderation of users /admin/config/people/accounts ie:

Who can register accounts?
--> Visitors, but administrator approval is required
Install Views Bulk Operations https://www.drupal.org/project/views_bulk_operations
Create a view that shows the moderated users by default (but you can use an exposed filter to change this). Include the fields that you want the administrator to be able to see (your text entry and taxonomy referred to above). Set your view to the VBO options and enable the operations for approving (or blocking) users.

Hope this helps!


Differences from dpm and dsm for devel module for debugging objects?

From the documentation:

Legacy function that was poorly named.
Use dpm() instead, since the 'p' maps to 'print_r'.
Code
function dsm($input, $name = NULL) {
  return dpm($input, $name);
}

So there is no real difference, except the function you are using is left there for developers that failed to switch when it was renamed.


How can I create a birthday calendar using the Date and Calendar modules?

You can try with Birthdays module. It allows users to add their birthday to their profile.

  The Birthdays module allows users to add their birthday to their profile. It also lists birthdays on a seperate page and in different blocks. Users can receive an e-mail on their birthday automatically, and the administrator can receive periodic reminders of who are having their birthday. Uses Profile module from core.


Override html.twig.php in your template, not page.twig.html. May I also suggest metatag for better control over page titles?


Location / distance based calculated field in views results?

I guess I should have looked through the module better. Here's the answer (tip: it's built right in!):

Go to your view (it needs to be a node based view I think)
In the "fields" section choose "add"
In the search box type "distance" and then choose the "Location: Distance / Proximity" field
Choose miles or kilometers to suite your needs
Then choose "Use Distance / Proximity Filter" from the drop down list (assuming, like me, you have an exposed filter in your view for users to enter a distance and a zipcode)
Adjust the label if you'd like, then click "apply"
In the "sort criteria" section, choose "add"
In the search box type "distance" and then choose the "Location: Distance / Proximity" field
Then choose "Use Distance / Proximity Filter" from the drop down list (assuming, like me, you have an exposed filter in your view for users to enter a distance and a zipcode)
Choose descending (most likely, anyway) and if you want to expose it, then you can click that check box also

And that does it!