You can run the follow SQL command on the databases of the sites:

SELECT * FROM `views_display` WHERE `display_plugin` = 'feed'

Maybe you can use a script to loop through all the databases and get those with results


What you need is the #ajax property of the Form API. Have a look at this page to find the answer to your question:

https://www.drupal.org/node/1256510


1 parent nodetype with 2 subnodetypes - show all subnodes in a viewlist

You will have to use Relationships to pull in data from your other nodes. When you have defined your relations then you will be able to use these in each fields setting:

Relationships:
field_1a
field_1b

Fields:
// Uses no relation
// Will display title from content-type 1
Content: Title
// Relation field_1a
// Will display title from content-type 1a
Content: Title
// Relation field_1b
// Will display title from content-type 1b
Content: Title


Do translated taxonomy terms have different tid's?

No if you choose to localize your terms. Edit your vocabulary and tick this option: "Localize. Terms are common for all languages, but their name and description may be localized."


This in untested code so you will need to adjust the paths to get the correct values however it shows the general approach to take:

$uids = db_query("SELECT uid FROM user WHERE status=1")->fetchCol();

foreach($uids as $uid) {
    $account = user_load($uid);
    $profile2 = profile2_load_by_user($account, 'profile_2_type_name_here');
    $profile2['maiden_name']->field_maiden_name[LANGUAGE_NONE][0]['value'] = $account->field_maiden_name[LANGUAGE_NONE][0]['value'];
    profile2_save($profile2);
}


Cannot do a `composer install` even though my minimum stability is listed as dev

This may be incorrect per information in comments and because it contradicts Installing an alpha dev version with composer.

I think the issue here is that the beta6 is not ^1.0. If you updated the requirement to be "drupal/focal_point": "^1.0@beta", this would work fine.

Alternatively, you could call composer require drupal/focal_point with no version specified and it would install the beta6 version just fine. I believe this is where minimum stability is checked, but that would add a  require line in your composer.json different from what is specified in your question.


Voting API + Fivestar Voting - Restricting votes to user and not to IP

This is the default behavior.

Votingapi will limit to IP address when a user is anonymous. If the user is logged in the voting will be restricted by the User ID not ip address.

What version of votingapi are you using? If you're having a problem where this isn't the behavior a bug report might be more helpful.


You will have to add

error_reporting(E_ALL ^ E_NOTICE);

to the settings.php file. Here's more.


How to add mulitple legends in chart created with the Forena reports module?

Any attribute supported as PHP SVGGraph options may be included as frx attributes also. Checkout the PHP SVGGraph library documentation to fully understand the available options, and identify the actual SVG Graph option you should be using (there are plenty of them).

In your case, I think you're looking for SVG Graph legends. In your Forena FRX file, you should be able to specify the desired legends (say 1st Legend, 2nd Legend and 3rd Legend) within the SVG tag of your chart with something similar to this example:

  <svg frx:renderer="FrxSVGGraph"
    frx:legend_entries_1="1st Legend"
    frx:legend_entries_2="2nd Legend"
    frx:legend_entries_3="3rd Legend"
    ...
  />

For many more details about how to create charts with Forena, refer to the reports/help.renderers#frxsvggraph in your own site (which is part of what comes with Forena), or refer to the online equivalent of it.

Note: if you only have 1 legend (say MyLegend), the SVG tag of your chart should be similar to this example (no need for the suffixes like _1, etc):

  <svg frx:renderer="FrxSVGGraph"
    frx:legend_entries="MyLegend"
    ...
  />


How to use token [comment:original:url:absolute]

[comment:original] only exists when a comment is being updated - without context, it will always be empty. And if you had the context to pass it in this case, you wouldn't need to use the token service in the first place, you could just use what you already had to get the URL.

You probably want to use;

[comment:url:absolute]


Get list of available options in a select field of custom content type

$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'slide');
$definition = $definitions['field_category'];
$settings = $definition->getSettings();
$allowed_values = $settings['allowed_values'];


Views partial Contextual Filter on username

You can achieve it by many way...make a relation with content:author and you will get all available options under user like (User: Name, User: First Name,User: last Name,User: Authentication name, User: Authmap ID, ) under contextual filter.


Loading a library only for the front page

function mytheme_preprocess_page(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'view.frontpage.page_1') {
        $variables['#attached']['library'][] = 'mytheme/cuddly-slider';
    }
}


Commerce create order when registering a new account

Perhaps the question is unclear but really I need to know what steps to include in the rules to be able to extract the user details, and add these to the created order, and then invoice the user.


If I'm clear, you don't actually want to remove any of the press offices because existing press releases should still be able to reference them, you just want to remove the option to associate new press releases with certain press offices (while at the same time, creating some new press offices that can be referenced).

So really, we just want to filter the list of press offices that can be referenced by new press releases.

I would suggest that you add a new boolean field to the press offices, something like: "Can be referenced". Then create a view that filters press offices on that field. Finally, configure your Entity Reference field Mode to use "Views: Filter by an entity reference view" and select the view you just created.


programmatically exclude new fields from render()

A common way is to use hide() function in a preprocess hook as:

hide($page['field_machine_name']);


Call to undefined function variable_get()

It seems you are confusing Drush 8 and 9 - Drush 8 has vget and vset.

Using Drush 8, the following two commands worked:

drush vget "mail_system"

drush ev 'print_r(variable_get("mail_system"));'

PS! Drush 7 isn't supported and you should use Drush 8 (currently 8.1.17) for Drupal 7.


Notification email on Content creation - admin approval?

You should try the Rules modules, it can does exactly what you want.

  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 this can be done via Rules and the Commerce Coupon Module. But you may need to write custom Rules condition and event. But first, from your question it is not clear that the form of email and price that you are saying is line items? I am assuming that those are line items and displayed in the Product display. So in that case in a custom module,

We will use the action "When an order is first paid in full" and create a new custom condition to check if the line items are set or not for the payment made. This can be done via creating a new file as "custom_module.rules.inc". In that file create a new hook as hook_rules_condition_info()

/**
 * Implements hook_rules_condition_info()
 * @return array $conditions
 */
function custom_module_rules_condition_info() {
  $conditions = array();
  $conditions['agree_to_mail_coupon'] = array(
    'label' => t('Check if user paid for Coupon Code'),
    'group' => t('Coupon'),
  );

  return $conditions;
}

function agree_to_mail_coupon() {
  //This conditions only return TRUE or FALSE.
  if(your line item check condition) { // Add logic to check for the line items. you will get API from api.drupalcommerce.org
    return TRUE;
  } else {
    return FALSE;
  }
}

Then create a new Event to send the mail. But you need a function to create the coupon code. So via commerce_coupon.module API list you will get commerce_coupon_create or other functions to use. So to create a custom event that will get the email address and the coupon code and send the mail you need the following,

/**
 * Implements hook_rules_action_info()
 * @return array $actions
 */
function armory_commerce_commission_rules_action_info() {
  $actions = array();
  $actions['send_coupon_code'] = array(
    'label' => t('Send Coupon code'),
    //Add your parameters in the parameter array. Given are some demo below
    'parameter' => array(
      'commerce_line_item' => array(
        'type' => 'commerce_line_item',
        'label' => t('Line item'),
      ),
      'component_name' => array(
        'type' => 'text',
        'label' => t('Price component type'),
        'description' => t('Price components track changes to prices made during the price calculation process, and they are carried over from the unit price to the total price of a line item. When an order total is calculated, it combines all the components of every line item on the order. When the unit price is altered by this action, the selected type of price component will be added to its data array and reflected in the order total display when it is formatted with components showing. Defaults to base price, which displays as the order Subtotal.'),
        'options list' => 'commerce_line_item_price_component_options_list',
        'default value' => 'base_price',
      ),
      'round_mode' => array(
        'type' => 'integer',
        'label' => t('Price rounding mode'),
        'description' => t('Round the resulting price amount after performing this operation.'),
        'options list' => 'commerce_round_mode_options_list',
        'default value' => COMMERCE_ROUND_HALF_UP,
      ),
    ),
    'group' => t('Coupon Discount'),
  );

  return $actions;
}
function send_coupon_code($line_item, $component_name, $round_mode) {
     //Add your coupon generation code
     //Use Drupal_mail to send email to the user
}

I haven't tested this one as it's a unique type of requirement. But this will be a basic logic to solve the issue. You may need to do a fair bit of R&D to get it working. I appreciate if you ask if you found some questions & queries.


Translate custom field in countries module

Consider using the Entity Translation module to get this to work.

In doing so, if you run into an error like "The entities of type Country do not define a valid base path: it will not be possible to translate them.", then review the issue about "Countries is not integrating properly with Entity Translation" (status = needs review).


You should be able to change the more variable in template_preprocess_views_view, like:

function YOUR_THEME_preprocess_views_view(&$variables) {
  $variables['more'] = \Drupal\Core\Render\Markup::create('HHH');
}


Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->cacheGet()

This is related mostly to the issue in your code or bug in the module which you're using.

Basically you should validate your DrupalEntityControllerInterface implementation, and you should not patch your Drupal core as suggested by @vgoradiya since it's not a bug in Drupal core.

  Consensus seems to be that issues arise with bad data and should be corrected at the offending module level, not by adding a safeguard to DrupalDefaultEntityController that would mask deeper problems. Having an error here is a warning to developers that they are using the D7 APIs incorrectly. - @jessebeach

So the challenge should be to identify which module implements Entity API incorrectly.

See also:

array_flip() [function.array-flip] issue in DrupalDefaultEntityController / entity.inc which is not a bug, but closed as 'works as designed',
Entity API Tutorial,
How to create a new entity type
Entity API at Drupal Groups
Creating your own entities with Entity API

If you're developer of the module which causing the issue, please check the followings:

Make sure your array won't contain NULL values, otherwise use the following trick:

$arr = drupal_map_assoc($arr, function($v) { return (string) $v; });

Check the Examples module (entity_example) for Developers how to implement entities.
You're loading entities using the right $ids structure.
Use debugger or debug_backtrace() to debug the issue.


How do I get the referring entity of a referenced node in a template file?

You can get the "relationships" to your referencing node in a preprocess function, in your theme's mytheme.theme file:

function mytheme_preprocess_node(&$variables) {
  if (!empty($variables['node'])) {
    $node = $variables['node'];
    if ($node->getType() === 'article') {

      // Get the review by article node id.
      $review = \Drupal::entityQuery('node')
        ->condition('type', 'review')
        ->condition('field_article', $node->id())
        ->execute();

      // Get release by review node id.
      $release = \Drupal::entityQuery('node')
        ->condition('type', 'release')
        ->condition('field_review', array_pop($review))
        ->execute();

      // Load release node and store in variables.
      $variables['release'] = Node::load(array_values($release)[0]);
    }
  }
}

Then you can access the fields in your template:

{{ release.field_name.value }}


Putting items in multiple places in a menu

You can use the Multiple Node Menu module.


Can I skip or bypass translation when creating a form #options elements?

Using t() is considered a good practice, but it is in no way required by Form API.

Your code should work all right. Be sure your code files are properly saved as UTF-8 and transferred using "binary" mode, to prevent misinterpretation of non-ASCII characters.


Get the node count by its node type and node status in Drupal 8

This function will give you the count of the node by its status and content type.

Example: if nodeCountState(1,'article');

the count of number of nodes in the article content type which is published will be displayed.

 public function nodeCountState($status, $type) {
    $query = \Drupal::entityQuery('node')
            ->condition('status', $status)
            ->condition('type', $type);
    $result = $query->count()->execute();
    return $result;
  }

Hope this help some one :)


Drupal 7: use Form API to make a button that doesn't submit the whole page

Just try to use "submit" as the type and specify a custom "#submit". From the ajax_example module:

$form['add_name'] = array(
  '#type' => 'submit',
  '#value' => t('Add one more'),
  '#submit' => array('ajax_example_add_more_add_one'),
  '#ajax' => array(
    'callback' => 'ajax_example_add_more_callback',
    'wrapper' => 'names-fieldset-wrapper',
  ),
);

This does not submit the form with the default submit handler but with your own. In this case it is "ajax_example_add_more_add_one".

Hope it helps, j


I have faced a similar problem in the recent past and found two solutions for the same.

Short solution

Install Me alias module, and then replace your uid with me, and the module will replace me with the uid of respective user.

Long solution

Install Menu token module and use token to replace the path of the menu. Go to edit menu and in the path, do the following


list users informations who flagged an entityform with views

You're on a good track with creating the Entityform type of View. When you first created this View you chose which Entityform this is about, you can see it (change it) under Filter criteria. This view is now listing all submissions for that form.

You have also setup a Flag "Take" that users can use on Submissions of that form. And you want to show a list of all users who flagged a submission, on the submissions page.

When you create a fresh Entityform view you'll have only the field "Entityform: Entityform ID" and the Filter "Entityform: Entityform Type".

If you create a Page in that view you can list all the flags for all submissions for that Entityform. You can maybe use this page as a test, to see the user info correctly listed on submission, and delete it later.

You'll have to create a Block display to be added to submissions pages, this is what you're after.

Here is what you have to do to your Entityform view to show info about users who flagged a submission:

Add Relationship Flags: flag_take (or however your flag is called). Configure that Relationship to show Any user, and not Current user. This will list flags from all users who flagged it, not only the flags from the user currently looking at the page.
Add a new Relationship Flags: User that uses the previous Relationship flag. This introduces info about users who flagged the submission with "take" to be available in this Views.
To actually display the user info Add a new Field User: Name and set it to use the Relationship Flag user. This will show the name of the user who flagged the submission. To show other user info add different user fields and make them use the Relationship Flag user (otherwise you'll show info for the user who submitted the form, and not the one who flagged the submission).
Add a new Contextual filter Entityform: Entityform ID and configure it so that

When the filter value is NOT available:
Provide default value
Type: Raw value from URL
Path component: 2

When the filter value IS available or a default is provided:
Specify validation criteria
** - Basic validation - **
Hide view (or whatever makes sense to you)

And set that Contextual filter to This block (override) because it doesn't make sense to have it on a page display, for example.
Save the view and place the block in a region you want, you can specify the path where to show the block, like you mention in your question, this is good for performance. The Contextual filter that will make sure to only list results relevant to the particular entityform submission.

If you need to check the Block while working on it in Views enter an ID number of one submission that got flagged, to preview the result.


Loading term references into a custom module

If the field is hidden and doesn't do anything client-side, you shouldn't touch it client-side. Do the Category -> Group translation server-side even if you're not very comfortable with it yet.

hook_node_presave should do the trick.


Where do i start when trying to get webservice API's integrated?

There is a very active group of developers working with the Services module. I am sure that another seasoned PHP developer would be welcomed by them.


Configure CKEditor - WYSIWYG HTML editor

You can install the CKEditor module for Drupal for that: http://drupal.org/project/ckeditor

You will have to include CKEditor by yourself, which you can download from here

Install the Drupal module and put the ckeditor folder from the second link under sites/all/libraries and that should be it.


drupal course module adding payment object

Here is the solution on the Course issue queue:

https://drupal.org/comment/7477856#comment-7477856


Service API acting strange with Answers module

I've figured it out, basically the answers module was changing the submit form's submit button text value. Doing this would break Service and make it not add any node to the database.
The solution for me was to remove that modification made by answers module by commenting out some lines:

answers.module , line 163
// $form["actions"]["submit"]["#value"] = t("Post your answer");

And everything works fine after saving.


Render paragraph reference field in page.html.twig

but if I add an extra field to the paragraph type, it is not updated.
  I would like to render all fields, even if I add a new field in the
  future.

To answer the question, you just need to loop though the paragraph fields.

{% for item in node.field_intro %}
  {% for paragraph_field in item.entity %}
     {% if 'field_' in paragraph_field %}
       {{ paragraph_field.value }}
     {% endif %}
  {% endfor %}
{% endfor %}


How can I exclude the link for the current page when I have a list of links in Views?

I had a similar problem with displaying node revision links on a node page, views would display the link to the current node being displayed. To fix this I edited the views template file and checked myself whether the link pointed to the current page or not and only displayed a link if it wasn't to the current node.


Showing a message while downloading a file from hook_form_submit

Your workflow lacks one step. What you want it to be, is:

Send user to "Your download should start shortly" page. On that page, place a script that will execute file download in new window after some arguably small timeout, and a target="_blank" link to the file, for cases when auto-downloading is disabled client side for security reasons.
When the script executes successfully and starts to download file for user, or when user clicks the link to direct download, use JS to send him to "thank you" page. Of course if JS fails, it might not get executed, so be sure all courtesy you really need is also displayed on the page mentioned in point one.


WSOD afte uninstalling the Memcache module and deleting it's folder

One of the steps to install Memcache module is to add a line in your settings.php file that specifies a module file as a cache backend.

To uninstall the Memcache module, you will also need to remove that line in settings.php.  Until then, Drupal will be attempting to load a cache backend from a file that is no longer there.


All taxonomy term paths default to the www.example.com root directory

If you have pathauto module installed, you might want to check the taxonomies aliases go to "/admin/config/search/path/patterns" and look for the old Vocabularies and see how the path is setup. moreover you might want to delete all aliases and do a bulk update for theme "/admin/config/search/path/delete_bulk" then "/admin/config/search/path/update_bulk".


/sites/default/files images not showing up

I appreciate that this is an old post but after days of trying to resolve the problem I have seen many of these posts and want to update with my solution.

My web host is classed as a shared web host which means for me that I don't have as much access to the server side as with other hosts. The control area for the admin on my host is custom and lots of stuff that I have with another host and previous hosts id missing.

I resolved the images not showing by adjusting the .htaccess file. There are 2 that I have found so far in Drupal 7.24 (one in the site root and one in sites/default/files/) and I had to adjust both of them by commenting out the options section and the symlinks section. There is info on this by googling "one.com Drupal Installation".

Once both htaccess files had been edited and the permissions had been changed on the "files" folder in "sites/default/" to "755" the extra folders where created when I uploaded my images and the images started to show fine. If like me you are unable to change permissions within your website hosts control panel you will need to do it with either an ftp client or via ssh.


Ajax in textfield adding extra div in markup

I have checked ajax.js in Drupal site and I have found that extra div is added as ajax wraps new content inside an empty div after a successful ajax request.

Comment Mentioned in ajax.js:

  We don't know what response.data contains: it might be a string of
  text without HTML, so don't rely on jQuery correctly iterpreting
  $(response.data) as new HTML rather than a CSS selector. Also, if
  response.data contains top-level text nodes, they get lost with either
  $(response.data) or $('

').replaceWith(response.data).

Code:

var new_content_wrapped = $('

').html(response.data);
var new_content = new_content_wrapped.contents();

Check this also.


How to scedule a reminder mail for nodes with date field in an oganic group?

When it comes to right on schedule or specific time, you need to have crontab on server. Role of cron tab will be none other than calling your cron.php file which in turn allows all modules to set the cron. But this is half of the process since with core drupal cron process you can not have much control on setting schedule time, so you can use elysia cron module to extend drupal core cron.This was cron part

Now inorder to trigger email you can implement hook_cronapi() as an example,

function mymodule_cron_cronapi($op, $job = NULL) {

  $items['send_email'] = array(
    'description' => 'Send email to group users',
    'rule' => '0 * * * *', // Every Hour at **:00
    'callback' => 'mymodule_email_group_callback',
  );
  return $items;
}

cron callback

function mymodule_email_group_callback() {
  // load all group content from that content type.
  // loop through all nodes check date
  // if true
  // get all subscribers and loop through them
  // send email
}


It's probably not possible to attach an empty fragment. See this code in  UrlGenerator::generateFromRoute():

if (isset($options['fragment'])) {
  if (($fragment = trim($options['fragment'])) != '') {
    $fragment = '#' . $fragment;
  }
}

If the fragment is empty it is ignored and no '#' shows up. This doesn't change if you provide the fragment in Url::fromUserInput(), because the fragment is transfered to the options and later processed by the same or similar code.

So you have to provide an anchor in the fragment:

$url = Url::fromUserInput('#anchor1');

or

$url = Url::fromRoute('<current>', [], ['fragment' => 'anchor2']);

As alternative option you can place a link with an empty fragment

{{ examplevariable }}

either in a twig template or in an inline template in php.


You should group your view by Taxonomy and for the taxonomy field in the view you should uncheck "Display all values in the same row".

These are the steps:

Add a taxonomy field to your view and uncheck "Display all values in the same row" and exclude this field from display.

Use the taxonomy field to group your view (Format settings of the view)

Of course add title field or other field to your view to have your content displayed (e. g. Company 1, 2, 3).


Can both my flag as well as unflag text have different background images?

You can use a preprocess function to override the output as a span with classes.

function MYMODULE_preprocess_flag(&$variables) {
  $flag = &$variables['flag'];
  $action = $variables['action'];
  if ($flag->name == 'drupal_like') {
    if ($action == 'flag') {
      $variables['link_text'] = '';
    }
    else{
      $variables['link_text'] = '';
    }
  }
}

Then you can target these classes to write your css as David mentioned.

.flag-heart-dark{
  background: transparent url('images/flag.png') no-repeat;
}

.flag-heart-light{
  background: transparent url('images/unflag.png') no-repeat;
}


How to fetch HTML created via a Forena report and store it as a node?

You can have a look to the module "Feeds". It's aim is to provide a way to import content (node, term...) from CSV File, XML...

You can also specify interval between two importation. So you won't need rules.


Replace frontpage to a page with wildcards

Make the term context of your page optional using ! rather than %, then set up your views so the default argument (when no term is supplied) is the one you want.

Your page should then work with no argument, ie. at path "myCustomPage". When all OK, you can assign that path as the front page for your site.


How can I override the menu toggle on AdaptiveTheme?

Oddly enough I haven't really seen this issue addressed anywhere else.  I found that the most straightforward solution is to put this in your theme's template.php and then style the span tag:

function your_theme_preprocess_block(&$variables) {
  if ($variables['block_html_id'] == "block-system-main-menu") {
   $variables['title'] = "";
  }
}

Cheers


Is there a site as good as Smashing Magazine geared towards drupal rather than wordpress?

Well I have been trying to make such a website www.techiestuffs.com, but since I haven't found authors to write drupal based content I have scattered the site with categories I am comfortable with. If I find authors I will work with them.


How can I create a table view of entities showing their related entities in the same row?

I don't see a way of creating with vanilla Views, that without changing the templates.

Starting from the Author Views is the worse path to take. You can use reverse Relationships to show nodes that reference a particular Author, but they will be in separate rows, reverse Relationship doesn't support Multivalue options that you get when directly displaying an ER field.

The best path seems to be to create Content Views that lists all  "Novel", "Drama", and "Short Story" nodes. Add the Title Field, Author ER, and the CT (type).
(I don't know if there is some magical Agreggate trick that could work to your solution, the usual ones I've used aren't sufficient for something like this.)
Hide the Author field with Exclude from display and then under Format Settings select the Author field as the Grouping field.
This will still give you each book in its own row, but they will be grouped by their authors. With some template changes you can change the grouping to appear within the table so it appears more like you'd like, with the Author as a column that spreads multiple rows (their work) and all results can be displayed within one table where each author info is within separate tbody elements.
With some more templates adjusted I think you could get to construct exactly the table you want where work nodes of the same type are printed out in the same cell, and types come out as columns, but it wouldn't be trivial.

You might also try the Views Field View module. This is usually used to embed Views within Views (that are related through a field such as an ER field) but it can be very heavy on the performance!
I also haven't tried it under the reverse condition, assuming you start from the author and then get to the relating nodes through backwards Relationships. But OTTOMH it seems possible, you could list all work in the same table row as the Author, each work would still be in a separate row but you could group them by type though. The types wouldn't display horizontally like in your case, but vertically, still it would be close to what you want to achieve. And you could use templates to replace the output of the "embedded" Views (works) to match it closer to what you had in mind.


Perhaps I'm missing something, but noting that using exactly the text 'Custom Type: Create new content' does not work with user_access, at least not for me.

Instead, use the machine value of the permission. One way to get that is to look at the user permission page, and view the checkbox value for the permission.

For example, instead of this:

if (user_access('Basic page: Edit any content'))

use this

if (user_access('edit any page content'))

To find the definition of the machine name, look in the .module file of the module that defines the permission.


Submenu can be created by selecting Parent link for that menu and ordering can be done by weights.
Try reading this in detail at drupal.org


How can I debug white screen when running install script?

You can edit your settings.php file and add

ini_set("display_error" , 1);


programmatically disable menu based on user taxonomy reference fields

The answer will depend on what your created menu items route to (hook_menu() is for defining new menus so it won't help you here).

Generically, hook_menu_alter() allows you to alter the access callback so that you can override access with your own logic. If the path you're overriding is specific to a special module route (e.g. admin/dashboard), then it would make sense to use this hook.

/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  $items['admin/dashboard']['access callback'] = 'MYMODULE_access';
}

/**
 * Access callback function
 */
function MYMODULE_access() {
  global $user;
  $user_entity = user_load($user->uid);

  // @TODO: Check your user entity's taxonomy field for access and return
  // TRUE | FALSE

  // EXAMPLE: Allow access for USER #123
  // return ($user_entity->uid == 123);
}

If your created menu items link to content nodes then you should look at hook_node_access(). This hook is specifically designed for controlling access to nodes so you'll have access to the node/user object from the hook's arguments.

/**
 * Implements hook_node_access().
 */
function MYMODULE_node_access($node, $op, $account) {
  $user_entity = user_load($account->uid);

  // @TODO: Check your user entity's taxonomy field for access and return
  // NODE_ACCESS_ALLOW | NODE_ACCESS_DENY | NODE_ACCESS_IGNORE
  // depending on your logic
}


Adding user roles without access to permissions


Table with Add row option for external users

I got it. We can use Matrix webform component module(https://www.drupal.org/project/webform_matrix_component) to achieve this.


Cannot edit any content Panes in Panopoly installation, getting JS error

I had a such problem with the module jquery_update when we used a library upper jQuery1.7 . Try use different jQuery versions for User interface and the Admin interface. And do not mix them.


Relationship to content in term view causes duplicate and missing results

You can use aggregation ("Advanced" menu, "Other" section, "Aggregation" feature) to sum your results and have something like:
Term 1 (5) - New comments
Term 2 (3)

Or you can try having distinct enabled ("Advanced" menu, "Other" section, "Query settings" feature) to show just the distinct results.

Hope it helps


You should be able to render the sub paragraph - without any loop, just like every other field - with

{{ content.field_name }}

If you really need the loop for some special markup you can try something like

{% for key, item in content.field_name if key|first != '#' %}
  <div class="some_additional_markup">
    {{ item }}
  </div>
{% endfor %}


How to create a view that display on the same row a field and its translation

I haven't found a way to show translations in the same row as the source, without additional modules that is. Although that would be nice to have.

These modules aren't currently covered by Drupal’s security advisory policy so they might not be a wise choice:

Translation Views
Views entity translation shortcuts
Translate Side by Side

A compromise might be to show your information spread accross two rows instead of one:

Create Views showing Title and Field for the two languages
Sort by ID (this will list translations close to their sources so you'll end up with pairs of English and French nodes that are translations of the same content)
Add another Sort criteria by Language (this way you're sorting inside each pair, so you always get French first, English second, if that's how you prefer it)

So in the end you'd have:

+----+------------+-------------------------+
| ID | Title      | Field                   |
+----+------------+-------------------------+
| 1  | Title_FR_1 | translatable_field_FR_1 |
+----+------------+-------------------------+
| 1  | Title_EN_1 | translatable_field_EN_1 |
+----+------------+-------------------------+
| 2  | Title_FR_2 | translatable_field_FR_2 |
+----+------------+-------------------------+
| 2  | Title_EN_2 | translatable_field_EN_2 |
+----+------------+-------------------------+
| 3  | Title_FR_3 | translatable_field_FR_3 |
+----+------------+-------------------------+
| 3  | Title_EN_3 | translatable_field_EN_3 |
+----+------------+-------------------------+


How to redirect into a specific page variant

Variants on the same Page always have the same URL.  The variant that is shown is determined by the selection criteria.

If the selection criteria for Variant 1 fails, it moves on to Variant 2.

If the selection criteria for Variant 2 also fails, then it will try to show Variant 3.

The only exception to the 'same URL' rule is if you have optional Arguments (that start with ! instead of %) in which case you can have a url of foo and foo/bar handled by the same page.


Are there any modules for Profile2 revisioning/moderation

Two options:

There is a patch for profile revisions here.
There is a Profile 2 Moderation module.

(I will update this answer as I'll be trying out both of these.)


How to show first X items and add and ellipsis [...] if there is more items?

I have not tested this, so consider this an educated guess:

Go to /sites/all/themes/yourtheme/ folder and in template.php add the following code:

function yourtheme_preprocess_views_view_fields($vars){

  if ($vars['view']->name == "view_name" && $vars['view']->current_display == "block_1") {
    if (isset($vars['fields']['field_example'][3]->raw)){
      $vars['fields']['field_example']->content = $vars['fields']['field_example'][0]->raw . ', ' . $vars['fields']['field_example'][1]->raw . ', ' . $vars['fields']['field_example'][2]->raw . '...';
    }
    else {
      $vars['fields']['field_example']->content = $vars['fields']['field_example']->content;
    }
  }

replace yourtheme with the actual name of your theme
replace view_name with the name of your view.
replace block_1 with the machine name of your view.
replace example with the name of your field.


You should have your host point directly to the "web" directory instead of your project root. I've run into this issue on webfaction hosting and my solution (actually my co-worker's) was to have 2 "apps." The first app is not web accessible and this is where my drupal-composer/drupal-project's root is. Then I create a second app that is web accessible, e.g. domain.com and is a symlink to the first apps /web directory. Maybe you can use this same approach.


How to show attribute dropdown in add to cart form in Commerce 2.x

You have somehow disabled the proper widget. Go to the "Order item types" page and click "Manage form display" for your order item type, the widget for the "Purchased entity" field should be "Product variation attributes".

I would love to find out how your system ended up in this state. Was this a fresh install? Did you create a custom order item type? Let us know in the Commerce issue queue.


Why you did double code wrap?
Try to use:

(function($) {
    "use strict";
    $(document).ready(function() {

        /* *********************** */
        /* Mobile only Hamburger menu       */
        /* *********************** */
        $(".masthead .menu").on("click", function() {
            $(this).toggleClass('menu-close');
            $("body").toggleClass('menu-open');
            $(".masthead ul").toggleClass("animated bounceInDown");
            $(".masthead .tap-back").toggle();
       });
              });
})(jq213);


If you have a look through the list of Drupal core functions that call watchdog(), you can get a good idea of the events that get logged.

http://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/calls/watchdog/7


Content profile image (CCK imagefield) instead of default drupal picture

To find out errors in WSOD you can look at you Apache Error Log, in Ubuntu you can execute tail -f /var/log/apache2/error.log and you will see the php error.

It's pretty sure the problem come from $content_profile which doesn't seem to be instanciated and thus don't carry the whole content profile object. You can load it using content_profile_load.


No, not really, and you wouldn't want to do this.

The thing is, Drupal aggregates CSS files into groups to be able to easily load different CSS sets for different 'media' and 'browser' values, as well as for different pages being viewed, without the need to regenerate them.

If you look into $groups variable generated by drupal_group_css() in includes/common.inc, there are 5 keys which different combination of values between each group: type, every_page, media, preprocess and browsers.

This allows for different groups to be loaded on different pages/in different situations without regenerating them (or including not-needed CSS), which would be the case if only one aggregated CSS file would exist.


How can I programmatically insert content via a script or import instead of through the UI?

The most direct answer to your question is Migrate Source XSL module for the D8 Migrate API.

Or hell, dont have Windows/Excel installed do the same with Google Sheets Migrate Plus plugin.

I'm not sure if there is a UI for Migrate yet in D8. But this would be the most flexible solution. If needed you could use the drupal api itself to code simple insertion from a php script to create Nodes from an excel script; but the above migrate plugins should be much for flexible to debug in the long run -- but may require Drush support currently.

Edit

Ask previously, how to create a Node in D8:
Programmatically create nodes


error_get_last() returns NULL after valid error in Drush

Drush sets an error handler via set_error_handler('drush_error_handler');.  This interferes with the operation of error_get_last()`, as php resets the last error when the error handler is called; error_get_last() always returns NULL with an error handler, even if it is the first function called in the handler.

Since there is no way to disable the Drush error handler, this prevents the use of error_get_last() in Drush command files.  For a quick test, you could always temporarily comment out the call to set_error_handler in Drush.


Exposed view in field widget submits node form when filtering

I don't understand exactly whether you're using a form here, but if so, you could give this little module a try, that resolved a similar issue of mine.

http://github.com/Itangalo/Node-creation-block--Drupal-7-

creates blocks for node-forms. If you seperate view from the block (e.g. with Panles) this approach could possibly help you too...


Drupal alias to the last node of one type

What you want is neither an alias, nor a menu. You want a view of nodes, filtered by type and sorted by date, that displays 1 item.


The right hook for this job is hook_field_attach_validate().

(As implemented by the Field Validation module, which may also do what you want.)

hook_entity_update() actually fires after the entity and all fields have already been saved (in the case of nodes, at least).


How can I tell which Feature something belongs to?

You can search in your editor or your repository for your 'block_machine_name'. It must have been referenced in the respective feature.


How do I display the content type's description in a view's header?

Here's what you can do:
First, add then config the contextual filter like this:

Then you update the header like this:

You can update the header status at this step also.
And then here is the result:

One more thing need you to handle:
The exception when the filter value is not in the url.
Can it be your part?


Hook_init() and Hook_exit not triggering in template.php

Unfortunately it's as you suspect - those hooks aren't invoked for themes.

Themes can implement hook_theme(), a variety of process/preprocess hooks, and alter hooks (there may be others but I can't find a reference right now).

For hook_init(), hook_exit(), and most other non-alter hooks you'll need to implement them in a custom module.


Views Exposed filter text search for multiple value field

You will probably want to add a (7th) Text field filtering on the same data as Field 6 and group it with an OR to Field 6. Then, you can use Field 7 in the Global: Combine fields filter and not have it overwrite the use-supplied values in Field 6.


How does one compare a date field with the non-UTC user/system time?

I've developed a method to handle the conversion, thanks to help from another answer to another question.  It requires a patch from Add DateTimePlus::getPhpDateTime() for situations that require a DateTimeInterface to work, however.

  /**
   * Fetches the current time adjusted for comparing to non-UTC date fields.
   *
   * Date field data won't always correspond to UTC. From a user perspective,
   * these dates are assumed to be in the user's timezone.  However, it is
   * currently not possible to store dates in timezones other than UTC. So when
   * comparing these fields to the current time, the timezones won't match
   * because one is the local timezone and the other is in UTC.  We therefore
   * need to adjust the current time to match the incorrect date field timezone.
   *
   * @param Drupal\Core\Datetime\DrupalDateTime $date_time
   *   The date-time object fetched from a Date field (e.g. field_date->date).
   */
  protected static function getCurrentTimeForComparingToDateFieldIncorrectlyStoredInUtc(DrupalDateTime $date_time) {
    $current_time = new DrupalDateTime('now', DATETIME_STORAGE_TIMEZONE);
    $userTimezone = new \DateTimeZone(drupal_get_user_timezone());
    $timezone_offset = $userTimezone->getOffset($date_time->getPhpDateTime());
    $time_interval = \DateInterval::createFromDateString($timezone_offset . ' seconds');
    $current_time->add($time_interval);
    return $current_time;
  }


Anonymous sessions breaking login for Drupal 7

If you are actually trying to override the default behaviour of assigning uid, you need to explain why. In order to access the already determined uid information created by Drupal, use this in template.php or a .tpl.php:

<?php
  global $user;
?>

To see what information is already available in $user, make use of the Devel Module:

  Helper functions for Drupal developers and inquisitive admins. This
  module can print a summary of all database queries for each page
  request at the bottom of each page. The summary includes how many
  times each query was executed on a page (shouldn't run same query
  multiple times), and how long each query took (short is good - use
  cache for complex queries).

specifically, the dpm() function.  This can be added just about anywhere as:

<?
  php global $user;
  dpm($user);
?>

This will present a breakdown of the $user array and all the information it contains.


How to transform the CSV link in the Views Data Export module in a non-image link display?

I agree that this CSV button needs some refinements, similar to what you are describing in your question. And quite a few others seem to think likewise.

To actually solve your issue, consider looking at the module's issue # 2261167, which is about an Option for non-image link display (issue status = needs review). Comment # 26 of that issue contains a patch which adds 2 new settings as shown in this screenprint:

Here are some more details about these 2 new settings:

a checkbox to (if selected) provide the download link as a text link instead of an icon/image link.
a textfield to add a class to the link, so that you can give the link a class like "button" (see picture) to your text link

Do I'd definitely consider this patch.

As an alternative (2nd choice?), you may also want to look at issue # 1379672, which is about Export Button, make it styleable with CSS. It also includes a patch that you may want to consider (eg if the previous one for some reason doesn't fit).


How to programmatically display an image field in Drupal 7 + default value when needed

field_view_field is a correct function to use if you want to display node image (if provided) or default (attached to field settings) if not.

$node = node_load($nid);
print render(field_view_field('node', $node, 'field_image')));


i have developed module ajax_links_api which help you to load any drupal page to a specified div with help of JQuery Ajax.

in your tpl =>

    <?php  l_ajax($title, $path, $target)  ?>

$title: Title.

$path : Drupal path.

$target (optional): ID or CLASS of DIV to be replaced. Default value is .region-content, you can change default value in admin page 'admin/settings/ajax_links_api'

Example :

<?php l_ajax("Load node 1", "node/1", ".region-content") ?>

Hope you can use this for this case


Drupal 7.13 and Services 3.5 XML Payload schema to Update Node?

See updated EDIT above.

RAW PAYLOAD:-

<?xml version="1.0" encoding="UTF-8"?>
<data>
    <name>user</name>
    <title>Change this owner!</title>
    <body>
        <und is_array="true">
               <item>
                <value>Another owner test</value>
            </item>
        </und>
    </body>
</data>


How to add one another library files with different name from the theme name?

Short answer: You cannot.

Looking answer:
The purpose to for the libraries file is too define all the libraries of a module / theme.

The file is recognized because it is has the name of the theme/module it is placed at.

If you want libraries with a different namespace then you will need to search for an alter hook, and define these libraries there (not recommended).


How to Invalidate cache for views by user's location

I resolved it by copy the Core Page Cache Module to my owner module, then disable Page Cache Module.

getCacheId(Request $request)

this function should be return a custom key is reach my goal.


It looks like the Google Analytics Reports module is very close to what you need, except it's currently only for Drupal 6. There is an issue open about porting it to Drupal 7, but it doesn't look very active.


You can use the Search_api_db to avoid Apache Solr. Facets come in many flavors, there's no standard tutorial but some googling will get you started...


How to exclude specific css file from aggregation

Similar to Drupal 7, the setting preprocess key to FALSE will prevent a JS or CSS library from being aggregated.

mylibraryname:
  css:
    theme:
      css/custom-style.css: {preprocess: false}

Same works for JavaScript

cuddly-slider:
  version: 1.x
  js:
    js/cuddly-slider.js: {preprocess: false}
  dependencies:
    - core/jquery
    - core/drupalSettings

As documented on Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module


Most simple way (i.e., without coding) would be to use Panels module, and create a node type view page override for the first content type.  Then use a nodereference field to make the first content type reference a node of the second type.  Lastly, use Panels' context system to generate a new context of that referenced node, and display it in whatever means you want on the overridden node view page.


Procedure to import a site to Acquia Dev Desktop

Dev desktop hides the settings file on local sites, so it's a little difficult to see what the settings actually are.

Looks like you're on windows. Hopefully you can find the directory your local settings are stored in by looking at where they are on my mac:

~/.acquia/DevDesktop/DrupalSettings/

The local settings file name has the pattern:

cld_prod_<site_name>_<dev_test_prod>_default.inc

Don't change this file. But you can see if it's accessing the psr_admin user you set up. By default my settings file shows the user 'drupaluser' with '' (an empty string) for a pw.


How do I add body class on specific content_type who have specific field?

You will need to do a little work in the html preprocess:

/**
 * Implements template_preprocess_html().
 */
function mytheme_preprocess_html(&$variables) {
  $variables['has_image'] = FALSE;
  if ($variables['node_type'] == 'article' && ($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {
    $variables['has_image'] = empty($node->field_image->value) ? FALSE : TRUE;
  }
}

and the html template:

{#
/**
 * @file html.html.twig
 */
#}
<!DOCTYPE html>
<html{{ html_attributes }}>
  <head>
...
  </head>
  <body{{ attributes.addClass(has_image ? ['has-image']) }}>

This will add the class has-image to the body tag of every Article type content node.


The Drupal Ajax call is not affected by event.preventDefault in the above code, as neither the Click() or on('click') Jquery function gets executed on Drupal Ajax call.
Please refer the link below

Jquery gobal ajax events

In the above code the ajaxSend()
 function can be used to stop the Ajax call even before getting started. And use event.preventDefault in the function to stop the Drupal Ajax Call before getting executed.

For Example:

$( document ).ajaxSend(function() {
  event.preventDefault();
//add you code here.
});

Please check if this code will work in the function your calling, i am not sure (may work) or else call this code directly in you attached JS file.


How do I create a workflow that creates multiple nodes?

Here is a solution I came up with.  Create a custom module and in your MODULENAME.module file implement hook_form_alter to add a custom submit handler MODULENAME_add_story

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  // if creating node of type A (article is machine name)
  if($form_id == 'node_article_form') {
    $form['actions']['submit']['#submit'][] = 'MODULENAME_add_story';
  }
}

In the custom submit function create the referenced node and save the reference on the original node

function MODULENAME_add_story($form, $form_state) {

  $article = $form_state->getFormObject()->getEntity();
  $aid = $article->id();
  $uid = $article->getOwnerId();

  // Create node of type B (story is machine name)
  $story = \Drupal\node\Entity\Node::create([
    'type'        => 'story',
    'title'       => 'New auto created story new',
    'uid' => $uid,
    //set other fields
  ]);
  $story->save();

  //set the reference and save
  $article->field_stories[] = ['target_id' => $story->id()];
  $article->save();
}

So when you create node of type article a node of type story is also created and referenced from article.


Add a link into a drupal header and table

Instead of returning returning $result->fetchAll(PDO::FETCH_ASSOC), You need to loop the result and add a link to the array like :

$rows = array();

foreach ($result->fetchAll(PDO::FETCH_ASSOC) as $row) {
  $rows[] = $row + array('link' => l('MyLinkText', 'mylinkhere'));
}

return $rows;


How to add a class attribute to a block?

Have you tried to just set #attributes on the render array returned by our block plugin?

$build['#attributes']['class'][] = 'my-nice-block';

Looking at BlockViewBuilder::preRender(), that should work.


How can I produce a non-blocking process to modify newly created nodes of custom content type?

As an alternative to the cron job, this sounds like the queue system might be better.

The main difference is that in your hook_cron(), you have to execute queries to find data to process. With a queue, you listen to new entities being saved (hook_entity_insert()) and put them in your queue.

Then Drupal will manage the list of tasks (queue items) and will automatically invoke your callback for each of them. It will also handle time management and process the configured amount of queue items until the time you configure on your queue is up.

There are plenty of examples and blog posts to be found, this one seems pretty good: https://www.sitepoint.com/drupal-8-queue-api-powerful-manual-and-cron-queueing/. It seems to be very close to your use case, with a hook_entity_insert() than then does stuff with the new entities. It's pretty complete and does some more advanced things like a form where you can check the pending items and fire them off manually. You can of course skip that if you don't need it.


How to add facebook iframe code directly to block?

Just use "Full HTML" input format and paste the iframe snippet in the source view of the block (e.g click "Source" on rich-text editor toolbar first )


I replaced a pdf file but google searches for the node turn up the old pdf file

Inside your Drupal File System - determined at Admin/Config/Media/File System - there are 3 directories that store files uploaded to your Drupal site. I would recommend navigating to each of these directories to find your (old) .PDF file and deleting it ...

If you want to keep the old PDF, consider renaming it ...


Which method is more efficient, database query or taxonomy term controller?

Do you need to load all of the children? Otherwise, loadChildren() will be performing the same query but also loading the full term -- which is a performance dent. The API on the entity storage won't make much of a difference here, honestly.

Have you looked at https://www.drupal.org/project/taxonomy_term_depth? This would be more performant. It caches the depth level in a new base field. If a term's depth is greater than one, you know it is a child.

I would even borrow the concepts from taxonomy_term_depth to add a new base field that is a boolean which caches if the term has children or not. That way you only need to work with the current term entity.


Creating a Batch with multiple functions

I do one batch operation but with multiple entry.

/**
 * Batch start function.
 */
function mymodule_batch_start() {
  $batch = array(
    'title' => t('Importing Excel data'),
    'operations' => array(
      array('_mymodule_import', array()),
    ),
    'progress_message' => t('Importing Excel data. Operation @current out of @total.'),
    'error_message' => t('Error!'),
    'finished' => 'mymodule_batch_finished',
  );
  // Run batch in background
  batch_set($batch);

Here is the pattern fot the operation:

/**
 * Import operation.
 */

function _mymodule_import(&$context) {

  // Get your import data with some custom function.
  $import_data = _mymodule_get_import_data($context);

  // Get Count of items
  if (empty($context['sandbox']['progress'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['max'] = count($import_data);
    $context['results']['total_count'] = $context['sandbox']['max'];
  }
  // Create Iteration variable
  if (empty($context['sandbox']['iteration'])) {
    $context['sandbox']['iteration'] = 0;
  }

  // Check for the end of cycle
  if ($context['sandbox']['iteration'] < $context['sandbox']['max']) {

    // Count of operation in one butch step
    $limit = 10;
    // Counts completed operations in one butch step
    $counter = 0;
    if ($context['sandbox']['progress'] != 0) {
      $context['sandbox']['iteration'] = $context['sandbox']['iteration'] + $limit;
    }

    // Main loop of all import items
    for ($i = $context['sandbox']['iteration']; $i < $context['sandbox']['max'] && $counter < $limit; $i++) {

      // Do smth custom here with import data item $import_data[$i].
      _mymodule_handle_import_item($import_data[$i]);

      // Update Progress
      $context['sandbox']['progress']++;
      $counter++;
      // Messages
      $context['message'] = t('Item %progress of %count', array(
        '%progress' => $context['sandbox']['progress'],
        '%count' => $context['sandbox']['max'],
      ));
      $context['results']['processed'] = $context['sandbox']['progress'];
    }
  }

  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }
}

P.S. Sometines I need to import data and then remove some old data. You can store some results of 1st operation in $context and then use it in other operation. I can do import in one batch with two operations:

'operations' => array(
  array('_mymodule_import', array()),
  array('_mymodule_remove_data_after_import', array()),
),


views_embed_view use to append new HTML from view

You are on the wrong path.

Install the Views Megarow Module. Then create another view that will list the respective Animals and Plants together. Set the path as well, in this example I will assume a path of

megaitems/%

Note the argument.

Then add a contextual filter of 'Content: Type'. When the filter value is not in the URL, display content of no results found. Verify that it works by typing the content type (animal or plant, ie the machine name of your content) in the preview contextual filters section at the bottom. It should only show the nodes for the specific content type that you type in.

Back to the original view, select the Format as Megarow table. Add a field 'content type', and set its display to hidden. Move this field so that it is the first field in the list. Then add a field Megarow links. In the megarow settings, there is a section 'Links'. Add this:

View|megaitems/[type]

This will now create a link which when you click on it loads your content using AJAX. You might have to adjust your view slightly as you are using aggregation.

Good luck!

I have just created this view with aggregation active and views megarow does not play nice with it. But all is not lost. Install Views Field View also. Then create a new view wherein you embed a field of a view. This field must then use the view of your aggregation and append as an argument that is passes the node type again. Then in you original aggregated view you have a contextual filter by type and you do your aggregation as normal. This aggregated view will then return your aggregation result per content type to the new view, and in the new view you add your megarow field.


Annotate term relationships with data via edit form

Just for reference. I found a solution: I used the field collection module to implement the needed relationships.


I think.. It will help to u.. Use views module and add image fields and rewrite the image fields. Look this image nkana-> database name.


How to refer paths relative to the theme directory?

<?php print drupal_get_path('theme', 'eternal'); ?>

as you've already tried, is the correct way to solve your problem. Notice though that you have to print it out as well, as drupal_get_path will only return the path, not print it for you.

I can't immediately think of any reason why it would not work in your case. Some potential suggestions to try could be

Double-check your spelling of the theme name in the code.
Clear caches.
Try disabling the theme/module and re-enable it.

Failing everything else, you'll need to debug drupal_get_filename() directly.


How to add a field widget for multiple file upload?

Multiupload FileField Widget

This is what you want. It enables the HTML5 standard for uploading multiple files. Use a normal file field but use this widget. Now one can select several files when browsing for files to upload. This works for never web browser but not IE8.


Installing a profile inherited from an existing distribution

Are you adding those dependencies to your .info file mydistro.info?

If not, you should. It looks like the install is getting to line 196 in the standard.install file and then trying to enable all those blocks, but the blocks module was never enabled and it doesn't test for that, which is breaking the install. @VanD

Basically you should add the same modules listed as dependencies in the standard profile, also to mydistro.info and re-run the installation.


Override or extend function of a contributed module

You don't need to override the submit function. Each module or theme can do exactly the same as the custom search module does. Use a form alter hook and add their own submit function to the form array. On submit they are each executed one after another.

mymodule.module

/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'form_id') {
    $form['actions']['submit']['#submit'][] = 'mymodule_search_page_submit';
  }
}

function mymodule_search_page_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
  // set cookie
}


How do I create a link to the author's profile on the node that user created?

Create a custom block with this:

/**
 * Implements hook_block_info().
 */
function mymodule_block_info() {
  $blocks = array();
  $blocks['author'] = array(
    'info' => t('author'),
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function mymodule_block_view($delta='') {
  $block = array();

  switch($delta) {
    case 'author' :
      $block['title'] = NULL;

      ////////////////////////////////////////////
      $link = NULL;
      if (arg(0) == 'node' && is_numeric(arg(1)) {
        $node = arg(1);
        if (!empty($node->uid)) {
          $link = l('view all work', 'user/' $node->uid);
        }
      }
      //////////////////////////////////////////

      $block['content'] = $link;

      break;
  }

  return $block;
}

And set this block to nodes page with context, panels or native drupal blocks page.


get to previous page with destination d6

In your onclick event, add a destination=previous_path along with your redirection url.

ie: yoursitename.com/user?destination=previous_path


I can't fetch anything else than '1' to my PDO query

With drupal_set_message('
test '.print_r($record).'
'); you're putting the return value of print_r into a string, not printing the contents of $record.

You can acccess the value you need with:

$result = $query->fetchAssoc();

// make sure we found something
if (empty($result) || empty($result[0]['review_nid'])) {
  dpm("No result");
}

// load the noad we found
$node = node_load($nid)
dpm($node);


What does "Revision translation affected" indicate?

I found this explanation in code comments:

  If a translation has changes in a certain revision, the translation is
  considered "affected" by that revision, and will be flagged as such
  via the "revision_translation_affected" field.

http://cgit.drupalcode.org/drupal/tree/core/lib/Drupal/Core/Entity/entity.api.php#n102


Ckeditor Stripping all attributes, when re-editing content

You shouldn't really hack the config.js file. You can pass any custom configuration values through the admin:

Go to /admin/config/content/ckeditor.
Click on the "Edit" link next to the profile you are working with.
Expand the "Advanced options" fieldset.
Enter the following code in the "Custom JavaScript configuration":

// Instruct CKEditor to disable the filter. You can also limit this to specific tags.
config.allowedContent = true;
// Allow p, div, li and ul tags to have any attributes attached to them.
config.extraAllowedContent = 'p(*)[*]{*};div(*)[*]{*};li(*)[*]{*};ul(*)[*]{*}';

See docs for CKEDITOR.config.allowedContent and CKEDITOR.config.extraAllowedContent. If you are insterested in having this in every Drupal installation, check out my Drupal 7 installation profile.
The file in question is here.

Hope this helps.


How do I get an image path from field preprocess function

You can do this more simply

$uri = \Drupal\file\Entity\File::load($variables['items'][0]['content']['#item']->getValue()['target_id'])->getFileUri()

Or for a field with multiple items

foreach ($variables['items'] as $delta => $item) {
  $uri = \Drupal\file\Entity\File::load($variables['items'][$delta]['content']['#item']->getValue()['target_id'])->getFileUri()
}

And then apply an image style to get the url

$variables['banner_url'] = ImageStyle::load('image_style_name')->buildUrl($uri);


$user-> removeRole('administrator') doesn't remove role

Ok i found an answer.
The code is proper and it works. The problem was that I got module installed that assigned a role to new created users. I found out that it not only assign role when someone create new user but also when you was updating any of them.
I've patched this bug and i got this hosted on my repo so if anybody needs it.
repo


Unable to install the Cloudinary Integration module

You haven't installed the dependencies.
They're listed on the module page:

Requirements

Libraries
Cloudinary SDK for PHP
Cloudinary API Account

Download each of those as well, then try again.


Create a custom template for a custom URL

You're on the right track. You just need to also create a file named page__mycustomtemplate.tpl.php (place it in your mytheme/templates directory). The starting point for this file should either be the page.tpl.php in your mytheme/templates dir (if there is one), or the one in mysiteroot/modules/system. Simply open one of these and save it as page__mycustomtemplate.tpl.php in your theme's templates dir. Then you can replace <?php print render($page['content']); ?> with your custom text/markup.


Unsetting not really, hide yes : use #title_display and its get accessible to screenreader :

$form['my_field']['#title_display'] = 'invisible';


As of Jan 11, 2017, there are still no Drupal 8 sources available, per Berdir, Mike Ryan, and others.

To follow along at home, see this issue: https://www.drupal.org/node/2607524


"[warning] Invalid argument supplied for foreach() Migration.php:641"

Usually this comes from having incorrectly coded a hard value in your migration yml script. As noted in the following example:
process:
  type:
    plugin: default_value
    default_value: 'profile'
  status: 1
  uid:
    -
      plugin: skip_on_value
      source: user_id
      method: row
      value: 1
    -
      plugin: migration_lookup
      no_stub: true
      migration: tabs_users
      source: user_id

  is_default: '1'
  created: created
  changed: user_lastvisit

Here I show a few different approaches, but one is wrong. Specifically, the status: line is trying to set a value of 1 but the migrate module is assuming it is a variable and since it is not set previously in the source section of the yml script, drupal is barfing. To fix this, do what is done in either the type line OR the is_default line; explicitly set the value via the default_value plugin OR encapsulate your value in quotes. This is identified in the documentation but can be easily overlooked when quickly coding up a solution.


Can I host Drupal alongwith Google App Engine?

Google App Engine now supports PHP, yes you can.
But Drupal technically is supposed to run on an Apache server (.htaccess rewrites, restrictions and options) with normal email servers that can be handled using normal PHP's mail(), and PDO, you will need to take care of providing alternatives for the services.

Mainly, GAE has limitations in emails, SQL, and writable file system.
Here is a link to a post that helped me a lot: http://blog.boombatower.com/drupal-google-app-engine


Go to the edit screen for your view. At the top right, just under Displays you will see a button labelled Edit view/name/description (right under the Save and Cancel buttons). This is a drop down. Click on it and choose export view.

The second item in the export is the machinr name of the view:

$view = new view();
$view->name = 'your_view_name';
$view->description = ...


When you have multilingual content not in the Original language

How to create content in a secondary language:

Go to the language settings of a content type and change it from "Site's default language (English)" to a secondary language or enable

  [x] Show language selector on create and edit pages

so that the editor can select a different language for each piece of content. As long as you don't add a translation to this content it stays monolingual (in the secondary language). You can even restrict a content type to this by disabling:

  [ ] Enable translation


Commerce 2: Is it 'really' necessary to setup product attributes before adding a simple product?

If the products you are adding do not require different variations, there is no need to add attributes. Product attributes are meant to define unique properties of a variation of the same product.

An example would be a t-shirt where the color and the size are two different attributes. The shirt has the same print and model (eg. long sleeves), but any given combination of size and color can exist, each having a different price, photo, etc. and its own SKU.

The documentation lists the creation of attributes before the creation of products, so you can choose these attributes once you start adding products.


Well I finally figured this one out.  Hopefully this helps someone else out there:

function mymodule_menu() {
  $items = array();
  $items['admin/mymodule'] = array(
    'title' => 'My Module Form',
    'page callback' => 'mymodule_callback',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function mymodule_callback() {
  $form = drupal_get_form('mymodule_form');
  return $form;
}

function mymodule_form($form_state) {
  $form = array(
    'field1' => array(
      '#type' => 'textfield',
      '#title' => t('Field 1'),
      '#required' => true,
    ),
    'field2' => array(
      '#type' => 'text_format',
      '#title' => 'Filed 2',
      '#default_value' => "",
      '#format' => 'filtered_html',
    ),
  );
  return $form;
}

For whatever reason, having the menu callback not point directly to the form builder function, but instead at an intermediary function that calls drupal_get_form() caused the text_format type to work properly.


How can I list all of the pages that display a certain view?

There is no way to do this through the UI and even to do it programmatically would be a tall order. Views can contain page, block, panel pane, and other types of display. Those displays can be embedded in pages via blocks, panels, or custom code.

If you have a specific view display in mind, e.g. a block, it would narrow the scope of the task, but the task would still be very difficult.


Why do I get Call to undefined function updatedb()

drush updatedb is a valid command.

updatedb (updb)       Apply any database updates required (as with running update.php).

However, I'm not sure about using it in place of db_query.

In D7 you would use db_update there.

In D6, you're stuck with db_query

It looks like a syntax error in the module code, it probably needs to use D6 style db_query


Fatal error: Call to undefined function drupal_array_diff_assoc_recursive()

drupal_array_diff_assoc_recursive() was added in Drupal 7.23, and you have a lower core version than that.

You could try copy/pasting the function somewhere into your current core as a hack, but don't be surprised if it doesn't work.

Or you could try hacking at the Token module to remove its reliance on that function, or install an older version of Token altogether, which doesn't rely on it.

Basically you're in "no warranty" territory; if you update one part of your codebase, but refuse to update the rest of it, you can't expect it to carry on working.

The proper solution is to upgrade your core version ASAP, not just for this, but mostly for https://www.drupal.org/SA-CORE-2014-005.


how to modify drupal 7 mysite/user/login and mysite/user/registration pages "in-place"?

If you want add form fields to either the login or registration form(s) you will have to write custom PHP code in a module file to make any use of the fields.

The forms are just blocks on the page, and should inherit or reuse block.tpl.php pretty much everywhere. Since they are just blocks, sitewide css can target them specifically once you've made them.

The drupal login and registration system is fairly pluggable, you can "inject" your own validation code (to handle your own custom fields) and authentication pretty much however you wish.

A useful tutorial/blog post might be:
http://omegadelta.net/2011/03/23/custom-authentication-with-drupal-7/

It doesn't add custom fields, but does modify the existing drupal login behavior which is what you're trying to do as well.

In your case you probably want to do something like:

create a custom login/registration block in a module, it simply
loads the default login or registration block as an object.
Implement hook_block family of functions.
hook_form_alter() the block and inject your fields and override the default user authentication validator with your own to consume your fields
(similar to the linked blog posts' _geospike_user_login_form_alter()
function).
define a hook_menu path which outputs a page that
loads/outputs your custom defined block to login or register.

Drupal can do what you want with basically a custom module and like a few hook functions. Your not creating your own user login or registration form, and your not writing your login login validators from scratch -- you are just overriding the pre-existing ones for new ones your basically telling drupal exist now via your module.


In what function in template.php are you adding this? A preprocess function I hope.

Anyway, you have to set the 'group' option as outlined on the drupal_add_js page. eg.

drupal_add_js('sites/itascacg.com/themes/custom/icg/js/fixtitles.js',array('type' => 'file', 'weight' => -19, 'group' => JS_LIBRARY));


How to show/hide a block at some content types using PHP filter?

There is another alternative available ... which doesn't require the PHP filter to be enabled (which you should try to avoid whenever possible) ... Just use the Rules block visibility module. Here is a quote from its project page:

  The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.

  The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless.

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

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

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

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

With that, and as per the "if you can do it with Rules, you can use it to control block visibility" above, you've reduced your question to making Rules "check the path of the current page" (so that the block is only shown for the page with an URL like /eshop).

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?".


For Views, the route pattern is view.(view_id).(display_id).

For instance, if I have a view called Articles, and a display that I named "All", it would be:

$form_state->setRedirect('view.articles.all');

If you don't rename your display ids (I usually do), it is probably page_1 or something of that nature.

Beyond that it's similar to how it was before. Here is a redirect with query string args attached:

$form_state->setRedirect('view.articles.all', ['keywords' => $form_state->getValue('keywords')]);


How to alter Core's user login final function

Override login form with hook_form_alter()

You need to replace validation function with your custom function.


"Add to Cart" button/from in template (form ID from Node ID)?

Found a solution!

Add a field of type "Product reference" to the Product content type ("Inline entity form - Multiple values" as widget)
Use "Add to Cart Form" to its display format
Field API in node--product-display.tpl.php:

print render($content['field_info_prodotto']);


Can you render a custom block in a view without adding it to the admin blocks page?

The only purpose of a block plugin is to be placed as a block. It's not an entity. The placed block instance can become an entity of its own but also be part of a layout section.
Since the block is your own custom code you don't need any of the workarounds discussed and linked. It would make more sense to refactor the code and expose it as block plugin to be placed on the page and at the same time as area plugin to be placed in a View.
For sharing the custom code between both plugins you can use classic OOP, or the in Drupal very common traits and services. The service has the advantage that it is more flexible and you can not only share code but also data, for example to cache the result if it is expensive to calculate and used in multiple places.


Why exposed filter doesn't appear, when ajax is off in block view

Simply because it is not a page. If you notice on page view, with ajax off, you will see a parameter passes through the url.

/example?something=yes

If you go to that url directly, it automatically filters your value.

Since blocks are not pages (do not have urls), you cannot do that. Therefore, reloading the block with AJAX is the only option for exposed filters in blocks.


You should not be using document.ready. Instead you should use drupal behaviors. Even though document.ready will work. Behaviors is the drupal 7 way to do things as these behaviors get called after ajax calls too.

css

body {display:none;}

javascript

(function ($) {
    Drupal.behaviors.fadein = {
            attach:function(context, settings){
                    $('body', $context).once().fadeIn(2000);
            }
    };
})(jQuery);

And FYI
Omega adds a 'responsivelayout' event that will get fired every time the layout is set/changed including when the page loads so you could potentially make the page display straight away on mobiles and fade in on others.

(function ($) {
    Drupal.behaviors.fadein = {
            attach:function(context, settings){
                $('body', context).bind('responsivelayout', function(e) {
                    if($('body', context).hasClass('responsive-layout-mobile')){
                            $('body').once().show();
                    }else{
                            $('body').once().fadeIn(2000);
                    }
                });
            }
    };
})(jQuery);

I have not tested the code BTW, but you get the idea


How do I create content importing data from an Excel file?

You need the Feeds module.

Export your excel sheet as CSV with column headings quoting every cell.
Download and install the Feeds module (and optionally Feeds Tamper).
Create a new Feeds importer to consume the CSV.
http://example.com/admin/structure/feeds/create
Set Fetcher (change) to file upload, Parser (change) to CSV parser and Processor to Node processor.
Map (exactly) your column headings in Node processor mapping.

I've used this with great success in Drupal 7 and once in Drupal 6. PS: Upgrade to D7.


Language switcher in a modal window (pop-up)

Got it! All I needed was a little JS to get rid of the query:

$(document).ajaxComplete(function() {
  var $link = $('a.language-link');
  $link.each(function(i,el){
    $(el).attr('href', $(el).attr('href').split('?')[0]);
  });
});


I have figured it out, by just adding a bunch of jquery dependencies in my

  theme.libraries.yml

   js:
      js/leadership.js: {}
   dependencies:
    - core/jquery
    - core/jquery.once
    - core/jquery.ui
    - core/jquery.ui.widget
    - core/jquery.ui.draggable
    - core/jquery.ui.mouse
    - core/jquery.ui.position
    - core/jquery.ui.resizable

once of the jquery ui was missing.


How do I Improve Drupal 7 Forum Performance?

If you remove statistics then things should fly.   From my understanding drupal statistics does not scale well


I would start with D7 if I were you. Taxonomy and CCK are in core in D7 and Views is really stable in my experience, even though there's only a release candidate at the moment.

Do not underestimate upgrading a site from D6 to D7. Yes, it is possible, but you want to save yourself a couple of headaches and start with D7 right away.

Drupal 7 is much more scalable and since you're planning a huge site, you're going to need that.

You write that you will be hosting documents; does that mean that you're storing the document contents in the database, or are you hosting downloadable files like .pdf's and .doc's? D7 is much better for managing files, as is explained in this Acquia blog post.


How to have various 'access denied' pages depending on URL

I think you what you need is: hook_node_access($node, $op, $account)
https://api.drupal.org/api/drupal/modules!node!node.api.php/function/hook_node_access/7

Parameters

$node: Either a node object or the machine name of the content type on which to perform the access check.

$op: The operation to be performed. Possible values:

"create"
"delete"
"update"
"view"
$account: The user object to perform the access check operation on.

Base on the return values, you can redirect them to custom error page.
Example:

function hook_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  if (in_array($type, node_permissions_get_configured_types())) {
   if ($op == 'create' && user_access('create ' . $type . ' content', $account)) {
    $query = drupal_get_destination();
    drupal_goto('node/custom-error-page',$query);
   }
 }


Use Javascript to Incrementally Add a Numer to a Selected Class

I don't think you really need to add the number to the class; the elements that you're targeting also have the .views-row class on them so you can use a bit of contextual jQuery to get the job done in a couple of lines:

$('.views-row').each(function(i,e) {
  $('.content .body', e).insertBefore($('.content .field-name-field-image-one', e));
});

I haven't tested that but I can't think of a reason why it wouldn't work.


How to put a date token at the start of Backup and Migrate file name pattems?

On the Advanced Backup options page below the Backup filename there is a link Replacement patterns which expands to display another link Current date which displays some of the tokens available. None of the existing ones suits my preference which is a numeric date.

Using the PHP date options a good date prefix would be [current-date:custom:Ymd-Gi] or [current-date:custom:Y-m-d-Gi] the latter resulting in a string like '2013-11-17-1924' for 17th November 7:24 pm.

As an example I have a Backup filename token [current-date:custom:Ymd-Gi]_[site:name]-PMU, the PMU meaning Pre Module Update, something to use just before upgrading modules so you can revert the configuration if something goes wrong


Content added in article tags, doubling content, even without article content

As per comments, I found my error:
I was talking about HTML tags. Sorry for not being precise there. I found my error though, which was incredibly stupid. I had given the content an url alias so as to function as a page, which would of course send along the content. I had then added a view as described above, adding the content once again. Silly me. Sorry for the inconvenience.


How do I render the absolute URL of a referenced entity in a simplenews newsletter?

external and absolute are different:

external is an url without internal route. You can't change this property. This is set when you create an url.

absolute is an option, which you can set at any time in the url object:

$url->setAbsolute();

Or set to false:

$url->setAbsolute(FALSE);

And this will change how the url is generated absolute or relative.


linking multiple node types to each other

Okay, I haven't test this out, but I think this should work:

You first need  a way to generate a taxonomy term for each Complaint node. I think that the NAT could help with that or through Rules.
Next, add a term reference field for Solutions, enable multiple selections but disable the ability to create terms.
Override the term reference view for that particular vocabulary through a custom url using Pathauto, this would be the "Complaint1 -> Solution1, Solution2, Solution3" part
For "Solution 1 is linked to Complaint1, Complaint2, Complaint3", you already have links to the taxonomy term simply by displaying the field in your node. You could also do this through views.

Done! Hope it works!


How does Drupal 7 determine the output of user menu?

You need to set menu_name for your menu item to user-menu, see userpoints_menu() for an example (the myuserpoints menu item).


How/where do I add $('#fullpage').fullpage() code?

You need to create a javascript file in your theme and attach it to pages as shown in the documentation.
https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

Make sure you theme library has a dependency on fullPage.


In Drupal 8, timestamps (and created and updated) are stored as integers in the database.  They do not use the native datatype.  Timestamps can be added via the UI, but created and updated can only be used as basefields.

Datetime and daterange fields are stored as ISO strings: date-only as Y-m-d and date+time as the full ISO8601 format (currently without the UTC offset).  These are store as plain strings, not as a native type, since the date/time handling in the default database backends is not portable.

The reason you are seeing different HTML, is that the two field types use different formatters.  Your timestamp is using TimestampFormatter and it looks like your datetime is using DatetimeDefaultFormatter.  It is possible to get both fields to output the same if you use the DatetimePlainFormatterformatter. You can also write your own formatter for timestamps to output HTML5 time.  For various reasons, they formatters between the two types are different.


How to alter the owner/authored by field to the current user when using quick_node_clone

Try this out:

use Drupal\Core\Entity\EntityInterface;
/**
 * Implements hook_entity_presave().
 */
function customModule_entity_presave(EntityInterface $entity) {
  $current_user_id = \Drupal::currentUser()->id();
  $entity->setOwnerId($current_user_id);
}

Edit
You would be better to check on your content type:

use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_entity_presave().
 */
function customModule_entity_presave(EntityInterface $entity) {
  $current_user_id = \Drupal::currentUser()->id();
  if ($entity->bundle() == 'your_content_type_name'){
    $entity->setOwnerId($current_user_id);
  }
}


The field uri has to be unique within the file_managed table. Apparently, in your old database (before updating to utf8mb4) this index was not created or not active and so your table got "corrupt".

Fix this by renaming the uri field of one of the records that refer to public://listings/4232.jpg to e.g. public://listings/4232_0.jpg and copying the image /sites/default/files/listings/4232.jpg to /sites/default/files/listings/4232_0.jpg (assuming that public:// refers to /sites/default/files/).

Note: just deleting one of the duplicate records will result in image/file fields pointing to no longer existing managed files, so better duplicate the file as described above.

If, afterwards, you want to get rid of those duplicate images, you can use my module duplicate images :)


How to use URL query parameter on a View Exposed Filter?

Views Exposed filters already work this way, no need for any Contextual filters.

In the settings for each Exposed filter there is an option to type in Filter identifier. That is the text that will be used for that field in the query.

In your case set the Filter identifier of the Category to Category and of Type field to type.

If you configure the Exposed filter Selection type settings for those two filters to Dropdown then you'll have to use term IDs in the link to make the filter work (I'm assuming your Security term has ID 6):

www.mysite.com/news?Category=6

Use Autocomplete to get term names in query

But if you set the Exposed filter Selection type settings to Autocomplete you will be able to use term names, which is what you want.

www.mysite.com/news?Category=Security

or

www.mysite.com/news?Category=Security+(6)

Drupal 8 adds the term ID next to the term name when choosing from the autocomplete suggestion list, but that part isn't necessary. You can construct the link with Category name only and it will work. If the Category name has spaces in it, replace them with + in query.

If you have more than one Exposed filter they get combined, for all types:

www.mysite.com/news?Category=Chemistry

or

www.mysite.com/news?Category=Chemistry&type=

and for some specific type in addition to Category:

www.mysite.com/news?Category=Chemistry&type=Blog

or change order:

www.mysite.com/news?type=Blog&Category=Chemistry


Views Slideshow, items per slide based on screen resolution

Ive done it using detect_mobile class and some tweaking of views_slideshow_cycle.theme.inc, changing the $styles['items_per_slide'] variable based on the device detected. Don't see much of an interest so I won't share the code but if someone is interested please let me know. Cheers ;)


Negative value for graphicXOffset not being applied

Actually, I've successfully used both negative x and y offsets.

However, since you're trying to raise the graphic (move it up, I'm assuming), you need to be using the y offset.  That's the one that controls the vertical placement.  ;0)


Hide the page titles of some content types

Just wanted to let you know that there is a module that does this Exclude Node Tittle


redirect in hook_init makes body text disappear

Okay, got the answer. hook_init() needs to document what functions are ok/not ok to call

Documention of hook_init() should mention that it's not allowed to call ... node_load() within this hook.
The correct way to redirect is as follow:

MODULE_menu_alter(&$items) {
  $items['node/%node']['page callback'] = 'MODULE_node_page_view';
}

MODULE_node_page_view($node) {
  if ($node->type == MODULE_NODE_TYPE) {
    $referenced_node = MODULE_get_related_node($node);
    drupal_goto('node/'. $referenced_node->nid);
  }
  else {
    return node_page_view($node);
  }
}


Webform Submission & Commerce Order Database Relations

Check out table: field_data_commerce_webform_sid
it contains webform submission ID and entity_id (for commerce_line_item)

Then use table: field_data_commerce_line_items to find the commerce_order id for a specific commerce_line_item ID.


Allowing unlimited values for a field in programmatically defined form

I have set up a module demonstrating how to allow the user to add unlimited values:
https://bitbucket.org/scotteuser/drupal-8-demo-form-unlimited-values

Here is the Form itself:

<?php

namespace Drupal\demo_form_unlimited_values\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Class UnlimitedValuesForm.
 *
 * @package Drupal\demo_form_unlimited_values\Form
 */
class UnlimitedValuesForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'unlimited_values_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    // State that the form needs to allow for a hierarchy (ie, multiple
    // names with our names key).
    $form['#tree'] = TRUE;

    // Initial number of names.
    if (!$form_state->get('num_names')) {
      $form_state->set('num_names', 1);
    }

    // Container for our repeating fields.
    $form['names'] = [
      '#type' => 'container',
    ];

    // Add our names fields.
    for ($x = 0; $x < $form_state->get('num_names'); $x++) {
      $form['names'][$x]['first_name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('First name @num', ['@num' => ($x + 1)]),
      ];

      $form['names'][$x]['last_name'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Last name @num', ['@num' => ($x + 1)]),
      ];
    }

    // Button to add more names.
    $form['addname'] = [
      '#type' => 'submit',
      '#value' => $this->t('Add another name'),
    ];

    // Submit button.
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
    ];

    return $form;
  }

  /**
    * {@inheritdoc}
    */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();

    // Decide what action to take based on which button the user clicked.
    switch ($values['op']) {
      case 'Add another name':
        $this->addNewFields($form, $form_state);
        break;

      default:
        $this->finalSubmit($form, $form_state);
    }
  }

  /**
   * Handle adding new.
   */
  private function addNewFields(array &$form, FormStateInterface $form_state) {

    // Add 1 to the number of names.
    $num_names = $form_state->get('num_names');
    $form_state->set('num_names', ($num_names + 1));

    // Rebuild the form.
    $form_state->setRebuild();
  }

  /**
   * Handle submit.
   */
  private function finalSubmit(array &$form, FormStateInterface $form_state) {
    drupal_set_message($this->t('Do what you want with the final data here'), 'status');
  }

}

The critical bits are:

$form[#tree] tells Drupal that the form is hierarchical.
$form_state->get() and $form_state->set() are used around the counter num_names
Check the 'op' to see which button the user pressed. If they pressed to add another field, use $form_state->set() to increase the count and $form_state->setRebuild(); to tell Drupal that the form should be rebuilt.

Hope that helps you get it working!


How to determine which element has called (triggered) the AJAX callback function?

Got it!!! This guy here $form_state['triggering_element'] does the trick.


Add user note in CiviCRM on behalf membership page

I would do this by using a CiviCRM integrated webform (using the webform CiviCRM integration module) and the CiviCRM contribution page. Use the webform to collect some of the information, including your comments field, and then on submission of that form take the user to the contribution page where they can initiate the transaction. Its less than ideal, but it works.

Work is going on to enable payment processors like Paypal website payments standard to work with webform_civicrm, but it's not ready yet, so I use this approach whilst awaiting that feature to be launched.


Change position of submit button on form

I added the form elements submit buttons onto the node add/edit panel in the correct place, which solved my problem.


I want to filter to show orders that their ending date is today

In order to use webform fields in views filter/sort, you will need to add relationship with them. They should be available for relationship in the format or Webform submissions: Data :XXX.

Once you add them, you can further use them in filter/sort with more conditions. Hope it helps !!


How to use view's relationships to pull user entity reference data?

There is a Relationship that introduces "backwards" Entity reference info into the Views.

In Drupal 7 that is called something like this (you can find this in the list of Relationships in your Content Views under the Entity Reference Category):

  Entity Reference: Referencing entity
  A bridge to the User entity that is referencing Content via field_[myERfield]

After you have that you will be able to add the User: Name field, it will automatically use the above Relationship, and it will show which user referenced that particular node, for your each Views row.

In Drupal 8 the Relationship is called

  User using field_[myERfield]
  Relate each User with a field_[myERfield] set to the content.

The procedure is the same, you can now add Fields or Filters relating to User fields/data, if they're set to use the Relationship the user shown will be the one referencing the content of that Views row.