Which of the two approaches to routing a module settings page is the best practice?

Without knowing what is in the controller this would be the second one. The extra custom controller class only makes sense if you do something in myMethod() the form controller invoked by _form is not able to do.

See https://www.drupal.org/node/2117411#fapi-in-route

This integrates the form in a request so that it can receive route parameters and the request itself as well as returning a response if necessary.


How to reset admin password with drush and Acquia Dev Desktop?

I'm not sure why it's failing for you.
Probably check the error logs to see if there are any warnings or notices being logged there.

The latest versions of drush have drush uli which just gives you a one-time login link for admin.

$ drush uli
http://default/user/reset/1/1311169130/gf-1uDYC51jONONNF-jq3_ciKfLqhE93SsS9YNAnaEY
Unfortunately it doesn't get the hostname right in most cases (probably there's no way to know it if base_url is not set) so you have to change "default" correct hostname.

So in the case above, I would paste the link into a browser and then change it to

http://example.com/user/reset/1/1311169130/gf-1uDYC51jONONNF-jq3_ciKfLqhE93SsS9YNAnaEY
There I have a one-time login link to user 1 on the site. Works flawlessly.

You can also run drush as admin by adding this:

drush -u 1 "command"

Eg:

drush -u 1 cc all


How to determine if Varnish/Pressflow is caching content in a useful way?

Below is the text that can been seen when using Google Chrome and under Network inspecting the response for you webpage. Observe the very last line. There you should get two numbers X-Varnish:1125490268 1125489929.

I've had problems before setting up Varnish and everything seemed to be going fine, then I noticed that only one number was present in X-Varnish. When fixed the two numbers appeared with a decrease in response time form 500ms to 45ms :)

Hope it can help you on the way.

Request URL:http://www.somepage.com/
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Host:www.somepage.com
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/28.0.1500.52 Chrome/28.0.1500.52 Safari/537.36
Response Headersview source
Accept-Ranges:bytes
Age:230
Cache-Control:public, max-age=900
Connection:keep-alive
Content-Encoding:gzip
Content-Language:en
Content-Length:6411
Content-Type:text/html; charset=utf-8
Date:Tue, 30 Jul 2013 08:03:13 GMT
Etag:"1375164849-1"
Expires:Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified:Tue, 30 Jul 2013 06:14:09 +0000
Server:Apache
Vary:Cookie,Accept-Encoding
Via:1.1 varnish
X-Drupal-Cache:HIT
X-Generator:Drupal 7 (http://drupal.org)
X-Powered-By:PHP/5.3.10-1ubuntu3.6
X-Varnish:1125490268 1125489929


Running tests is fairly straight forward:

Enable the Testing module at /admin/modules
Visit /admin/config/development/testing and choose tests to run (you'll find Path, Path API and Pathauto)
Run them and wait for the results

If you have stable versions of core and the contrib modules it's a pretty safe bet that they'll pass.


You could also try to alter the "user_register_form" and "user_profile_form" and add a custom validation.
So in that validation you'll be able to check the domain and set an error if it's wrong.


Error when trying to load taxonomy term name from tid

Because there is the case when no argument is passed and $tid is null. So better keep a check you have data in variable $tid and further perform the task. Even the view name condition is not mentioned so it may apply to all views.

  function hook_views_pre_render(ViewExecutable $view) {
      $tid = $view->args[0];
      // or alternatively $tid = intval($view->args[0]);
    if(isset($tid) && !empty($tid)){
      $term = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($tid);
      $name = $term->label();
      $view->setTitle($name);
    }
    }


A View listing Multiple Locations and each Location having it's Own Map

I was able to use the Address Field Static Map module to get this taken care of.

Since I was already capturing the address in the content type, after installing the Address Field Static Map Module, I could add another 'location' field to my View and select the 'Address Field Static Map' field formatter and customize as needed from there. The module even provided an option for linking out to the location in Google Maps.

To use this, the Address Field Module is a dependency.

This gave me the exact thing I needed.


I found another great example in the book "Drupal 7 Module Development", having worked through this example I am now able to alter it to my own purposes and the data is persistent.

Below is a working 3 field example.

function prodlist_field_info() {
  return array(
    'productorder' => array(
      'label' => t('Product Code'),
      'description' => t('Used to assign product codes'),
      'default_widget' => 'prodlist_text',
      'default_formatter' => 'field_example_simple_text',
    ),
  );
}

function prodlist_field_schema($field) {
  if ($field['type'] =='productorder') {
      $schema['columns']['code'] = array(
        'type' => 'varchar',
        'length' => 10,
        'not null' => FALSE,
      );
      $schema['columns']['description'] = array(
        'type' => 'varchar',
        'length' => 10,
        'not null' => FALSE,
      );
      $schema['columns']['amount'] = array(
        'type' => 'int',
        'not null' => FALSE,
      );

      $schema['indexes'] = array(
        'code' => array('code'),
        'description' => array('description'),
        'amount' => array('amount'),
      );

      return $schema;
  }

}

function prodlist_field_is_empty($item, $field) {
  if ($field['type'] == 'productorder') {
    if (empty($item['code']) && empty($item['description']) && empty($item['amount']) ) {
      return TRUE;
    }
  }
  return FALSE;

}

function prodlist_field_widget_info() {
  return array(
     'prodlist_text' => array(
      'label' => t('Prodcode entry fields'),
      'field types' => array('productorder'),

    ),

  );
}

function prodlist_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $base = $element;

  if ($instance['widget']['type'] == 'prodlist_text') {
    $element['code'] = array(
      '#type' => 'textfield',
      '#title' => t('Code'),
      '#default_value' => isset($items[$delta]['code']) ? $items[$delta]['code'] : NULL) + $base;
    $element['description'] = array(
      '#type' => 'textfield',
      '#title' => t('Description'),
      '#default_value' => isset($items[$delta]['description']) ? $items[$delta]['description'] : NULL) + $base;
    $element['amount'] = array(
      '#type' => 'textfield',
      '#title' => t('Amount'),
      '#default_value' => isset($items[$delta]['amount']) ? $items[$delta]['amount'] : NULL) + $base;

  }
  return $element;

}


How can I extend Commerce Discount to apply discount on custom price field?

All you need is Rules :)

You can start with next steps:

Visit Product pricing rules page: /admin/commerce/config/product-pricing
Click + Add a pricing rule
Enter Name. E.g. "Custom discount calculation"
Click "Save"

After that you can program logic of "some cases, depending on the node display term value of a taxonomy" via rules. If you provide more details I can explain steps more precise.

From this point you should only add conditions and actions. There is a good module rules_conditional which allows you to add conditions in any place of your rule.

Some hints on Rules:

When you want to do some actions and check with field values, you have to check if the field exists first (that's a tricky part of rules).

E.g. if you want to check the value of the field_price_with_flight, you have to add 2 conditions before:

Entity has field: Entity commerce-line-item, Field: commerce_product
Entity has field: Entity commerce-line-item:commerce-product, Field: field_price_with_flight.

After these 2 actions you can do things with the field.

P.S. An alternative way for checking fields is to check the bundle of the entity.

If you need to do some price calculations you can use actions:

Data > Add variavle
Data > Calculate a value

Once you have finished your calculations, you can apply your price. Check the `Commerce line item' actions for unit price. You can multiply, divide, set unit price.

That is basically it. In this case you do not need the discount module.

Advanced

If you need some very custom calculations you can code a custom action for price calculation. There is a lot of examples if you try to search it. E.g. How To Create A Custom Rules Action

Useful links, videos:

Product Pricing Rules (with screencasts) - a very detailed explanation of using pricing rules with steps, videos, examples.
Drupal Commerce Basic Discount on Vimeo
Drupal Commerce Complex Pricing Rules


How to make strings from templates translatable on all pages they appear?

Your requirement:
In order for my site to work in multiple languages
as a authenticated user
I need to be able to translate at once any and all translation calls found in my site's codebase that were done with the t() function.

Is that requirement description even close to what you're asking for?

Crawlers

Like someone said - a crawler could theoretically go through the entire site to force the registration of all t() calls. But 1) the crawler does not know which pages to crawl; 2) we are not looking to maintain a list of pages to crawl, therefore; 3) we don't want to use a crawler, period. Eww. Just, eww. Right?

The problem

We don't have a list of all translation strings.
Drupal/PHP is a dynamic language unlike C which is compiled. So we cannot go and say for example: compile this entire codebase, then find me all instances of this function t(), then register those instances in the database, then translate all those registered instances of t() in one go. I don't think is an option we have on our table.
A static code analysis tool would be helpless for the same reason a crawler would be helpless. I found this t() in this file. Great! What URL is it used in? What's the context?

Attacking the problem with the current tools (Drupal, and some contrib modules), and with the current constraints (relying on real-time theme calls -> template files -> t() calls), looks like a no-exit alleyway here. We might need to think a little bit out of the box.

What we need

We need a data source, a model, that tells me which current translation strings we have, and what is their context -
Proactive data model. The current data model is reactive (the model gets updated whenever a call to t() happens). We need a proactive data model - one in which the application takes care of looking for t() instances before they actually get executed by the customer.
We need context. t() alone does not cut it - because - we do not know we are translating 'foo', but the target language we are translating to depends on the URL of where the t() occurs on. Even if we could hardcode the target language into the t() call, say, using a wrapper call, it would not work for your purposes.

I have identified some of the tools that - if we had them - would help our problem. With these tools we could go into the data model and say: give me all the strings wrapped in t() that have not been populated yet. Now insert these translations. Thank you.

And the next time the customer comes, the translations are there in place.

How would we...build these tools?

Constraints

The target language cannot be on the template, that is decided by the URL. Assuming the string must support any language.
The translated string cannot be on the template. The translation will reside in a database.

Now that I've given the problem more thought, and identified some challenges and constraints, I can think about looking at any solutions available out there, or at making any custom solutions.

Solution brainstorm

I need something that ties "everything" together. What about...an entity?

An entity can hold the product that needs to be translated.
Entities can provide the relation - the glue - between the product that needs to be translated, and it's context.
The entity can specify say, in a field, the default URL location of the product.
Tokens can be used to specify alternative locations (languages?) that the product will appear on.
Entities provide us with the proactive data model that we need, and it's context. Which in turn allows us to do thing such as: go into the database, grab all the product entities, and if the do not have a translation string for fields X, Y, and Z, create those translation strings.

When the customer then grabs /pl/product/200, you take a trip to the db, look up product 200, and grab the already existing pl translation. You have a title and caption field for that product as well? The translations should be there also.

Note that I'm being very vague and generic here in terms of what translation module you're using. You could very well end up using your own translation module - most likely this is the case. All the translations models I've seen in Drupal so far (as of D7, haven't looked at D8 yet) are reactive, not proactive.

In a nutshell

In theory, the tools to build what you need are there, entities being the key component that would tie everything together:
 - data (translation string),
 - target languages. Don't have to be on the Entity itself, preferably a taxonomy vocabulary, say for product languages. or maybe a generic taxonomy for other entities as well.
 - Context. The URL that the entity appears on. The URL would contain a token, and the token in turn would reference the target language taxonomy.

With those three ingredients you can say: Grab all the product entities, go to the  URL alias field, get the taxonomy token, cycle through all possible term combinations, present all combinations to the current user using either a very large ugly form - or, AJAX - and multi-step forms (something like that), and as the currently logged in user translates the various languages for product 200, save those somewhere into the database

Somewhere in the database could be a Field API field in the entity, the settings field belonging to each entity (not exactly Field API, but it can still hold data), or a separate table that you use for this. I think saving the data into the Entity would keep both the code and data tidier and easier.

Building It: Possible solutions

D8MI (Drupal 8 Multilingual Initiative)
Custom code: "index" translations made available in templates by t() by programmatically querying and rendering available bundles and their related theme hook implementations.

Pseudocode

Foreach entity (of type x),
Find all languages (taxonomy or core language associated with product),
Render the entity,
     - in order to detect it’s t() translation strings
     - render calls theme(), which handles the multilingual presentation layer of the product, not the product data model itself.

Result:
     - First call to render entity template in each language returns the default language implementation for each call.
     - The t() parameters on the template are now cached in Drupal and ready for translation (for each language instance, not each product instance).
     - User with “translator” role can now go to translation interface and translate all available t() parameters, for each language.
     - Site owner does not need to wait for customers to visit each product page, or visit each product page manually, as this was done programmatically for him.

Open questions:
     - What is the context? If I do a programatic call to theme() for each “product” entity bundle, does it record the location from which the call was made? Does it record the URL of the node? Can the “context” be altered? Where is the context recorded? What happens when you have "dynamic" templates - i.e., when you have more than one template per product and how you go about detecting those variations?

As always, theorizing and pseudocode is only good for brainstorming. But in development we'll hardly know what we're really up against until we start prototyping. So having drawn up a couple of constraints, possible solutions, and possible problems or questions - I can now proceed to implement a proof of concept or working prototype. Some of the open questions above can only be answered this way, and the earliest we prototype (regardless of success or failure), we can start answering some of those questions - or change the approach altogether. Stay tuned ~


How to allow user registration and allow them to upload videos?

If you have to upload a Youtube video in your website, there is the Youtube field module which enables you to upload videos from Youtube by putting the link in the field.

If you want to upload a video from any site use the Media module for this.

  The YouTube field module provides a simple field that allows you to add a youtube video to a content type, user, or any entity.

  Display types include:

  YouTube videos of various sizes.
  YouTube thumbnails with image styles.

  This module is a lightweight alternative to Media or Embedded Media Field, if you're looking for a way to add video fields from more than one provider, you may want to consider looking into either of those two modules.

  The Media module provides an extensible framework for managing files and multimedia assets, regardless of whether they are hosted on your own site or a 3rd party site - it is commonly referred to as a 'file browser to the internet'.

  Media is a drop-in replacement for the Drupal core upload field with a unified User Interface where editors and administrators can upload, manage, and reuse files and multimedia assets. Any files uploaded before Media was enabled will automatically take advantage of the many of the features it comes with.


allow user to choose from his own referenced nodes

No need to write any code for this.
Use reference_option_limit module properly in your content types & when you create view and provide default value 'User ID from URL' - Please mark the checkbox 'Also look for a node and use the node author' to true.

Enjoy !!!


In which template file is the create new account/log in/request new password page rendered?

They are just menus. You can find those menus and their page callback in drupal core user module at hook_menu section.


stylesheets-remove in .info.yml file doesn't work

I was also having trouble with this and I found a change record which states:

  "In cases where a Drupal core asset is being removed (for example, a
  CSS file in jQuery UI) the full file path is needed. In cases where
  the file is part of a library that belongs to a module or theme, a
  token can be used. Note that when using the token it needs to be
  quoted because @ is a reserved indicator in YAML."

In my case I was trying to remove the eu_cookie_compliance.css file from the eu_cookie_compliance module. To do this I used the following in mytheme.info.yml:

stylesheets-remove:
  - '@eu_cookie_compliance/css/eu_cookie_compliance.css'

To remove module (even core ones) provided css you could try something like:

'@system/css/system.module.css'

To answer your second question about the aggregation of css files, you can switch off aggregation by visiting /admin/config/development/performance and unchecking "Aggregate and compress CSS files"


Programmatically load the contents of a Product in a particular product type

This can be done with an EntityFieldQuery:

<?php
  $query = new EntityFieldQuery();
  $result = $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'product')
    ->execute();
  $nodes = node_load_multiple(array_keys($result['node']));
?>


The node is cached and this function is only called for the first time the node is displayed for the given view mode.

If you really need to vary your output between ajax and non-ajax context, you need to add a cache context for that. See https://www.drupal.org/docs/8/api/cache-api/cache-contexts and the other related documentation pages. You could use the header:NAME-OF-THE-header cache context I guess.

As an alternative, do whatever needs to be done differently with ajax vs not  with Javascript/CSS


Error 500 when including controller file in Route

If that is the entirety of your controller, then you are missing use statement for ControllerBase.

namespace Drupal\mailing_list\Controller;

use Drupal\Core\Controller\ControllerBase;

class MailingListController extends ControllerBase {
  public function mailingListList() {
    $output = array('table', array('header' => '1'));
  }
}

You also need to return a Response or renderable array from the controller method the route calls.

Example:

namespace Drupal\mailing_list\Controller;

use Drupal\Core\Controller\ControllerBase;

class MailingListController extends ControllerBase {
  public function mailingListList() {
    $output = [];
    $output['#markup'] = $this->t('Hello!');
    return $output;
  }
}

See: https://www.drupal.org/docs/8/api/routing-system/introductory-drupal-8-routes-and-controllers-example

If that does not work you need to post the full error you are getting.


Serve a different admin theme for a user role

I think that this module does exactly what you need, I used it on a project and works very well

Role theme switcher module


I18N site: welcome page with links to translated pages, or translatable content type?

Not sure what you mean by "automate" the translation page but I think you're on the right track for what I think you're trying to accomplish.

First make sure you have at least the Multilingual content module enabled.
You likely want to also go to admin/config/regional/i18n/strings
        and make sure that Filtered HTML is translatable
Then go to admin/structure/types/manage/page and then Publishing options and choose Enabled, with translation under the Multilingual support option.

You should now have a basic page that is translatable. There will be a Translate option next to the Edit option on the node that should allow you to do the translation. Enabling the Language switcher as well as translating menus and paths is also recommended.


Render admin pages (forms) alongwith their admin theme from within a custom theme

Theme nesting is not implemented in Drupal. Too much risk of CSS conflicts, and HTML and CSS does not provide any way of isolation except for iframe. There is, quite literally, no way to write an universal solution. So you may:

Implement resets as you need. Probably hard, but still infinitely easier than any attempt to make solution universal and foolproof.
Trim the admin theme to remove footer, sidebars etc, and open admin pages in iframe
Prepare your own theme in a way that will render admin pages in a convenient way, "borrowing" code from admin theme you like (probably it's GPL, so you are allowed to do it).


Nobody can give you this answer, check your permissions against what is typical in the documentation page you listed. Have you checked this page selecting the given Role you want to examine:

  If non-administrative users encounter access denied (403) errors or
  fail to see notifications about moderation states, the "Check
  permissions" tab can help you determine what permissions are missing.
  Visit:

  Admin > Configuration > Workbench > Workbench Moderation > Check
  Permissions

The My Content page in Workbench Moderation is a View. You can customize its filters or conditions to meet your needs -- but be careful it's provided by the Workbench module so if you update the module you will likely loose your changes to the View unless you implement your changes using hook_views_default_alter.


How to override node content in Drupal 7

In Drupal 7 the content is in $content.

See node.tpl.php

<?php print render($content); ?>

The $content definition:

  An array of node items. Use render($content) to print them all, or
  print a subset such as render($content['field_example']). Use
  hide($content['field_example']) to temporarily suppress the printing
  of a given element.


You should always prevent special characters in filenames, this can lead to strange behavior. Specifically because certain characters can be part of a query string (example.com/index.php?var1=value1&var2=value2).

I recommend the Transliteration module (assuming Drupal 7) to remove these charaters form the filename. If that does not help (or if you are using Drupal 8), you might want to take another look at you upload configuration. There might be a token provided by File (Field) Paths that does provide you with a good encoded name.


Composer.json deletes dir even with preserve path

It looks like you haven't installed the plugin. Just run:

composer require drupal-composer/preserve-paths

And try again.

If it still doesn't work, you'll probably need to report it as a bug to the plugin's issue queue.


HTML5 Video showing both Source and Flash fallback

In these kinds of cases, the easy fix would be to add a second text field for "embed code" outside the main wysiwyg area. If you set it to use a new "HTML without linebreaks" text formatter, that'll help eliminate any wackiness on the "Full HTML" default setting.

Protip: use the Better Formats module to stop the user from having to choose a format for this field. That way, they can just paste and forget.


can i use entity id instead of node id to load node with node_load() function

The node ID is the entity ID for the node entity type.

As they're the same thing, the answer to your specific question can only be "yes".


How can I pass a variable to javascript from a preprocess function?

send it:

function mytheme_preprocess_page(&$variables) {
   $variables['#attached'] = [
        'drupalSettings' => [
          'myLibrary' => [
            'is_front' => $variables['is_front'],
          ],
        ],
    ];
}

access it in jquery:

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

      console.log(settings.myLibrary.is_front);

    }
  };


Deoes any email is send when i open drupal webpage first time?

You have the SMTP module set up for debug mode, so it prints the protocol exchange details for every email sent. In addition, poormanscron (which is default in Drupal 7) is being triggered by the page request.

If you turn off the debug option for SMTP those lines will no longer appear. Also you may want to set up an automated cron job so cron runs in the background rather than when users are making requests.


Modifying only one field with a twig template

Target the field template instead of node. Enable twig debugger and then inspect element with browser to see all the template files available to use/override.
You'll see you can use field--[field-name].html.twig or field--node--[field-name]--[content-type].html.twig if you want to be more specific.


Change taxonomy term field into text field in content-type

Eventually, I simply used a PHP script I execute in mysite/devel/php to copy my taxonomy term field value to my new text field:

$nodes = node_load_multiple(array(), array('type' => 'contact'));
foreach($nodes as $node) {
  if ($node != NULL) {
    $tid = $node->field_title['und'][0]['tid'];
    $term = taxonomy_term_load($tid);
    $name = $term->name;
    $node->field_function_title['und'][0]['value'] = $name;
    $node = node_submit($node);
    node_save($node);
  }
}


You have B that references A (single value entity reference field).

Construct your view as follows:

View of content (nodes) filtered by type A

Relationship: Entity Reference: Referencing entity (A bridge to the Content entity that is referencing Content via YOUR_ENTITY_REFERENCE_FIELD.). ISSUE - are you making this required? If you do then some A's that are not referenced will not show up. If you leave it as not required then unreferenced nodes will show up in the list either first or last, depending on whether sort is ASC or DESC.

Sort Criteria: Content: Post date, and set the relationship to the relationship added.

And that is it. To test your view you might want to add the field: Post Date, and set the relationship to the relationship added. This will show the post date of the referencing node so you can easily see if it works or not.

You might also want to add a second sort criteria.


Drupal Views Exposed filter ( Taxonomy )

If you have arranged your taxonomy in a hierarchical manner, then you can use the Hierarchical Select module:

https://www.drupal.org/project/hierarchical_select


Simply add a validation on the entity level, then you have easy access to the whole entity.

You can see an example in content_translation_entity_type_alter():

$entity_type->addConstraint('ContentTranslationSynchronizedFields');

You register a constraint like any plugin, the only special thing is that there are two classes, the plugin class itself doesn't really have anything except the messages usually while the validator has the logic, in the validate method::

ContentTranslationSynchronizedFieldsConstraint
ContentTranslationSynchronizedFieldsConstraintValidator::validate

Once you have that, writing the actual logic is often much easier, because you have a fully built entity object to work with and don't have to wory about getting the raw values from the form values. And as a bonus, it will also automatically work for REST/json_api and any other module that uses the validate() method to ensure that created entities are valid before saving them.

For example, verifying that an image field is not empty when the entity is published:

if ($entity->isPublished() && $entity->hasField('field_image') && $entity->get('field_image')->isEmpty()) {
  // add a violation...
}


DOMPDF not showing images and writing empty tmp files via print module

It's because your permission is -rw------- which only has read and write, there is no execute.

Use chmod -R 0775 sites/default/files


How to programmatically create a View on a node that displays SQL Query content?

You can create a View block to show on the nodes, and use a contextual filter (Content: Nid) in the View to figure out which node to reference.

Then you can display the related user (user reference field?) for that node in the block.

In case you are using pathauto to auto alias your node URL's, you can setup the Contextual Filter field (Content: Nid) to determine the Nid from the URL:


Programmatically place image field as default value in form plugin

Turns out I needed to get the fid of the images and place them into an array. First I started by retrieving the images like I did before

    if ($node->get('field_equipment_photo')->entity != null) {
        $photos = $node->get('field_equipment_photo');
    }

Then I grabbed the fid and placed them into the default value like so

if ($photos[$i]->entity->fid->value != null) {
                $form['image'.$i]['#default_value'] = array($photos[$i]->entity->fid->value);
            }

For some reason even though the fid is just one value it still needs to be wrapped in an array when being used as the default value.


How to hook payment created on commerce 2

One option would be to use hook_entity_create() but I would rather react on Order transition event, such as commerce_order.place.post_transition which is triggered when Order reaches Completed state.


Print out recaptcha webform verification

You can use this code for adding in temlate.php or in custom module for adding captcha.

if (strstr($form_id, 'webform_form_id')) {
        $form['my_captcha_element'] = array(
            '#type' => 'captcha',
            '#captcha_type' => 'image_captcha/Image',
        );
    }

Also refer https://www.drupal.org/node/1254710 link.

One module is there you can check CAPTCHA Webform Bridge.
This is a simple module that automatically set (or unset) CAPTCHA challenges to webforms.


Cannot change logo or colors of a scheme

I'd check the folder/file permissions set on the "public files" folder for Drupal, especially the sub-folders (css, js, color) because if those aren't set right then the Color module can't write changes for custom CSS and logo uploads.


Is Windows XP and XAMPP able to render complex development sites in Drupal 7?

Sorry if my question was not well formatted. It happens that the theme installed was rebuilding on every page load, and that consumed lots of RAM. I switched off the rebuild, and it worked very fast, as expected. It was not a specific OS problem, but a performance one due to theme rebuilding


Implementing hook_user_insert() this way (calling drupal_goto() inside) is plain wrong:

if there are any other implementations of this hook in other modules meant to be called after yours, they will not get called at all
if for whatever reason hook_user_insert() from user module will not be called before your implementation, the user will not be saved at all
if you look at user_save() function in user.module, you'll see that after invoking 'insert' hook there are many other things this function is doing, so if you use drupal_goto(), they will not be done.

What you can do though is to add your own submit function to user_register_form, and in that function set $form_state['redirect'] to wherever you want (note that updating $form_state['redirect'] in hook_form_alter() will not work in this case, as user_register_submit() sets its own redirect, so you need to do it after this - hence the need for your own submit).


Request parser best practices for Services 3.x

This code will send a request encoded as JSON:

function toolreq_test_create() {
  $base_url = 'http://example.com/dirt';
  $options = toolreq_service_login(); //this yields $options['headers']['Cookie'] = $data->session_name . '=' . $data->sessid;
  if (!is_array($options)) {
    print "error
";
    return;
   }

   //create a node
   $node_data = array(
     'title' => 'DHC Tool 03',
     'type' => 'item',
     'status' => FALSE, //ensure unpublished
     'language' => 'und', //lanugage neutral
     'field_webpage' => array(
       'und' => array(
         0 => array('url' => 'http://berkeley.edu',)
       )
     )
   );

   //use json
   $options['headers']['content-type'] = "application/json";
   $options['method'] = 'POST';
   $options['data'] = json_encode($node_data);
   $request = drupal_http_request($base_url . '/node', $options);
   if ($request->error) {
     print ("Error doing http request");
     print '
' . var_dump($request) . '
';
   }
   else {
     print ("Success doing http request");
     print '
' . var_dump(json_decode($response->data)) . '
';
   }
 }

When considering the best format for your request keep in mind:

JSON is a useful format for Ajax applications because it allows you to convert between JavaScript objects and string values quickly. ref: http://www.ibm.com/developerworks/web/library/wa-ajaxintro11/index.html
https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data


I don't know what type of file are you trying to copy over the FTP server, but I did something like that once. This is what I did (it might give you an idea):

I created a content type where I added all the fields for the data I was collecting (like 10 fields)
Then I created an small module that will query the database and will create a CSV file from the data entered on the content type (I applied some logic to the data as well needed for my project)
I use the Drupal default file functions to name the file, placed on the define directory and avoid been overwritten by following exports.
Then on the same small module I created an small function that will read the directory content where the CSV file was and upload it to and FTP server.
When all this was done I use the "hook_cron" to create an small function that will do all that for me.

Note: in my project I created an small admin interfaced where I entered a couple of settings like the name and location of the local directory where the CSV files will be stored as well as the FTP credentials (the client wanted to have there as well) and the location on the FTP server as well.

Note 2: I know this module is good with moving media files: http://drupal.org/project/media_mover/

Thank you.


How to update taxonomy term of a node using services

I think your JSON format to create node is wrong. Please check the created node. I guess it creates node but with empty taxonomy field.

The correct format to create a node having taxonomy term is like follows.

Assuming that your 'widget type' for 'term reference field' is 'Select list' or 'Check boxes/radio buttons'

{
    "title": "my title",
    "type": "page",
    "field_mynodeterm": {
        "und": "3"
    }
}

here field_mynodeterm is machine name of your 'Term reference field' (which is used in content type).

Similarly you can use the same format to update the node

{
    "title": "my updated title",
    "type": "page",
    "field_mynodeterm": {
        "und": "5"
    }
}

If you use 'Autocomplete term widget (tagging)' as widget type for term reference field, the JSON format would be the following

{
    "title": "my updated title",
    "type": "page",
    "field_mynodeterm": {
        "und": "termname"
    }
}

I tested the above scenarios and working fine. Hope this helps.


dbQuery with condition and date_format()

condition() can only be used for simple expressions (=, >, <, <>, BETWEEN, LIKE, and a few others).

Using where() as you are already is the correct way to construct a more complex query.


BrowserTest on a multisite gives an error

It is possible to have a multisite directory setup with PHP Unit.

Since your default directory is empty, I suggest creating a symbolic link from the default directory to the site1 directory. You can do that by using commands similar to this one from sites directory.

ln -s sites1 default

Not sure, but you may also need to adjust the $sites variable in sites.php.

Also, make sure you specify a printerClass like this in the last line.

<phpunit bootstrap="tests/bootstrap.php" colors="true"
         beStrictAboutTestsThatDoNotTestAnything="true"
         beStrictAboutOutputDuringTests="true"
         beStrictAboutChangesToGlobalState="true"
         checkForUnintentionallyCoveredCode="false"
         printerClass="\Drupal\Tests\Listeners\HtmlOutputPrinter">

Here is what my php tag looks like in phpunit.xml (I use SQLite though and specify an output directory.) You may need to adjust directory permissions so that it is writable. I test on my remote machine with a FQDN, not sure if that is ideal though.

<php>
    <!-- Set error reporting to E_ALL. -->
    <ini name="error_reporting" value="32767"/>
    <!-- Do not limit the amount of memory tests take to run. -->
    <ini name="memory_limit" value="-1"/>
    <!-- Example SIMPLETEST_BASE_URL value: http://localhost -->
    <env name="SIMPLETEST_BASE_URL" value="https://dev.example.com"/>
    <!-- Example SIMPLETEST_DB value: mysql://username:password@localhost/databasename#table_prefix -->
    <env name="SIMPLETEST_DB" value="sqlite://dev.example.com/sites/dev.example.com/files/.ht.sqlite"/>
    <!-- Example BROWSERTEST_OUTPUT_DIRECTORY value: /path/to/webroot/sites/simpletest/browser_output -->
    <env name="BROWSERTEST_OUTPUT_DIRECTORY" value="/path/to/document/root/sites/dev.example.com/files/simpletest/browser_output"/>
</php>

Also, I run the phpunit command from the Drupal core directory like this (I do not use group ID but I know it may be possible.

sudo -u www-data ../vendor/bin/phpunit ../modules/contrib/example/tests/src/Functional/ExampleHomepageTest.php

Here is what my test looks like. It will need the correct directory structure and classname.

<?php

namespace Drupal\Tests\example\Functional;

use Drupal\Tests\BrowserTestBase;

/**
 * Tests to ensure Example.com Homepage is reachable
 *
 * @group example_ui
 */
class ExampleHomepageTest extends BrowserTestBase {

/**
 * Modules to enable.
 *
 * @var array
 */
protected static $modules = ['node', 'user'];

protected $profile = 'standard';

/**
 * {@inheritdoc}
 */
public function setUp() {
parent::setUp();

}

/**
  * Tests that the reaction rule listing page works.
  */
public function testHomepage() {

  $account = $this->drupalCreateUser(array('administer site configuration'));
  $this->drupalLogin($account);

  $this->drupalGet('<front>');
  $this->assertSession()->statusCodeEquals(200);
  $this->assertSession()->pageTextContains('cleaning');
 }
}

This page will be useful: https://www.drupal.org/docs/8/phpunit


reCaptcha is not display correctly in the Bootstrap Login Modal registration form

This helps me adding recaptcha in modal forms.

Check this patch.
https://www.drupal.org/node/1463768 in thread number 21.


Custom form, input with ajax autocomplete not working

After some tests I have found the problem. My code is right and it works good. The problem was the template file input--textfield.html.twig. Input textfield needs some automplete classes to work and this template deleted them to add some other classes. The required classes are: form-autocomplete form-text ui-autocomplete-input. I have changed this template file to add a new class I need but without deleting the other, and then, autocomplete works.


How to create a link on a field in a custom template file

You will want to use a preprocess function in your theme's template.php file, so that you can manipulate the element's attributes before it is rendered.

For example, if you wanted to link a particular field to the node's page, you could implement template_preprocess_field() as such:

function THEMENAME_preprocess_field(&$vars) {

  $items = $vars['items'];
  $node = $vars['element']['#object'];

  $path = 'node/'.$node->nid;

  if($vars['element']['#field_name'] == 'TARGET_FIELD_NAME'){
    foreach($vars['items'] as $key=>$item){
      $vars['items'][$key]['#markup'] = l($item['#markup'], $path);
    }
  }
}

the l() function is a structured way to build a link within the Drupal API. In this example I have assumed that the field is only allowing plain text, but if your field allows HTML, you can pass extra variables to the l() function that will allow that.

You can access other node data in the $node variable I created, such as the node type, published status, etc. If you want to investigate all the variables available to you in this (or any) preprocess function or template, I would suggest installing the Devel module and printing out the variable you are interested in with the kpr() function. For example, you could add the following code to the preprocess function I created above:

kpr($vars);

and you would be able to see all of the data available for use in that function in an easy-to-read format.


Drupal 7 Custom Content form_alter validation

Perhaps try $form_state.

$form_state['field_adpostcode']['und'][0]['value']['#value'] = 'TESTING';
$form_state['field_adpostcode']['und'][0]['#value']['value'] = 'TESTING';

I suspect the array structure is different but you get the idea.


How can I attach the same library with Javascript multiple times on the same page with different settings?

Thanks to responses from 4k4, the following works:
$id = $items[0]->getEntity()->uuid() . '__' . $this->fieldDefinition->getName();
$settings = [
  'id' => '#' . $id,
  'setting1' => 'foo',
  'setting2' => 'bar',
];
$elements['#attached']['drupalSettings']['gallery'][$id] = $settings;

And then in the javascript:
(function ($) {
  Drupal.behaviors.galleryBehavior = {
    attach: function (context, settings) {
      $.each(settings.gallery, function(key, item) {
        var main_selector = item.id + ' .gallery-main';
        alert(main_selector);
      });
    }
  };
})(jQuery);


The "Search by Date" Views field should be configuration (clickable) in the Views Administration and in its settings allow you to select the Year range, or the granularity of the date fields and their format.


Read only version of node form for anonymous users?

can anyone suggest a way to preview the form?

The no code way would be to use screen shots (images).

Alternatively, you could check if the user is logged, it they are not then unset the submit button via a hook_form_alter.

  prevent someone from circumventing it by submitting the form manually

Better yet, if user is anonymous, you alter the callback function of the submit button by unsetting the existing one and adding a new custom callback.


Add #theme_wrapper after drupal_render() is called

There are two errors in your code:

If you use '#theme' => 'custom_theme_func' to reference the theme function, Drupal will look for theme_custom_theme_func(), not my_module_custom_theme_func().
The argument a theme function gets is always $variables, an array that in your case probably contains $variables['element'].
What exactly that array contains depends from the definition given in the implementation of hook_theme(). For example, theme_status_report() is defined as:

'status_report' => array(
  'render element' => 'requirements',
  'file' => 'system.admin.inc',
),

The array it gets contains $variables['requirements'].

theme_image() is defined as:

'image' => array(
  'variables' => array('path' => NULL, 'width' => NULL, 'height' => NULL, 'alt' => '', 'title' => NULL, 'attributes' => array()),
),

The array it gets can contain $variables['path'], $variables['width'], $variables['height'], $variables['alt'], $variables['title'], and $variables['attributes'].

As for setting #theme_wrappers, setting them in the theme function doesn't have any effect, as the theme function doesn't receive the $variables array as reference; therefore, it cannot change its content, and pass those changes back to drupal_render().

As zdecibel said, you can use the preprocess function to set the theme wrappers, even if it is probably better to define them directly in the code you shown at the beginning (the first 3 lines), as you are not dynamically changing the theme wrappers. (At least, that is what you shown in your code.)


Fatal error when altering the user login form

Looks like the problem is your class definition.

['attributes']['class'] should be an array but you are setting it as a string.

Your line:

$markup .= ' ' . l(t('Sign up'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'), 'class' => 'register-link')));

Should be:

$markup .= ' ' . l(t('Sign up'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'), 'class' => array('register-link'))));


PHP XML parsing + daily authentication request

You could write a module where you implement hook_cron() to get the authentication ID and then store in the drupal DB (e.g. as variable via variable_set()). After that you can use it inside your templates without any worry. But you have to trigger your cron.php once a day via a sytem cron-job or the poormanscron module. For PHP xml-parsing take a look at SimpleXML.

EDIT: Module creation:

For this job it would be a simple module. Take a look at the module-dev-guide. First you create a YOURMODULE.info file. After that you put your code inside a YOURMODULE.module file. Than implement that hook_cron() like that:

function YOURMODULE_cron() {
     update_news_service_id();
}

function update_news_service_id() {
    // add your code here
}

One more comment: If you try to solve it this way you must consider calling update_news_service_id() from the template (or ..._preprocess()) if you run into an expired service id-error.


How can i display user name and email address fields to the user on "My Account Page"?

You will need to create a custom module to achieve that functionality.

If you want to override tabs in view page

function mymodule_menu_alter(&$items) {
  $items['user/%user/view']['title'] = t('My account');
  $items['user/%user/edit']['title'] = t('Edit account information');
}

If you was to display additional info in view page

function mymodule_user_view($account, $view_mode, $langcode) {
  // hide unwanted fields
  hide($account->content['summary']['member_for']);
  hide($account->content['summary']['blog']);
  hide($account->content['user_picture']);

  // add information
  $account->content['summary']['#title'] = t('My Account');
  $account->content['summary']['personal'] = array(
    '#type' => 'user_profile_item',
    '#title' => t('Personal'),
    '#markup' => get_profile_details($account),
    '#weight' => -100,
  );
  $account->content['summary']['login'] = array(
    '#type' => 'user_profile_item',
    '#title' => t('Login'),
    '#markup' => get_profile_details($account, 'login'),
    '#weight' => -99,
  );
}

This function returns details in list. Feel free to add/delete details based on your requirements

function get_profile_details($account, $view = 'personal') {
  // profile details
  $items = array();
  switch($view) {
    case 'personal':
      if($account->picture) {
        $items[] = theme('image_style', array('path' => $account->picture->uri, 'style_name' => 'thumbnail'));
      }
      $items[] = t('Name: ').$account->field_account_first_name['und'][0]['value'].' '.$account->field_account_last_name['und'][0]['value'];
      $items[] = t('Email: ').l($account->mail, 'mailto:'.$account->mail);
      $roles = array();
      foreach($account->roles as $role) {
        if($role != 'authenticated user') {
          $roles[] = ucwords($role);
        }
      }
      if(count($roles) > 0) {
        $items[] = t('Role: ').implode(', ', $roles);
      }
      else {
        $items[] = t('Role: ').t('General user');
      }
    break;
    case 'login':
      $items[] = t('Username: ').$account->name;
      $items[] = t('Timezone: ').$account->timezone;
      $items[] = t('Member since: ').format_interval(REQUEST_TIME - $account->created);
      $items[] = t('Last login: ').format_interval(REQUEST_TIME - $account->access);
    break;
  }
  return theme('item_list', array('items' => $items));
}

Let me know if you need any help


How can i access variable inside body node(input format:php) from my own module

Some comments on your code and question:

global $get_specific_ip; and $GLOBALS['get_specific_ip']; are both the same  thing. For more info see http://php.net/manual/en/language.variables.scope.php
global variables and the template $vars array are different, so
global $get_specific_ip;
$vars['get_specific_ip'] = get_client_ip();
won't actually set a global variable because you're never setting $get_specific_ip to anything, it will only set the $vars['get_specific_ip'] variable, which will make $get_specific_ip available in all your templates but not as a global variable.
The getip_preprocess() does not seem like the best place for this code. IP address is not specific to theme templates and would be best as either a global variable or attached to the existing global $user object. In either case gettip_preprocess() is not the optimal place because it isn't a global solution.
If the function get_client_ip() is a custom function of yours you should name space it to your module to avoid possible conflicts with other functions. For example, call it getip_get_client_ip().
The variable name $get_specific_ip is a little strange because it sounds like an action or function name but it should describe what is stored in it. For example $client_ip. That however could also run into name spacing issues so would be better as $getip_client_ip or something like that.
Note that there is a Drupal function ip_address() that might possibly be useful to you.

If you really want this available everywhere then you could use hook_boot() like this:

/**
 * Implement hook_boot().
 */
function MODULENAME_boot() {
  // Set the user's IP address to a global variable for use elsewhere.
  global $get_specific_ip;
  $get_specific_ip = get_client_ip();
}

Then you can use global $get_specific_ip; from anywhere on the site to get that variable.

The use of hook_boot() means it will run even on cached pages, which is a must for IP detection because you want your code to run and get the current user's IP even if they are getting a cached page.
The other side to that is that you need to be careful to try not to use resource intensive code in there because it will always run on every page load.

It's worth noting at this point that whenever doing something with dynamic data like IP address make sure to properly test cached pages to make sure they always function as you would expect.

One last thing is that Drupal core already makes the user's IP address available to you in the global $user object.

So you can also get the IP like this:

global $user;
$ip = $user->hostname;

So unless you are doing something special in your get_client_ip() function it might be better to use that.


How can I manually edit the search options in a facet block?

I decided to implement this by creating a new facet instead of editing an existing one.  This article describes the process.

The basic code looks like this:

/**
 * Implements hook_entity_property_info_alter().
 */
function MYMODULE_entity_property_info_alter(&$info) {
  $info['user']['properties']['agg_gender'] = array(
    'type' => 'text',
    'label' => t('Search API Agg Gender'),
    'sanitized' => TRUE,
    'getter callback' => 'MYMODULE_search_agg_gender_getter_callback',
  );
}

/**
 * Getter callback for agg gender property.
 */
function MYMODULE_search_agg_gender_getter_callback($item) {
  // Need to load the user object to get fields
  $account = user_load($item->uid);
  switch ($account->field_gender['und'][0]['value']) {
    case 'F':
      return 'f';
      break;
    case 'M':
      return 'm';
      break;
    case 'O':
      return 'fm';
      break;
  }
}


How to show pop up message "Are you sure ......?" with "OK" button before save the content

The custom way to do this would be to use hook_form_alter to add some jquery into the form you are targeting that would bind to the submit action of the form and execute some javascript function (ex. an alert) if a form field value is not filled out.

The key library for this is the jquery validation library here:

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

There are also a couple modules you could try and install that implement this library and offer direct integration with your field through the form api. I've used this one:

http://drupal.org/project/clientside_validation

To achieve a similar validation effect as what you're looking for.


theme('status_messages') will output all of your messages those are pushed using drupal_set_message()

EDIT:

If you are processing your form via ajax call then you can return the status messages by following code example. Use it in your ajax callback where form is being posted.

$messages = theme('status_messages');
drupal_json_output(array('status' => 'OK', 'data' => $messages));


Show all revisions with entity reference field referencing a specific entity

So if I am reading this correctly, Content Type A references Content Type B. You want to show all revisions of Type A nodes that reference a certain Type B node.

Contextual Filter: Content: Reference Field for Type B Provide Default: ___
There are two revision relationships.. ID and NID. The one with ID is provided by default. Add the one for NID and for its relationship, choose the one with ID.
After it's added, move it above the ID relationship. This is vital and I don't even know why..
Make sure your Title field doesn't use any relationship.

Now, all revisions that reference Type B will show and be linked properly.

If anyone can explain the significance of reordering the relationships, please post in the comments. I spent far too long working on this a few months ago and a reason would be great!


by this module String Overrides you can translate strings .
That's it


Display particular Image Style for image based on Role of User?

You can use a hook_preprocess_image_style to alter the style name to use:

/**
 * Implements hook_preprocess_HOOK for theme image_style.
 */
 function mymodule_preprocess_image_style(&$variables) {
   $style = mymodule_determine_style_to_use($variables);
   $variables['style_name'] = $style;
 }

Take care that you do not alter all image styles, but only those you want/need to change, so mymodule_determine_style_to_use() should e.g have a check on $variables['style_name'] being S1 or S2.


Why isn't my Sub Theme's CSS file showing up?

Any change in .info does not take effect only by clearing cache. Remember to clear the theme registry. You can do this by just going to the admin/appearance and saving it.


The most easy way to get this taken care of is use the Views module. Set up a view that queries for nodes based on the term as an argument. This will give you what you already have, however, it will also allow you to use exposed filters to get more granular with the results based on the values of the exposed fields.

If you would like to learn more about exposed filteds and views, check out this video, which is not the best video in the world, but highlights using exposed filters in Views, which should hopefully get you on the right track.

As a summary, what your doing is replacing Drupal's built in taxonomy view pages with a view instead and allowing views to handle the querying and filtration of the data respectively.

Happy Programming!


User->id() or Node->id() do not give back an integer but a string?

The value is in integer (for most content entity types, that is). The variable type however is a string.

That has a simple technical reason, values loaded from the database are always strings, those put into the node object and never explicitly cast to something else. Doing so would be too expensive for what it brings.


basic difference between Date, Date(ISO format), Date(Unix timestamp) to create a field

Below explains three field types in details

Date

Called a 'datetime' field type in techno database speak. This format type is recomended for most installs because it takes advantage of the database's date handling functions without any conversion, which means faster queries.
Stores the date in the database's native date format (YYYY-MM-DD HH:MM:SS).
The data is in a human-readable form.
You can use it for incomplete dates, i.e. only a year or only a year and a month, and pad the other values with zeros, so it does not appear to be any more precise than it really is.

Date (ISO Format)

Stores the date in an ISO format (YYYY-MM-DDTHH:MM:SS).
The data is in a human-readable form.
List You can use it for incomplete dates, i.e.
only a year or only a year and a month, and pad the other values with
zeros, so it does not appear to be any more precise than it really
is.
It is a format that is internationally-recognized, and it is used
as-is on many web sites and in many applications.

Date (Unix Timestamp)

Stores the date as an integer.
Takes up less room in the database because it's smaller.
Often easier to use for date calculations because you can increase or decrease it just by adding or subtracting seconds.
It is the format used by php date functions.
It must be filled with a complete date -- year, month, day, hour, minute, second, so you sometimes have to arbitrarily set some of these values even if they are not applicable.

Taken Reference from Here


Resetting/reverting a custom module's update 'N value'

The schema_version column in the system table contains the version of the last successful update. Manipulate that value and you can re-test your update.

The name column is the machine name of the module, same as the info file is named.

This query will do the trick for you.

UPDATE system SET schema_version = XXXX WHERE name = 'name_of_module';


How can I display node fields contextually in a block with terms from two separate vocabularies based on node ID?

My original goal here was to do this dynamically via contextual filters so I wouldn't need to create a bunch of individual blocks to control various displays. However, I never found a suitable solution for doing this dynamically via the contextual filters, so I ended up resorting to using different blocks with the different filters applied for each one appropriately. It makes a little more of a mess when it comes to managing blocks, but that's not that big a deal.


How to implement an enumerated field using hook_schema()?

If you are using the Form API to accept this data, you can map integers to string values.

You can also store that mapping array in your .module file.


The easiest thing for you to do would be to override the actual template file which displays that language.

Look at the template file called search-results.tpl.php in the core search module.

It has the following code at the bottom:

<?php else : ?>

<?php print t('Your search yielded no results');?>

  <?php print search_help('search#noresults', drupal_help_arg()); ?>
<?php endif; ?>

Copy the entire template file (you don't even need to rename it, it'll override the file in the module) and paste it into your own theme's /templates folder.  Re-write the section I've pasted at the top to be whatever you want.  The part that prints the search_help() is the bulleted list you're looking to change.

Of course, before the system will pick up your new template file, you need to clear all your caches!

Let us know if this works!


Creating custom form at registration process for unknown number of nodes

You can try with

field_attach_form to attach the 'trip' content type's fields to user form. (with an alter can become multivalue)

on submit you can use these values to populate the trip entity with entity_metadata_wrapper and create a new node

you can build N menu_items than are the trip of the user by a custom menu


Custom ajax widget can't save generated value to database - $item always zero

I found multiple examples on how to write your a custom submit handler, but most of them had a flaw in it. They were either always or never called. Sometimes I couldn't access the node_id, which was crucial for me.

I ended up using this:

function b2share_form_node_form_alter(&$form, &$form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'seal_the_deal';
}

function seal_the_deal($form, &$form_state, $entity_id, $entity_type, $form_id) {
 $values = array(
  'url' => $form_state['values']['b2share_fieldset']['url'],
  'pid' => $form_state['values']['b2share_fieldset']['pid']
 );

 if ( (empty($values['url'] == false) || (empty($values['pid']) == false)) ) {

    $insert = db_insert('field_data_field_b2share')
     -> fields(array(
        'field_b2share_url' => $values['url'],
        'field_b2share_pid' => $values['pid'],
        'entity_id' => $form_state['node']->nid,
        'entity_type' => 'node',
        'bundle' => $form_state['node']->type,
        'delta' => 0,
        'language' => 'und',
     ))
    ->execute();
     }
   }

Details can be found here:

Custom submit handler is also called when deleting a node

http://atendesigngroup.com/blog/form-altering-node-addedit-forms

Drupal 7 custom form submit handler is not being called


Modal window open once when user visits website

Why invent a new module while there are existing, well-supported ones?

Two existing modules:

The popup_message does what you want and has a lot of features and a large installed base.
popup_announcement - this is a relatively new module with full html support, but with only a few downloads.


In your composer.json file (found in the root of your drupal site) find the line "drupal/core": "x.xx" and change it to "drupal/core": "~8.8" and then run composer update drupal/core --with-dependencies

Also, don't forget to run your database updates after! (run drush updb or go to your-drupal-site.com/update.php)


Use db_merge

  In the general sense, a Merge query is a combination of an Insert
  query and an Update query. If a given condition is met, such as a row
  with a given primary key already existing, then an Update query is
  run. If not, an Insert query is run.

Thus, db_merge adds it, if it doesn't exist yet. OR updates it, if it already exists.

db_merge('example')
  ->key(array('name' => $name))
  ->fields(array(
      'field1' => $value1,
      'field2' => $value2,
  ))
  ->execute();

  by: dzutaro, tlyngej, stewart.adam, AndreyMaximov


How can I allow the user to choose their language upon registration?

As Drupal 7 doesn't show the language selector for the users who create their own account, you need to implement hook_form_user_register_form_alter() (see the documentation for hook_form_FORM_ID_alter()) using the following code.

function mymodule_form_user_register_form_alter(&$form, &$form_state) {
  // Only alter user forms if there is more than one language.
  if (!isset($form['locale']) && drupal_multilingual()) {
    locale_language_selector_form($form, $form_state, $form['#user']);
  }

  if (isset($form['locale']) {
    $form['locale']['#access'] = TRUE;
  }
}

The code is generic, and works even in the case a module removed the language selector field (which is something a module should never do, though).

"user_register_form" is the form builder used for the "user/register" path. The code works if the Locale module is enabled. The code will show the language selector if there are more than one language enabled; differently, drupal_multilingual() would return FALSE.

  $items['user/register'] = array(
    'title' => 'Create new account',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('user_register_form'),
    'access callback' => 'user_register_access',
    'type' => MENU_LOCAL_TASK,
  );

The code used from the Locale module is the following one.

function locale_form_alter(&$form, &$form_state, $form_id) {
  // Only alter user forms if there is more than one language.
  if (drupal_multilingual()) {
    // Display language selector when either creating a user on the admin
    // interface or editing a user account.
    if ($form_id == 'user_register_form' || ($form_id == 'user_profile_form' && $form['#user_category'] == 'account')) {
      locale_language_selector_form($form, $form_state, $form['#user']);
    }
  }
}

In general, the equivalent for hook_user('register') in Drupal 7 is hook_form_user_register_form_alter(); the equivalent of hook_user('form') is hook_form_user_profile_form_alter().


LoginToBoggan and user registration password to allow users register with password and email verification at the same time

You could use https://www.drupal.org/project/registration_role to auto assign a different role (as in other than authenticated) to users who register.
https://www.drupal.org/project/autoassignrole this one offers a little bit more functionality.


Why is the default Search module not returning partial results?

Actually there's a quick way to set this up with the Search API and the Search API Database Search modules. No need for Solr.

Enable both the modules and go to the Search API configuration page
(admin/config/search/search_api)
Add a server and give it a recognizable name (such as "MySQL"), make sure it's enabled
Choose the following service class: Database service (normally the
only option. If you don't see it, make sure that the "Search API
Database Search" module is enabled).
Selecting this service class will provide you the option Search on
parts of a word (make sure you enable it). Now hit "Create
server". Next, go back to the Search API configuration page, and
add an index. Again give it a recognizable name, such as "Contentindex", and make sure it's enabled.
Select the server you recently created (in this example "MySQL").
Datasource options: check the content types you want to index (the
description of this field may be a bit confusing, but make no
mistake: you should check the content types you want to index, not
the ones you want to leave out).
You could check "Index items immediately", but that depends on the
size of your content. This option is alright for smaller websites.
In the other case: let cron take care of it. Hit "Create index".
Next, you want to enable the fields (in the fields tab) to that
very index, e.g.: contant type, title, status and author - and hit
"Save changes" (we'll take care of the related fields later).
Then you want to configure the filters (in the filter tab). Here
you can enable the bundle filter, if you want to finetune the
content types once again (probably won't need to).
Down below you'll find the highlight filter, to highlight the
search word in the results.
Now return to the fields tab and unfold the "Add related fields"
 tab. Add all the fields of which you want to get the content
 indexed, and hit Save Finally go to the "view" tab of the index,
 and index now all the items.

The last step is to create search results page and search block in Views, which only takes a few minutes.

Make sure the submodule Search Views is enabled and create a
view page which will show "Contentindex" (select the name you gave
to your index configuration instead of "content" which is selected
by default.
Add all the fields (make sure your format is "fields") that every
search result should consist of (title [link to content], body, …).
You'll notice that these field look like this Indexed Node: Title
Add an exposed filter: Search: Fulltext search; and select the
following in its settings: Contains any of these words, and use
as: Search keys.

You're done!

There's an excellent video tutorial on this partial search method without Solr, which also incorporates faceted search (which is not necessary for partial search, but in case you're interested…). If you're only looking for a partial search option, you can watch the video until 5:08 and after that skip to 6:45.


How do I make a custom module trigger a function when content is unpublished?

Based on this: My goal is to then delete a specific-type node when it gets unpublished.

You can use hook_ENTITY_TYPE_update.

You will have to just check, if the (not the original) entity is unpublished, and the it's type is the one you are looking for.

+1: From OO perspective you can also take a look on events.


How to get group ids by ids of elements of group content?

The way Group module maintainer recommended:

use Drupal\group\Entity\GroupContent;

function getGroupIdsByEntity($entity) {
  $group_ids = [];

  $group_contents = GroupContent::loadByEntity($entity);
  foreach ($group_contents as $group_content) {
    $group_ids[] = $group_content->getGroup()->id();
  }

  return $group_ids;
}


Redirect  is the drupal 7 version of path redirect. Path redirect This module allows you to specify a redirect from one path to another path or an external URL, using any HTTP redirect status. and GlobalRedirect is a simple module which…
Checks the current URL for an alias and does a 301 redirect to it if it is not being used.
Checks the current URL for a trailing slash, removes it if present and repeats check 1 with the new request.
Checks if the current URL is the same as the site_frontpage and redirects to the frontpage if there is a match.
Checks if the Clean URLs feature is enabled and then checks the current URL is being accessed using the clean method rather than the 'unclean' method.
Checks access to the URL. If the user does not have access to the path, then no redirects are done. This helps avoid exposing private aliased node's.
Make sure the case of the URL being accessed is the same as the one set by the author/administrator. For example, if you set the alias "articles/cake-making" to node/123, then the user can access the alias with any combination of case.
Most of the above options are configurable in the settings page. In Drupal 5 you can access this after enabling the globalredirect_admin module. In Drupal 6, the settings page is bundled into the module.


How to show a notification at a speicific page based on visitor's country?

If you can sort out the Smart IP bid and you get the user's country then you can use Context and Context GeoIP.

Create a new Context where you can choose the countries you don't deliver as a condition and show block as a reaction. Your block might be a modal box informing your users.


I know this is not an answer (I don't yet have enough reputation to post a comment); I am also uncertain if you are still looking for answer. It is possible sometimes for distributed modules to call user_login_submit.

For example, the D7 LDAP module's _ldap_authentication_user_login_authenticate_validate calls user_login_submit, which causes the user login form to fork two calls to user_login_finalize, both of which triggers hook_user_login. If you are still experiencing this problem, one possible way to debug your application is to use PHP XDebug, and dsm function traces.

After you have installed XDebug, you can use xdebug_call_function() on user_login_submit, user_login_finalize, user_module_invoke to see where the two calls of hook_user_login are coming from. I hope this helps.


Create a Node with Fields and turn them into tabs in a display?

The easiest approach to create tabs to nest your content for visitors to see on your pages without much hassle is to try to use the Field Group module in D7.

Another solution is to use the Paragraphs module with 2 fields: title and body. And try to setup Field Groups possibly to treat each paragraph entry as a Tab on the page ...


How to secure ajax on automatically save field data

It seems pretty secure. Also check the content type permissions for the role ;)


How to write session data for another user?

I'd delete this question but someone might find this useful.

It toke me half a day to figure this thing out and the result feels quite hacky and not Drupal-way in any shape or form but it's the only working solution I have been able to put together. The SessionBag is just a simple wrapper around session information - for my purposes.

/**
   * Creates session for provided user without destroying
   * the current user's session.
   *
   * @see user_login_finalize()
   * @see \Drupal\Core\Session\SessionManager::regenerate()
   *
   * @param int $uid
   *
   * @return \Drupal\foo_auth\SessionBag
   *   Session information.
   */
  public function createSession(int $uid): ?SessionBag {
    $session_options = $this->sessionConfig->getOptions($this->requestStack->getCurrentRequest()) + session_get_cookie_params();
    $session_id = Crypt::randomBytesBase64();

    // @see \Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag
    // @see \Symfony\Component\HttpFoundation\Session\Session::set()
    $data = [
      '_sf2_attributes' => [
        'uid' => $uid
      ]
    ];

    // Special handling for session serialization.
    $current_session = $_SESSION;
    $_SESSION = $data;
    $serialized_data = session_encode();
    $_SESSION = $current_session;

    // @see \Drupal\Core\Session\SessionHandler::write
    try {
      $this->database->insert('sessions')
        ->fields([
          'uid' => $uid,
          'hostname' => $this->requestStack->getCurrentRequest()->getClientIP(),
          'session' => $serialized_data,
          'timestamp' => REQUEST_TIME,
          'sid' => Crypt::hashBase64($session_id)
        ])
        ->execute();
    } catch (\Exception $e) {
      watchdog_exception('foo_auth', $e);
      return NULL;
    }

    return new SessionBag(
      $session_options['name'],
      $session_id,
      $session_options['cookie_lifetime'] + REQUEST_TIME,
      $session_options['path'],
      $session_options['cookie_domain'],
      $session_options['cookie_secure'],
      $session_options['httponly']
    );
  }


Update the price of a line item after shipping method is selected

You want to change the price components of the line item you're wanting to update. You can use rules for this, but since you're writing a hook, you can just call the function that Rules would use:

commerce_line_item_unit_price_amount($line_item, $amount, $component_name, $round_mode);

For example, if you want to change it to $5.00:

commerce_line_item_unit_price_amount($line_item, 500, 'base', COMMERCE_ROUND_HALF_DOWN);


Out of the box, no it does not. For that you need to use an add-on module:

Content Access Control Modules

  All the modules that implement an access control system.

Information on Access Control Modules
A web search for 'drupal access control' will yield thousands of sites, tutorials, videos and other useful information.


You place your menu through the admin/structure/blocks form. Relocate the menu block from the disabled category at the bottom of the form to wherever you wish (footers).  To get rid of the name, select configure for the menu block and enter  in the Title box.


delete a specific element within field collection programmatically

You need to grab the id of the field collection and wrap itself in an entity wrapper. Use the save method in the wrapper to do this instead of the entity_save function. E.g.

 $wrapper = entity_metadata_wrapper('field_collection_item', $entity);
 $wrapper->field_specific_field_collection_item->set("");

or:

$wrapper->field_specific_field_collection_item = array();
$wrapper->save();


How to call a custom function when Migration(Import) is done?

use a static variable in postimport to do a check that you're on the last folder or task or the import, there has to be some value you can track. You could even set a variable of all the csv files to do (in-order) within your migration class -- and check which file you're on in postimport.


Why is 1 of 8 menu choices not displaying for anonymous users?

Check the permission of whatever "Board of Directors" links to (a node, a view, something else?). To ensure anonymous have permission to access it (also).


How to change the "Check boxes/radio buttons" fields weight?

In field edit settings page, you can organize your options in "Allowed values list" section.


8 - Node::load is generating an object with circular reference which is crashing kint() and var_export()

Yes, this is normal and by design.

When you want to dump it, just use $node->toArray(). Then you get an array with the plain values. You can use those field names and properties again to access the values on the node object, e.g. $node->yourfield->value.


How can I generate a Report from database table? and how can I show it in page

Create a page view, and see your report in that page.


How do I reference another field properly?

It's best to turn on the devel module and do a dsm() on the $entity object to see what fields are available to you. Even if you think field_name would work, there are other arrays inside that field variable.

In the case below i am parsing a URL link from another field and exploding it via the dashes. Since my field_sell_link is a "link field" i had to add the ['url'] at the end of the field reference instead of the usual ['value']. I didn't find this out until I did a dsm on $entity. You can also do a set_message(print_r($entity)); too.

let me know if this helped anyone.

Example code for the PHP code section:

$ebay_url = isset($entity->field_sell_link['und'][0]['url']) ?
  $entity->field_sell_link['und'][0]['url'] :
  'zero/one/two/three/nothing-here-asdf/last';

if (isset($ebay_url)) {
  $url = explode('/', $ebay_url);
  $pattern = '/-/';
  $replace = ' ';
  $entity_field[0]['value'] = 'testxxx' . $url[3];
}
else {
  $entity_field[0]['value'] = "";
}


Maybe you could use the teaser for displaying your entityreference nodes. Under Manage display under format for the entity reference field, choose Rendered entity, choose settings and use teaser instead of full mode.

Go the the display settings for the content type that is being referenced and apply your display settings for the teaser display.


Did you try Facet API filters? check the Facet API module

The Facet API module allows site builders to easily create and manage faceted search interfaces. In addition to the UI components that come out of the box, themers and module developers can build their own widgets that can optionally be contributed back to Drupal.org. Facet API works with the core Search, Search API, and Apache Solr Search Integration modules (including Acquia Search) meaning that code and configuration can be reused as-is with the most popular search solutions available to Drupal. Refer to the documentation for more details.


When to add an extra "helper" table rather than running complex query

As long as all your fields used in JOIN and WHERE are indexed properly, you don't really need a separate table to do this, I probably would rewrite it in a single query, sub queries tend to be slow.

If you want something intermediate (in case you have > 1.000.000 rows), you have 2 options:

Create a temporary table and keep it up to date using cron and/or
hooks
Use caching in Drupal to remember the result and combine it
with hooks

Both solution have pro's and con's:

Can be updated by cron, but has a record for every user, no matter if that user visits the site or not.
Needs to run the query when there's no cached data, but will be faster on a second page visit.


The default value is stored in the field's config, rather than the node type's. Currently it's not possible to get that value without having a node to work with.

This is alluded to in NodeTypeForm::form() (and also the save() method of the same class):

if ($this->operation == 'add') {
  $form['#title'] = $this->t('Add content type');
  $fields = $this->entityManager->getBaseFieldDefinitions('node');
  // Create a node with a fake bundle using the type's UUID so that we can
  // get the default values for workflow settings.
  // @todo Make it possible to get default values without an entity.
  //   https://www.drupal.org/node/2318187
  $node = $this->entityManager->getStorage('node')->create(['type' => $type->uuid()]);
}
else {
  $form['#title'] = $this->t('Edit %label content type', ['%label' => $type->label()]);
  $fields = $this->entityManager->getFieldDefinitions('node', $type->id());
  // Create a node to get the current values for workflow settings fields.
  $node = $this->entityManager->getStorage('node')->create(['type' => $type->id()]);
}

It goes on to set the options arrays for the checkboxes using that node:

$workflow_options = [
  'status' => $node->status->value,
  'promote' => $node->promote->value,
  'sticky' => $node->sticky->value,
  'revision' => $type->isNewRevision(),
];

So, for now at least, you'll probably need to do the same thing.


With several user profile pages built in Views as tabs, how do I build a menu linking to those pages?

I went ahead and implemented the OpenAtrium code in Drupal 7 which I'll use unless somebody comes up with a better answer.

/**
* implements hook_block_info()
*/
function helper_block_info () {
  $blocks['helper_user_links'] = array(
    'info' => t('Menu user links'),
    'cache' => DRUPAL_CACHE_PER_ROLE,
  );

  return $blocks;
}

/**
* implements hook_block_view()
*/
function helper_block_view($delta = ''){
  $block = array();

    case 'helper_user_links':
      $block['subject'] = NULL;
      $block['content'] = array(
        '#markup' => theme('links', array(
          'links' => helper_user_links(),
          'attributes' => array('class' => 'menu'),
        )),
      );
    break;
  }

  return $block;
}

/**
 * Generates an array of account links suitable for use in theme_links().
 */
function helper_user_links() {
  global $user;
  $links = array();

  // @TODO: If menu.inc had a real API function for this we would use it, but
  // as of now we'd have a copy hand paste hack job of menu_local_tasks()...
  $paths = array(
    "user/{$user->uid}/businesses/reviews" => '',
    "user/{$user->uid}/content" => '',
    "user/{$user->uid}/workbench" => '',
    'logout' => '',
  );
  foreach ($paths as $path => $title) {
    $item = menu_get_item($path);
    if ($item && $item['access']) {
      $links[] = array(
        'title' => !empty($title) ? $title : $item['title'],
        'href' => $item['href'],
        'class' => $_GET['q'] == $item['path'] ? 'leaf active-trail active' : 'leaf',
      );
    }
  }
  drupal_alter('helper_user_links', $links);
  return $links;
}


Combining several attributes with string join

The Feeds Tamper module has an implode plugin that makes this work.

  Feeds Tamper provides a small plugin architecture for Feeds to modify data before it gets saved. Several plugins are available by default and are described in the examples section below. Additional plugins can be added in separate modules or through the issue queue.

  Replace every instance of 'dog' with 'cat'
  Filter items based on keywords or vocabularies
  Make every letter uppercase, lowercase, or capitalise every first letter
  Break a comma separated list of words into Taxonomy terms or a multivalued text field
  Combine separate 'first name' and 'last name' fields into one 'name' field
  Convert urls from relative to absolute


Migrating database content to a new server

It will be sufficient most of the time, but it is a good idea to open mydrupalsite.sql in text editor and scan it for old configurations. Especially if domain name also changes. Even if not, some modules needs may save things like local network addresses to data import sources et cetera.

And of course don't forget to truncate all cache tables and session table before data export. Best would be to disable cache and css/js aggregation on site before export, truncate tables, and re-enable these performance options on new site.

Alternatively, simply omit data from these tables when exporting with Backup and Migrate module or your favourite SQL client you use for export (for example, phpMyAdmin can do that, too). Of course disabling aggregation to have proper variables exported still needs to be done.

Safety note:

Truncating cache and session tables is only safe if you have put your site in maintenance mode. If you want to avoid it, you can't really truncate them, as they will be instantly re-populated and only effect will be performance hit and users logged out. In that case you need to omit that data, and make sure no one will change anything in the time of server switching, for the sake of consistency. Read only mode can help with that.

When talking about migration security - more modules equals more risk. My experience tells me that if your site is complicated one, you need to assume something will go wrong. So plan for it. Make sure you have time and manpower to fix it, no matter what exactly it is. Make sure you have enough old server paid for at least month after planned migration, so you can postpone and retry it. And make sure hosting company you are migrating away from will keep backups for you for at least 3 months.


put views block in a content type different than the one in views block

Getting a block view to get a parameter from the node view can be tricky.  Here's what you can do:

For "tribute nodes":

create a new view to display "offer" nodes
add a filter to that view to limit the content type to "offer"
add an argument to that view to your node reference
Under "Action to take if argument is not present" select "Provide default argument"
For default argument type, select PHP Code
We now need to write some php code to grab the node reference id from the node being viewed.  your case might be a bit different, but here's a starting point: (you dont need php tags)

<?php

if(arg(0) == "node" && is_numeric( arg(1) )) {
  $node = node_load(arg(1));
  if($node->type == 'tribute') {
    return $node->field_county[0]['nid'];
  }
}

replacing field_county with whatever your cck field is named.

Then you should be able to add that block to any tribute node page and it will pull in the associated offers, and just do the same thing again for the offers->tribute direction.


How can I display a change password form on its own?

I couldn't find anything out there already and it sounded like a handy thing to have, so here's a small module providing a block with a change password form:

File: change_password.info

name = Change Password
description = Provides a block containing a form for the current user to change their password.
core = 7.x

File: change_password.module

<?php

/**
 * Implements hook_block_info().
 */
function change_password_block_info() {
  return array(
    'change_password_form' => array(
      'info' => t('Change Password Form')
    )
  );
}

/**
 * Implements hook_block_view().
 */
function change_password_block_view($delta = '') {
  $block = array();
  // Only show the block for a logged-in user.
  if ($delta == 'change_password_form' && user_is_logged_in()) {
    $block['subject'] = t('Change Password');
    $block['content'] = drupal_get_form('change_password_form');
  }
  return $block;
}

/**
 * Password change form.
 */
function change_password_form($form, &$form_state) {
  // Sanity check
  if (user_is_anonymous()) {
    return $form; // Or drupal_access_denied()?
  }

  // Get the currently logged in user object.
  $form['#account'] = $GLOBALS['user'];

  // Textfield cor current password confirmation.
  $form['current_pass'] = array(
    '#type' => 'password',
    '#title' => t('Current password'),
    '#size' => 25,
    '#required' => TRUE
  );

  // Password confirm field.
  $form['account']['pass'] = array(
    '#type' => 'password_confirm',
    '#size' => 25,
    '#title' => t('New Password'),
    '#required' => TRUE
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit')
  );

  return $form;
}

/**
 * Validate handler for change_password_form().
 */
function change_password_form_validate(&$form, &$form_state) {
  // Make sure the password functions are present.
  require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');

  // Make sure the provided current password is valid for this account.
  if (!user_check_password($form_state['values']['current_pass'], $form['#account'])) {
    form_set_error('current_pass', t('The current password you provided is incorrect.'));
  }
}

 /**
 * Submit handler for change_password_form().
 */
function change_password_form_submit(&$form, &$form_state) {
  // Set up the edit array to pass to user_save()
  $edit = array('pass' => $form_state['values']['pass']);

  // Save the account with the new password.
  user_save($form['#account'], $edit);

  // Inform the user.
  drupal_set_message(t('Your password has been changed.'));
}

It's (lightly) tested and works, but you might want to give it a once-over for your own peace of mind.

Update I've chucked it up as a sandbox project in case anyone's interested.


Which image editor can be used within Drupal for creating flowcharts?

Try Image Editor module

  integrates several popular online image editing services into Drupal:

There are integrations with quite a few popular online image editing services.


How is a field's key (rather than value) obtained?

You can change the display in your content type "Manage Display" and ask to have the key and not the label :)
It's here : /admin/structure/types/manage/[your type]/display

Programmatically for a nude value as asked :

$items = field_get_items('node', $node, 'field_list');
$key = $items[0]['value'];


Change the default image based on certain condition

I would suggest using Rules as follows:

You can either include Conditional Rules for a single Rule, or use two rules:

Event: After user registration

Condition: image field is empty (only want it to run if they don't upload an image)

Condition: sex field is girl

Action: set image field to url location of girl default image

New Rule:

same as above except for the condition of sex changes to boy

  The Rules module allows site administrators to define conditionally
  executed actions based on occurring events (known as reactive or ECA
  rules). It's a replacement with more features for the trigger module
  in core and the successor of the Drupal 5 workflow-ng module.


I think that you can use, in respective field settings of your view, the option Rewrite the output of this field. please see this example (in image) with a field title. you must replace [title] with the respective field tag, according the indication in Replacement patterns > Fields.


Where is MODULE_membercheck() getting called from? It would seem that it's getting called on user/login page requests which makes these pages redirect to themselves, hence the infinite loop.

You can either modify the calling of the function to ensure it doesn't get called on the login page or add a check in your function to make sure the current path is NOT user/login before doing the redirect, something like this:

function MODULE_membercheck(){
  global $user;
  if (!$user->uid && current_path() != '/user/login') {
    drupal_goto('user/login', array('query' => array('destination' => 'member/check')));
  }
  // other stuff.
}


I hope this like help you

How to Translate Content type name using i18n module?


How to use Rules to perform a monthtly reset of a field for all users accounts?

You can make a small module for this to write some code using hook_cron().

Inside hook function you can write query to collect all the user ID & update one field value in loop.

Then use Elsia Cron to schedule your made cron function.


How can I override template_preprocess_file_link function?

Yes, seems you need to add:

use Drupal\file\Entity\File;

to the begin of your mytheme.theme file. You can also do something like:

$file_entity = $file instanceof \Drupal\file\Entity\File ? $file :
\Drupal\file\Entity\File::load($file->fid);

And you will have the same problem with Attribute and Url. You need to import the classes with the complet namespace in your file. https://secure.php.net/manual/en/language.namespaces.importing.php


How to access phone contacts from PhoneGap in DrupalGap?

Here's the approach I would take:

1 - Build a custom DrupalGap module.

2 - Implement hook_install() in the module:

/**
 * Implements hook_install().
 */
function my_module_install() {
  sync_contacts_get_contacts();
}

3 - Create a Custom Service Resource Endpoint

4 - In your onSuccess function is where you would send the contacts JSON data up to your Drupal resource.

What (and how) you store the data in Drupal is up to you and your custom Drupal module(s).


Your 2nd approach may be more trouble than it's worth, unless this is a learning exercise. As far as other options go, can't think of any, you may have to just recreate your displays.


Good method/approach in improving advanced Drupal development skills

I have found the Drupal Examples module to be a great starting point for learning enough to develop my own modules, or to aid in solving a particularly thorny problem I'm having.

There's also the Devel and Dev Themer modules, which help to illuminate some of what's going on behind the scenes.

Then there is the API documentation, which I personally have a harder time understanding until I read some of the comments.

These are the ones I use most; others will probably chime in with others, which I know about but lack enough experience in to form a helpful opinion.


Better code to output a pdf downloaded by the browser

Provide a controller to download the PDF as discussed in the comments:
https://stefvanlooveren.me/blog/serve-pdf-download-controller-drupal-8

<?php
namespace Drupal\MYMODULE\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

/**
 * Class PdfGeneratorController.
 */
class PdfGeneratorController extends ControllerBase {

  public function Render($uuid) {

    // In my case, I render a file by UUID
    // This actually does not matter too much here
    // String below contains the url of the file
    $uri = 'private://'.$uuid.'.pdf';

    $headers = array(
      'Content-Type'     => 'application/pdf',
      'Content-Disposition' => 'attachment;filename="download"');

    return new BinaryFileResponse($uri, 200, $headers, true);
  }
}

Then add to the button link the HTML5 Download Attribute to download the file in the background without redirecting.
See https://stackoverflow.com/questions/20830309/download-file-using-an-ajax-request
If the PDF file is created dynamically this can be integrated in a Drupal Ajax form workflow by generating the file on user request and providing the button link to the custom built PDF file via Ajax.


The Serial module will be helpful for you.

  This module provides an auto-increment (serial) field.

  Unlike Drupal's built-in auto-increment node ID, which is global and shared by nodes belonging to all content types, serial fields are managed per content type (D6)/entity (D7). For example, the serial field of an Invoice instance will generate a unique sequential number (starting at 1, then 2, etc.) exclusively for Invoice instances.


How do I know which Drupal 8 modules are supported by Drupal 8 versions?

How do i know which drupal 8 modules are supported by Drupal 8 versions?

You can't.

Specific projects might release alpha/beta versions in sync with core but if that's so and which version requires which version is something you have to figure out for each project separately.

You can try to get guess based on the release date, check if a release came out before or after a beta version. But it might be that an older release still works.

No contrib project that I've seen so far explicitly defines version specific dependencies, and it's actually not really possible, because you don't know yet when you release whether the module is going to be compatible with the next beta or not and when something will break it.

That said, there should be fewer and fewer API changes that break contrib modules from now on.


Is it currently possible to install Drush locally on a Windows 10 PC?

You can install Drush on Windows using composer - http://docs.drush.org/en/7.x/install/

You can get composer from - https://getcomposer.org/doc/00-intro.md#installation-windows

In theory you can manage a remote site with Drush, but you have to have ssh access to the remote server. If you have ssh access, you are better off just logging in and running it on the server. If you have multiple sites across multiple servers, then setting up site aliases in Drush makes more sense.


How to attach a css style with a node in the node-edit form

take a look at css_injector, it allows to add css only on specific pages, like 'node/add'.


Can invite module work for existing users?

The Invite module serves to invite those who are not yet existing users to become ones. That's why you cannot use it to invite existing users.

Anyway, when using UR, at existing user's public profile, there's a Become USERNAME's friend link which you can use to befriend an existing user. This is an equivalent of the Facebook Add Friend button.

With the UR's user_relationship_invites module enabled, you can give users the option of specifying a relationship when inviting new users, e.g. friend. Together with the Contact Importer this would be an equivalent of the Facebook Find friends page.


How to resize an uploaded image based on the longest side?

To follow up on this question; ImageCache Actions now offers a feature called Aspect Switcher which allows for different image styles based on the original images aspect ratio, if it's portrait or landscape.