Calendar widget translate problem on Drupal 7

If you by date widget means the JS popup, then that part is not actually translatable in Drupal. Instead you need to activate a load a language js file for the jQuery plugin which will translate the widget for you. If those translations are wrong, you should file a bug report with the jQuery team.

I searched the data module and couldn't find the text strings that you mention above. Drupal 7 allows modules when creating translatable strings to provide a context. I see that the date module does that several places:

t($date->format('F'), array(), array('context' => 'Long month name', 'langcode' => $langcode));

Doing this will create an extra translatable strings. An example use would be:

t('Order', array('context' => 'the order of items');
t('Order', array('context' => 'an e-commerce order');

The word is the same but the meaning is different, by doing the above it will allow translators to translate the strings differently. If a Drupal module provides the text strings for your widget, they will need to do something similar: fx

 t('T', array('context' => 'Tuesday');
 t('T', array('context' => 'Thursday');

If the module haven't done this, your best bet is to submit a patch for the module and explain why they need to do this. This is generally a good practice to do when you create translatable string that aren't unique.


In the Other section of the views edit form, there is a link "Theme: Information." Inside that link there is a list of the many ways to template the view output. As always when theming, you start by copying the base file (e.g., views-view-unformatted.tpl.php), and make your modifications to the copy. Follow the naming conventions given in the link exactly. It can sometimes be tricky to get the dashes correct. Double-dashes are used to separate sections within the filename but single dashes are used to replace single underscores in content names. For example, for a content type named article_ratings, the template file would be named views-view-unformatted--article-ratings--default.tpl.php.


This question is essentially asking the same thing as this previously answered question:
Programmatically change select field options in contact form

The accepted answer in the other thread describes how to set the select list from php code. You would alter the $options in the function provided to contain your vehicle list from SQL, a yaml file, or wherever.


It sounds like a View of Taxonomy terms would meet your needs.

If I wanted to create a block with a list of items tagged with term in the category "Electronics" then I would do something like this:

Create a View with the following options:

Show Taxonomy Terms
of type Electronics
sorted by [unsorted]

Check the "created a block" box.
Add terms "DVD player", "DSLR camera", and "LCD monitor" to my "Electronics" vocabulary.
Add the relevant terms to the relevant product pages
Enable the block

Now, if I start selling Zunes next month (hah) then I can add term "mp3 player" to the "electronics" vocabulary and it will show up in the list of electronics-related terms in my block.


How to output correctly an html_restricted textarea field in Twig?

The Drupal 8 way would be to use a view mode and let the field formatter do its work.

If you want to do this in custom code you can build the render element for processed text like you did in the question, but use the text format stored in the field:

$user['bio'] = [
  '#type' => 'processed_text',
  '#text' => $data[0]['value'],
  '#format' => $data[0]['format'],
];

Then you are sure, that the text filters are applied configured in the format, that the user who filled in the text field had permission to use.

To output the variable in twig you don't need any filters, they are applied automatically by the render element:

{{ user.bio }}

Edit for the question in the comment, how to render a field without a view mode. There is a way to do this. You can view a field by providing the display options in an array:

$user['bio'] = $journalist->field_bio->view(['label' => 'hidden', 'type' => 'text_default']);

But this is as expensive as rendering the complete entity and is not optimized for caching. So use it only if you can't figure out a way how to render whole entities in view modes.


If you were building the SQL directly, you could do it in the ORDER BY clause with the CASE WHEN syntax where you do something like:

CASE WHEN comment_table.timestamp > node_table.timestamp then comment_table.timestamp else node_table.timestamp

Since there is no default Views core plugin for CASE WHEN sorting, you can either build a Views sort plugin that implements the syntax or use existing plugins that allow custom SQL with a notable security caveat that comes with storing code in your configuration.


Drupal 7 - Give permission to manage users but not permissions

I had the exact same requirement, and I was able to use the Roles Delegation module to build it to perfection :-)

Here is my scenario to give you more context -

I had a drupal site with roles - A, B, C, Admin, Maint
I wanted users with role Maint to be able to create new users and also assign them roles while doing so
I also wanted to limit Maint users to be able to assign only roles A, B, C to the new users and not the role Admin
All of it was just a few clicks with the Roles Delegation module

Hope this helps.


How to apply pager in a table using theme function?

Added  the below lines in above and below theme table script.

     $form['pagerTop'] = array('#theme' => 'pager'); and
     $form['pagerBottom'] = array('#theme' => 'pager');


Disable translation of watchdog messages

I made it like this:

function MYADMINTHEME_dblog_message($variables) {
  $output = '';
  $event = $variables['event'];
  // Check for required properties.
  if (isset($event->message) && isset($event->variables)) {
    // Messages without variables or user specified text.
    if ($event->variables === 'N;') {
      $output = $event->message;
    }
    // Message to translate with injected variables.
    else {
      $output = format_string($event->message, unserialize($event->variables));
    }
    if ($variables['link'] && isset($event->wid)) {
      // Truncate message to 56 chars.
      $output = truncate_utf8(filter_xss($output, array()), 56, TRUE, TRUE);
      $output = l($output, 'admin/reports/event/' . $event->wid, array('html' => TRUE));
    }
  }
  return $output;
}


How to show a variable of node in page template

This question is more or less a duplicate of https://stackoverflow.com/questions/8074485/drupal-7-how-to-render-custom-field. But I'd rather see the answer and question here on Drupal.stackexchange.com.

This goes into your template.php or in a module included file.

function THEME_OR_MODULE_preprocess_page(&$vars) {
  $vars['VAR_NAME'] = '';
  // Get the object and do some other checks based on what you need.
  if (($node = menu_get_object()) && $node->type) {
    // Generate a render array for the node.
    $view = node_view($node);
    // "Create" a new variable for the page.tpl.php.
    // This will expose $VAR_NAME in the page template.
    // You will most likely have to clear your cache.
    $vars['VAR_NAME'] = drupal_render($view['FIELD_NAME']);
  }
}

And then in your page.tpl.php:

HTML
<?php print $VAR_NAME; ?>
HTML

You might also have to hide the field in your node template, if you don't want to print the field twice. Check at hide() for that.


How to edit order summary field labels on paypal page

The Paypal WPS API can be used to hold multiple individual items, but it can also just be used to handle a single order. It effectively does this by making the Drupal order the only product on the PayPal order.

If you are wanting to customize checkout further, you'll need to find another processor that gives you that ability. PayPal PayFlow Pro or some other option might work.


Views boolean column if user has a specific role

I don't see an out of the box method. Maybe someone else will have a better answer. But what I did for a quick solutions is to add the Views PHP module, then add a PHP field with the following output code:

<?php

  $account = user_load($data->uid);

  $roles = array('YOURROLE', 'ANOTHER ROLE');

  if (count(array_intersect($roles, $account->roles))) {
    print 'Yes';
  }
  else {
    print  'No';
  }

?>

It will print yes if any user has either of the two roles.


Load Aegir's site credentials from a php function

Installing sites in sub-directories is supported in Aegir 2+ without any such hacking. Just enable the "Site subdirectories" feature, under the 'experimental' group at admin/hosting/features.

That said, to answer your question, DB credentials are available via drush_get_context('site').


How do I add to $page_top in html.tpl.php?

Have a look at how the Drupal core toolbar module does this:

/**
 * Implements hook_page_build().
 *
 * Add admin toolbar to the page_top region automatically.
 */
function toolbar_page_build(&$page) {
  $page['page_top']['toolbar'] = array(
    '#pre_render' => array('toolbar_pre_render'),
    '#access' => user_access('access toolbar'),
    'toolbar_drawer' => array(),
  );
}

This is probably the most correct way of adding something to the page top as you can comfortably use render arrays.


there are a few steps you need to do:

Please upgrade you  Drupal Core
Apply this patch: Patch to your Ctools Module, you can be found the file here /includes/css-cache.inc


Exclude a single module from a Drush update?

You can use the following command:

drush pm-update --lock=modulename

There is a post here about it: http://blog.wassill.eu/en/blog/short-excludes-modules-drush-update-09-04-2013


Perform bulk operations on a custom database table

I've had a similar problem.  It's not ideal behaviour, but when I created the field, save it (selecting no action, or an action at random), then edit it (unselecting the random action, if I did that), then my custom action shows up.


Allow a role to edit a specific taxonomy list of terms

Taxonomy Access Control provides this functionality.  Workbench does as well, though it is slightly more complex and from my limited experience performs better when only a single term is used per node to control access.  Workbench (access + moderation) includes a nice set of tools for content moderation and workflow not found in Taxonomy Access Control. Both are worth a look before you decide for your use case.


Exclude exposed filter for one content type in my view

It looks like you want to make more distinct and/or groups. If using Drupal 7, here is a clear explanation of how to do it (see the accepted answer):
How can I do with Views and Drupal 7 what the Views Or module does in Drupal 6?

If using Drupal 6, the Views Or module can do the same thing.

If I understand your problem, the solution would be to put the first 2 Content Types in a group with the Taxonomy Term filters, then use a separate OR group for your 3rd Content Type.


Unable to see URL path setting menu for a user edit page

Download & install Pathauto module & then check.


What is the difference between DRUPAL_ROOT and file_directory_path() in drupal 6?

DRUPAL_ROOT is a root folder of Drupal's installation. file_directory_path() returns a path to directory meant for uploaded files, default DRUPAL_ROOT/sites/example.com/files (replace example.com with your site or default). If you will replace it with hardcoded path, your modules will break on sites configured to store files in other directory. So this is not the way.

If you need it for forms, use new managed_file form element. It takes care. No need to provide path.

For reading file, if you know it's ID it's easy again. Load it and access it's properties, like that:

file_load($fid)->uri; // get URI to display it

If you don't want to use managed files (you should, but no one can force you), use:

$dir = file_default_scheme() . '://' . $any_subdirectory_you_want;

This will create directory string Drupal functions understand. For example, you can use it as $destination in  file_save_upload($source, $validators, $destination, $replace) - again, no need for hard-coding actual path or using DRUPAL_ROOT on your own.


Can drupal be setup for users to interact with and submit suggested changes to an article?

Yes - this is a common use case and is mostly done through adding and configuring  the workflow module and some combination of a moderation module (ex. Moderator or Modr8) to control who has final say over publishing the node.

To add a voting component to this, you would add voting api and then a voting widget (ex. fivestar or vote_up_down) based on what kind of user experience you are looking for. Then when a revision gets a certain number of votes, your moderators could publish the content. If you wanted this to occur automatically, you should take a look at the Rules and Voting Rules modules.


I've solved the puzzle and I'm sharing the solution.

function custom_alter_views_pre_render(&$view) {
    if ($view->name == 'hot_offers') {
        //dpm($view);
foreach ($view->result as $key=>$value) {
    $c = @$value->field_field_hot_offers_new_date[0]['raw']['value'];
    $d = date("Y-m-d"); //2014-06-26
    if ($c < $d) {
    $value->field_field_hot_offers_new_image[0]['rendered']['#access'] = FALSE;
    }
  }
 }
}

The tricky part was to set the $d same format as the new_date field, otherwise the if statement logic will not work.


How can I redirect user/*/edit to another page based on user content?

So in broad strokes, basically what you want to do is grab the user's uid and then open for editing the corresponding profile type node owned by that user.

So, if you have that user's uid in $uid, it would be something along these lines:

$nid = db_select('node', 'n')
        ->condition('n.type', 'YOUR_PROFILE_NODE_TYPE')
        ->condition('n.uid', $uid)
        ->fields('n', array('nid'))
        ->execute()->fetchField();

which, if I've not typo'ed anything will set $nid to the node id of the node of type YOUR_PROFILE_NODE_TYPE that is owned by $uid.

If there is only one, that's the node we are looking for.

So, now you just need to create a link to node/$nid/edit and you're all set.  (Somewhat obviously, you want to present this link only to admins and the user who owns the profile.)

So, where do you put all of this?

Of course, you could preprocess this into a variable that's used in a page template, but you could also create a new menu item as well, eg user/#/edit-profile that grabs the user id out of the second argument and then does all of the above to grab the actual nid and then presents the node edit form, but now we are getting past the broad strokes :)  (But hook_menu() is the place to look, with user.module a great starting point for example code for user/#/edit to modify)


How do I make a link to a flagging edit page?

Digging into the flag module a little, I can see this entry in flag.routing.yml that appears to be for your Flagging edit screen.
flag.field_entry.edit:
  path: '/flag/details/edit/{flag}/{entity_id}'
  defaults:
    _controller: '\Drupal\flag\Controller\FieldEntryFormController::edit'
    _title_callback: '\Drupal\flag\Controller\FieldEntryFormController::editTitle'
  requirements:
    _flag_access: 'entity:flag{flag}'

You can build out the link to the flagging manually, e.g.
Edit My Flagging

Or if you're working with twig, e.g. rewriting a view's field, make sure you're also including the flag's id and flagging's id in the view then rewrite doing something like:
{{ "Edit Flagging"|t }}

Or you can use PHP to build the url directly from the route. It's recommended to use one of the following methods if you're working in PHP.
To get just the url text or object in PHP, use Url::fromRoute():
use \Drupal\Core\Url;

$my_flagging_url_object = Url::fromRoute('flag.field_entry.edit', [
  'flag' => FLAG_ID,
  'entity_id' => FLAGGING_ID,
]);
// $my_flagging_url_string returns something like "/flag/details/edit/123/1234"
$my_flagging_url_string = $my_flagging_url_object->toString();

To build the whole link in PHP, use Link::createFromRoute():
use \Drupal\core\Link;

$my_flagging_edit_link = Link::createFromRoute('MY FLAGGING EDIT TEXT', 'flag.field_entry.edit', [
  'flag' => FLAG_ID,
  'entity_id' => FLAGGING_ID,
]);


drupal gridview drop down menu - showing all menu and sub menus under one parent

Maybe you could use the Superfish module? Here is a quote about it (from the module's project page):

... integrates jQuery Superfish plugin with your Drupal menus:

Unobtrusive JavaScript.
Keyboard-accessible, screen reader friendly.
Multi-column sub-menus. (Megamenus)
Easing effects with the jQuery Easing plug-in.
Automatic width calculation (sfAutomaticWidth plugin) (Use the development release)
Automatic sub-menu width calculation (Supersubs plugin), automatic sub-menu placement (Supposition plugin; prevents sub-menus from appearing off-screen.)
Touch-screen compatible. (almost)
Small-screen compatible. ( and vertical accordions)
Window width (client-side) and UA string (client-side and server-side) detection for touch and small screen plugins (no CSS3 media-queries)
RTL (Right-to-left) language support.
Plenty of built-in options for designers.
And a whole lot more...


How do I configure subdomain url as one.mysite.com/subdomain1

The Subfolders Domain module sounds like it'll handle what you're after. Additionally, you may want to read through my blog entry about serving Domain Access-controlled sites from subfolders instead of subdomains.


Replace placeholder in custom block with preprocess hook

In addition to @sonfd answer you also need to consider caching. The easiest way would be to add a cache context:
$variables['#cache']['contexts'][] = 'user';

But then the database needs to store a cached version for each user.
Better for performance would be to postpone replacing the placeholder by attaching a lazy builder to the render array:
function mytheme_preprocess_block(&$variables) {
  $variables['#attached']['placeholders']['{{user-uid}}'] = [
    '#lazy_builder' => ['_mytheme_replace_uid', []],
  ];
}

which then returns the markup of the user UID:
function _mytheme_replace_uid() {
  return [
    '#markup' => \Drupal::currentUser()->id(),
    '#cache' => ['contexts' => ['user']],
  ];
}

Drupal 9
Drupal 9 requires using only trusted callbacks. So define a class implementing TrustedCallbackInterface or RenderCallbackInterface:
mytheme/src/MythemeLazyBuilders.php:
<?php

namespace Drupal\mytheme;

use Drupal\Core\Render\Element\RenderCallbackInterface;

class MythemeLazyBuilders implements RenderCallbackInterface {

  public static function replaceUid() {
    return [
      '#markup' => \Drupal::currentUser()->id(),
      '#cache' => ['contexts' => ['user']],
    ];
  }

}

and add it to the render array:
function mytheme_preprocess_block(&$variables) {
  $variables['#attached']['placeholders']['{{user-uid}}'] = [
    '#lazy_builder' => ['\Drupal\mytheme\MythemeLazyBuilders::replaceUid', []],
  ];
}


Is it safe to call field_view_field() for a field that isn't attached to the given node?

Source code of this function looks as follows:

function field_view_field($entity_type, $entity, $field_name, $display = array(), $langcode = NULL) {
  $output = array();

  if ($field = field_info_field($field_name)) {
  // Actual work on field, not needed here in this answer
  }

  return $output;
}

It means that if there is no field, empty array will be returned. That's all. Is it safe? Depends what are you doing with that array down the road. For example you cannot render empty arrays with render(), as it accepts only arrays representing Drupal's renderable elements.

Note that this is from the current, 7.23 version of Drupal.


Drupal Views: Get all of x categorised by y

I haven't learned how this works myself yet, so I can't give you an exact answer, but here's a video tutorial on Using aggregation in Views, which should answer this for you.


Why don't you simply go to Structure -> Content Types -> [Your type] -> Manage Fields -> Body -> Edit uncheck "Required field"? Since Drupal 7, body behaves as any other field...

If you really need to do this in code, then you do it in form_alter like this:

function [mymodule]_form_alter(&$form, &$form_state, $form_id) {
  // some logic here to filter which form is affected (or use hook_form_FORM_ID_alter)
  $form['body'][LANGUAGE_NONE][0]['#required'] = FALSE;
}

Is there any particular reason for you to do it during validation and not on form render? You stated that you need to "skip required body field validation, if it's empty" which is equivalent to turning the "required" completely.

EDIT:
I found a way to do this (based on this - https://api.drupal.org/comment/28464#comment-28464):

function my_validate($form, &$form_state) {
  $errors = form_get_errors();

  if ($errors) {
    // Clear errors.
    form_clear_error();
    // Clear error messages.
    $error_messages = drupal_get_messages('error');
    // Initialize an array where removed error messages are stored.
    $removed_messages = array();

    // Remove all errors originated by the 'foo][bar' element.
    foreach ($errors as $name => $error_message) {
      if ($name == 'body][und][0][value') {
        $removed_messages[] = $error_message;
        unset($errors[$name]);
      }
    }

    // Reinstate remaining errors.
    foreach ($errors as $name => $error) {
      form_set_error($name, $error);
      // form_set_error() calls drupal_set_message(), so we have to filter out
      // these from the error messages as well.
      $removed_messages[] = $error;
    }

    // Reinstate remaining error messages (which, at this point, are messages that
    // were originated outside of the validation process).
    foreach (array_diff($error_messages['error'], $removed_messages) as $message) {
      drupal_set_message($message, 'error');
    }
  }
}


Reference current user when creating a content type

You can set default values in a hook_ENTITY_TYPE_create:

/**
 * Implements hook_ENTITY_TYPE_create() for 'node'.
 */
function mymodule_node_create(\Drupal\node\NodeInterface $node) {
  if ($node->getType() == 'my_content_type') {
    $node->field_user->target_id = \Drupal::currentUser()->id();
  }
}


How to resolve my Fatal Error after uninstalling Views Chart Tools and Google Chart Tools

SOLVED - Used phpMyadmin and selected all cache tables then using the Empty option from the dropdown performed TRUNCATE on all cache fields. At this point cleared the cache that was throwing the error.


Changing a block title per theme or page

Here is a per theme solution.
In your View, under Advanced, click on Theme Information, the following pops up:

Now click on style output, and copy the entire code inside in to a new file in your text/code editor.
In my case it is:
<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * @ingroup views_templates
 */
?>
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>

Change the
<?php print $title; ?>
 to
Your Custom Title

Then save the file as views-view-unformated--[view-name]--[machine-name].tpl.php
(In my screenshot, example is the name of my view, and machine name is page, basically use last name suggestion)

Put this template file in your Adminimal theme's template folder and clear the cache to see changes.


You should be able to just retrieve the form and print it on your node template. In your theme's template.php (a custom module would work too):

function MYTHEME_preprocess_node(&$variables) {
    if ($variables['view_mode'] == 'full' && $variables['nid'] == 9 && user_is_anonymous()) {
        $variables['login_form'] = drupal_get_form('user_login');
    }
}

And then in either your theme's node.tpl.php or a specific node template if you're using one:

<?php if (isset($login_form)): ?>
  <?php print render($login_form); ?>
<?php endif; ?>

This will just print the same form you'd find at /user/login wherever you want it. Just make sure to replace the 9 with your node's nid.


Use AJAX with form button to clear checkboxes in separate forms

In talking to Randy Fay, this will not work for a number of reasons, of which security is a big one.  Form API was written to avoid one form modifying other forms (among other things), so I re-architected the form elements to be all in one form instead of separate forms.


Show new result each time I visit the page

In Views Sort criteria Section Choose the Global and then choose Global: Random field, it will display each time different result(when the page is refreshed) but it will be random.

I hope it will help you.


Using EntityFieldQuery's FieldCondition on file fields (or complex fields)

A file field only contains the fid (file ID) relating to the file. The extra data you see (filename, uri, etc.) are loaded by the file module, but are actually contained in the file_managed table, which is not a field table.

Since EntityFieldQuery doesn't support JOINs you're out of luck, unless you alter the query a bit later on, e.g.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->addTag('customtag');

...

function MYMODULE_query_customtag_alter(QueryAlterableInterface $query) {
  $query->innerJoin('file_managed', 'file_managed', 'file_managed.fid = field_data_field_name.fid');
  $query->condition('file_managed.filename', $something);
}

That will obviously need some tweaking for your specific situation.


Anchor links to views grouping field titles

I think this may be a template modification task.

This is the current views-view-unformatted.html.twig file:

{% if title %}

{{ title }}

{% endif %}
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}

    {{ row.content }}

{% endfor %}

Switch:

{{ title }}

With:

{{ title }}

This would require your titles to all be unique to ensure unique ID's. There may be something better to use than "title" for the ID as well in this case.

Also, I would wonder if using an "attachment" in the view might give better options and control over a block for the table of contents...


Best way to get module and commit meta data from drupal.org

It took me a while to find but this is what I was looking for:

https://www.drupal.org/api

  The following node types currently exist on drupal.org:

  book book_listing casestudy changenotice forum image organization
  packaging_whitelist page project_issue project_core
  project_distribution project_drupalorg project_module project_release
  project_theme project_theme_engine project_translation story Of
  particular interest is interacting with the issue queues. Some of the
  field values returned by the api are the numeric representations in
  the database. The following mappings are used for some key fields on
  project_issue nodes:

  field_issue_priority

  400,"Critical” 300,"Major” 200,"Normal” 100,"Minor" field_issue_status

  1,active 2,fixed 3,closed (duplicate) 4,postponed 5,closed (won't fix)
  6,closed (works as designed) 7,closed (fixed) 8,needs review 13,needs
  work 14,reviewed & tested by the community 15,patch (to be ported)
  16,postponed (maintainer needs more info) 18,closed (cannot reproduce)
  field_issue_category

  1,'Bug report' 2,'Task' 3,'Feature request' 4,'Support request'

  Available Taxonomy Vocabularies

  1,Forums 2,Screenshots 3,Module categories 5,Drupal version 6,Core
  compatibility 7,Release type 9,Issue tags 31,Page status 34,Front page
  news 38,Audience 44,Maintenance status 46,Development status
  48,Services 50,Sectors 52,Locations 54,Keywords 56,Level 58,License
  60,Book availability 62,Book format


Have a look at Taxonomy Split, Drupal 6 only at the moment.

if you have a vocabulary in the form of a tree, eg it has terms within terms with nodes attached to them.
It will place all the first level terms in a block and when a term is clicked displays the tree below that term in another block.


how to find image style url from themed image

You need to use the image_style_url function instead of theme.

$path = image_style_url('home_theme', $node->field_theme_image[$node->language][0]['uri']);


How to display different menu in a panel depending on node nr?

Solved by using the following php code in the visibility rule:

return arg(1) == 1; for menu abc block
return arg(1) == 2; for menu cde block


Configuring views to display all book-pages inside a book, from whenever you are inside the book

I did found the reason why it not work (as it should), it's probably a bug at the "filter criteria", who not where working with setting of Book depth.
I am lucky because I had different content-types on each level of the book.
And when trash away the book depth filter criteria  I could set filtering on the Content type instaed, and all works out as I wanted.
So this problem is solved,now I can display all book-pages inside a book, from whenever you are inside the book without any problem.


Change checkboxes in a node edit form alter

But when I change the value of the select list, the ajax doesn't seem
  work and options stay the same.

Simply because there is no db_query logic inside the ajax_options_choice callback.

How is Drupal suppose to know that it needs to run again the results db_query and then assign it to #options?

So essentially, currently, AJAX is executing, but you're just returning the same value that was calculated on initial page load.

  Which ways can I test the ajax works or not?

function ajax_options_choice(&$form, &$form_state) {
  drupal_set_message('Yes AJAX was called');
  dpm('yay dpm works!');
  watchdog('my_module', 'ajax was fired', array(), WATCHDOG_NOTICE); // now check /admin/reports/dblog
  return $form['field_options'];
}


Drush: Wrong PHP version when trying to sql-sync with SSH

Check the user that is specified in your Drush alias file.  From the error message above, my guess is that you have configured your alias file to use the web server user, and your web server user is probably not configured to use php-cli -- that's probably why you're getting an old php-cgi instead.  Log in as the web server user (you may need to edit /etc/passwd and change the shell to /bin/bash first), and then configure your path and DRUSH_PHP environments as you describe above.

Alternately, you could use some other user in your Drush alias file.  I like to create a user called 'www-admin', or something similar, and make all of my web files owned by that user.


How can we render graphviz diagrams in drupal pages?

There's the Graphviz Filter module, which provides an input filter that will convert Graphviz DOT syntax to the required diagrams. You can find more information in the Drupal documentation on graphing modules.


Can I get the Node's content type in hook_flag_alter

If you're using flag 2.x with Drupal 7, then this should give you what you want.

function hook_flag_alter(&$flag) {
    $type_text = "";
    switch($flag->entity_type) {
      case 'node':
        switch(reset($flag->types)) {
          case 'page':
            $type_text = t('Page');
            break;
          case 'blog':
            $type_text = t('Blog Post');
            break;
          default:
            $type_text = t('Node');
        }
        break;
      case 'user':
        $type_text = ('User');
        break;
      default:
    }

    $flag->flag_short = t('Follow @type', array('@type' => $type_text));
    $flag->unflag_short = t('Unfollow @type', array('@type' => $type_text));
}

Note: This code assumes that each flag only applies for a single content type.


In Drupal 8 this option has been removed. You don't have to configure  base_url to run your site. Drupal 8 can detect this without your help. If not, you should first check your webserver configuration.

Instead of base_url you should configure trusted_host_patterns in settings.php. This is not needed to run the site, but important for security reasons.

More info: Removed base_url option from settings.php and New setting for trusted hostname configuration

Edit:

There are some special use cases when running drupal from command line or reverse proxy, that used $base_url in the past. This can no longer be supported in the same way because of symfony. There is a discussion going on how to provide a solution for these cases. This does not mean that you cannot run drupal from the command line or reverse proxy. The standard way is of course possible without problems.

You can follow the development here: https://www.drupal.org/node/2753591


Changing label of views exposed date filter select list

Looks like this is something we have already on drupal issue-queue as https://www.drupal.org/node/2296607.

I was expecting the options to be alterable by any hook, unfortunately could not find any.

I explored the code in date module, and found the elements are processed by a function as date_parts_element, under which it appending '-' before the label.

Now, while the following will fix your issue but I would nor recommend it to you until it is approved by community. The hack is

In your date_api_elements.inc file(date/date_api) inside function date_parts_element add this line drupal_alter('date_process_element', $sub_element); in the bottom just before return $element; so it looks as

    .....
    if ($element['#date_label_position'] == 'within') {
      $sub_element['ampm']['#options'] = array('' => '-' . $label) + $sub_element['ampm']['#options'];
    }
  }
  drupal_alter('date_process_element', $sub_element);
  return $sub_element;
}

This will allow any custom module to alter the elements of date filter. Now in your custom module let's say named as my_module implement the hook we have added as following

/**
  * Implements hook_date_process_element_alter.
 */
function my_module_views_date_process_element_alter(&$element) {
  foreach($element['year']['#options'] as $key=>$value) {
    if($value == '-Year') {
        $element['year']['#options'][$key] = 'Year';// Or whatever you like to give.
    }
  }
}

I will be adding the same suggestion on drupal issue page.

Update

Indeed no patch required, date module provides the hooks out of the box, got to know from update mentioned issue feeds, didn't try the cpde myself but looks promising

function MYMODULE_date_select_process_alter(&$element, &$form_state, $context) {
  // Tweak the -Year filter to remove the -
  if (empty($element['year'])) return;
  foreach ($element['year']['#options'] as $key => $value) {
    if ($value == '-Year') {
      $element['year']['#options'][$key] = 'Select Year';
      break;
    }
  }
}


The parameter will have been upcasted from nid to full node object by the time you get access to it, so:

$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
  // You can get nid and anything else you need from the node object.
  $nid = $node->id();
}

See the change record for more information.


I suggest you two solution one based on what you tried to did

First solution

in yourthemename.theme

if ($variables['node']->getType() == 'YOUR_CONTENT_TYPE') {
    $variables['My_Field'] = $variables['node']->get('YOUR_FIELD')->value;
  }

and in your custom node template

   {{ My_Field }}

  Tips: Those of "YOUR_CONTENT_TYPE" and "YOUR_FIELD" are
  machine names for your content type and your content field.

Second solution

in your content type node template file ( I mean if your content type name is News in node--news.html.twig) try to add your custom value to it with:

  {% set My_Field = node.YOUR_FIELD.value
      {# Make your manipulation here #}
   %}
   {# And then print it back wherever you like with below code: #}
  {{ My_Field }}


How to make an editable catalog on Drupal?

The simplest thing todo is to make a View thats lists your catalog entries. In the Header area of the view add a global text area in which you create a link such as Add New Entry.

Then also install the Editable Views module:

  Editable Views lets you create Views where the fields can be edited.
  Fields show both the current value and a form to edit it. A 'Save'
  button allows saving of all the entities shown in the View.

  Editable fields can be added on the base entity as well as on entities
  brought into the View by a relationship. Other, non-editable fields
  may be added to the View, in which case they function normally.

From the project page you can see a screencast on how to use the Editable Views module.


Using base_url() in image paths without using PHP?

in your .htaccess file, you could try something like:

RewriteEngine on

(in case it is not already turned on)

RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
RewriteRule ^$ subfolder [L]

(where in this case 'subfolder' represents the address of the installation)

This should create a system based, base url, rather than a php based url - so relative paths should work.


What module can create a gateway or doorway popup AD page before viewing content for Drupal 7?

The Splashify module should do exactly what you need. You can specify a list of the pages you want to redirect to an ad (you can use the wildcared (*) too) and a list of different pages to use for the ads, and they're choosen either random or in order. You'll have to create the pages for the ads though. How they get from the ad page to the content they requested may require a little PHP/javascript, I'm not sure.

http://drupal.org/project/splashify


How can we just apply the updates to a single module using composer without apply patches for other modules?

Unfortunately, composer is always going to apply any patches you have defined that are not already applied whenever it runs. You can comment out the patches, run your composer command, and then uncomment them.


The problem is the way this is stored (1 to many relationship). There is no simple way of asking for nodes with terms 1 and 2.

To query for nodes they way you describe you would have to select nodes that has tid 1 and the nid is in a list of nodes that has tid 2. This is possible to do, but not something views support AFAIK.

To get this list, it would be easier to create the query yourself, or resort to hook_query_views_alter, which easily gives problems when maintaining.


How to allow users have only alphabetical "username"?

Check out the Custom Username Validation module, it seems like it should do exactly what you like.

If not, (In Drupal 6) you can set up "Access Rules" in the administration pages.  Set up multiple access rules to deny usernames that contain undesired symbols.  Access Rules Docs. Unfortunately that would take a lot of time to deny all non-alphabetical characters.

Finally, you could also create a custom module and use hook_form_alter() (or hook_form_FORM_ID_alter()) to change the validation on the username field. Here's a related question on SO: Hook into Drupal registration and validate user info against business logic


How to pre populate the commerce shopping cart with products

I implemented a hook_menu with callback that adds specific product variation from the arguments to the cart and then redirects the user to cart. With same logic you could toss in all the products you wish. Mayby just additionally check that that cart is initially empty.

function x_menu(){
    $items['tickets'] = array(
      'page callback' => 'x_tickets_callback',
      'access arguments' => array('access content'),
    );
    return $items;
}

function x_tickets_callback(){
    global $user;

    // mayby check that cart is empty here

    // you should get these really from some variable
    for($i = 1, $i<7,$i++){
      $commerce_product = commerce_product_load($i);
      // create line item from product
      $line_item = commerce_product_line_item_new($commerce_product);
      commerce_cart_product_add($user->uid, $line_item);
    }
    // prevent notification
    $messages = drupal_get_messages();
    drupal_goto('cart');
}


You could try setting the subscription confirmation pages at: /admin/config/services/simplenews/settings/subscription > "Confirmation pages"

  SUBSCRIBE CONFIRMATION

  Drupal path or URL of the destination page where after the
  subscription is confirmed (e.g. node/123). Leave empty to go to the
  front page.

It may be that that page is only used when confirming from the email link, but might work for the subscribe block as well.

The message text could be overridden with the stringoverrides module


How to place an image on a specific page

You can check template suggestions in the documentation.

  The list of suggested template files is in order of specificity based
  on internal paths. One suggestion is made for every element of the
  current path, though numeric elements are not carried to subsequent
  suggestions. For example, "http://www.example.com/node/1/edit" would
  result in the following suggestions:

  page--node--edit.tpl.php
  page--node--1.tpl.php
  page--node.tpl.php
  page.tpl.php

The template name started with "page--" is an override of page.tpl.php for a particular node or whatever.

Find out what is the node ID of your "page-5", let's say it is node ID 1.
Copy page.tpl.php and rename to page--node--1.tpl.php
Then you can update it as you need ( print your image like you did in the front page ).


what permission is need to access to content page?

According to the node module a user must have a role that is allowed for 'administer nodes'.


How to set a session variable when a link is clicked?

You can do like this.

Link URL :

 'name' => l(t($n['name']),'edit_details/@uid', array('@uid' => $n['uid']))

In hook_menu() :

$items['edit_details/%user'] = array(
    'title'          => 'Lets start',
    'page callback'   => '_get_user',
    'page arguments'  => array(1),
    'access callback' => TRUE,
    'type'            => MENU_CALLBACK,
  );

In callback :
In callback function you will get complete user object, as this wild card used for user core module.

function _get_user($user) {
  $_SESSION['user_name'] = $user->name;
  //Redirect to any other page you want.
}

Thanks!


How to get Taxonomy Menu working properly with Contextual Filters in Views?

You have made one mistake that is easy to make. The alias created in the menu doesn't change the "true" url. So when you go to catalog/cars Drupal will perceive that as taxonomy/term/[tid].

What you could do instead is to enable the default taxonomy term view that ships with Views (which uses taxonomy/term/[tid] as the path) and then set it up like you want.

See Screen shot:


How do I enable private messages for normal users, and not just administrators?

You need to set up permissions to use Privatemsg.

Go to example.org/admin/people/permissions (Home > Administration > People, Permissions tab) and check privatmsg boxes for Authenticated User role.

It might be also convenient to create "Messenger" role with these permissions, and grant it to all users by default. That way, you will be able to ban someone from messaging by simply taking role away from him.


Store user test results against their profile in Drupal Quiz Site

You can also create fields directly attached to the User entity just as you would to a content type.  It may make more sense to store the information for a specific user in fields attached to their identity directly. You can create views and panels to display the information however you want and provide hook functions in a custom module to do whatever specialized calculations you desire for presenting averages, grades etc.

I also noticed that you have used the Profile tag which relates to a module that has been deprecated for D7.  If you have the module enabled, I recommend not using it for any future site since it will very likely not be maintained in D8.


user_profile_form doesn't show profile2 information

You've implemented hook_form_FORM_ID_alter(), which only fires for a single form (user_register_form in this case).

If you want to catch multiple forms in a single function, you need hook_form_alter():

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form' || $form_id == 'user_profile_form') {
  ...
}


Add a field Global: Custom text at the end of your field list, add the replacement patterns in the `Text' box.

The is from the comment by Dom Day which worked for me.
Still wondering why the method in the question produced no output at all.


How to hide child field collection using jquery

Can you replace the code in your JS file with the following:

(function ($, Drupal, drupalSettings) {

  'use strict';

  Drupal.behaviors.myModuleName = {
    attach: function (context, settings) {
        $('#node-student-form .field--type-field-collection .field--name-field-child-english-info').css("display","none"); // Child FC 1
        $('#node-student-form .field--type-field-collection .field--name-field-child-maths-info').css("display","none"); // Child FC 2
    }
  };

})(jQuery, Drupal, drupalSettings);

This is based on this article
The attach() function ensures that your code runs each time an Ajax call is made


How to use Block Access with specific Block?

Solved this using a patch and granting input filter permission. Patch is here https://drupal.org/node/1916028#comment-7302100.


How to create a Rule to email referenced authors after saving new content?

Actually it's a LOT easier than I thought. I found that the following worked for me so far:

node:referenced-field:0:author:mail

I hope that this helps someone.


New path creation through hook menu problem

You form function callback is incorrect you need to return a valid form, try this code:

function displayproducts_show_form($form, &$form_state){
  $form['item1'] = array(
   '#markup' => "hello world",
  );
  // @TODO: include more form items.
  return $form;
}

Documentation: FAPI

Make sure that this function is in your uc_cart.admin.inc file as you indicate in the hook menu declaration: 'file' => 'uc_cart.admin.inc', if it is in your main module file (.module) remove this line and clear the caches again.


How to assign define role to group creator in groups created with the Group module?

The latest beta release of the group module (8.x-1.0-beta5) includes that functionality.

Download, install, run DB updates and go the the settings page for the group type.


"syntax error, unexpected end of file" Upon enabling modules

I figured out what this was. It wasn't necessarily related to Drupal or PHP syntax, but the answer might save someone else some stress.

I had VMWare Fusion on my Mac running a Linux VM with Apache/MySQL/PHP server.  The webroot for Apache was a shared directory on my host machine which contained my Drupal install. I did this so I can have the benefit of a Linux web server while being able to edit my code locally on my host.

This works when serving up the site, but whenever I used Drush on the VM to install a module, there was always a hidden line appended to the module's files that Vi didn't pick up, which is why the syntax error was always on the last line. I'm assuming it had to do with the hgfs filesystem used for sharing between my host and the VM.

Once I removed the VM sharing and modified everything on the VM itself, all of my problems went away. Downloading modules with Drush no longer produces these syntax errors.

Here is a related thread on the Drush issue queue where people are having similar issues.

https://drupal.org/node/1948962

Thanks to those who gave their feedback.
--richard


Scheduled unpublished content and media that is under content moderation

It should be no problem for a module to implement a cron hook to unpublish content and media after a set amount of time.
Concerning the media files, if you want that they can no longer be accessed after unpublishing the media entity you have store them in the private file system configured in settings.php. See
https://www.drupal.org/docs/8/modules/skilling/installation/set-up-a-private-file-path
The public file system example.com/site/default/files can be accessed through the web server directly without Drupal being involved.


I found the answer here.

The required field radio button was not selected, when the image was uploaded. It seems an error with the form validating when the image is uploaded.


Adding multiple nodes using a single form

Your question is so specific to your implementation; what you want to do is create a node with some single value fields and multiple images, each image with a title, description and nodereference.

It is the last part of the above that is actually the question: How do you add fields to an image?

The file entity module allows you to add fields to a file, but those fields are not available on the node edit form, you have to go to admin/content/file to add these values.
The Field Collection Module allows you to define a set of fields, so on your node you would define a field collection field which has an image, a caption, nodereferences or whatever. (not too clear...try it out)


Follow  below steps and change that file.

Go to your XAMPP installation Folder and edit - ..\xampp\php\php.ini file.
Use the FIND function of your editor an look for "max_execution_time"
in that line you will see the value attributed to "max_execution_time"
change it to max_execution_time=120
Save the php.ini file.
Restart the XAMPP Server
Proceed with Drupal Commons installation.


How to log in users without credentials?

You can do it like this:

global $user;
$user = user_load($uid);

Where the $uid is the User ID of the user you want to log in.

Note that this potentially opens you up to major security issues.


Download field_slideshow module and enable it. After enabling go-to this link and download as jquery.cycle.all.js, place it under sites/all/libraries/jquery.cycle. Clear cache after this.

After enabling go-to manage display and in your image format select as Slideshow.

Attaching screenshots.


Formatting options in Webform Select field

Take a look at Chosen module can help you.


The problems with your original (first) question are as follows:

Your callback function expects 2 parameters, but you are providing just one.
You are missing nojs in your url.
You are giving param as a parameter to your callback function, but you wanna % instead/

So it should look like something like this:

  $items['myajax/param/nojs/%'] = array(
    'page callback' => 'myajax_ajax_callback',
    'page arguments' => array(2,3), // drupal starts counting from 0 so nojs is 2nd and % is 3th arg
    'access arguments' => TRUE,
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );

I hope this will help someone.

P.S.
sorry for my English


redirect after login in drupal without impacting the password reset functionality

hook_user_login is as you'd expect for when someone goes from anonymous to authenticated. This happens by using the login form and by using a password reset link.

Having a look on Drupal's API site is always worthwhile as people have usually commented on comment occurances like this. For example on https://api.drupal.org/api/drupal/modules%21user%21user.api.php/function/hook_user_login/7.x it has exactly what you're describing and recommends using something like:

if((!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset')){
  //your redirect code
}

But also using form_alter would also be perfectly fine really as you want to target a specific action of logging in via a specific form


Moving the Up/Down Vote Widget to end of content

Widget is getting displayed using hook_node_view code in vud_node.module...

/**
 * Implementation of hook_node_view().
 */
function vud_node_node_view($node, $view_mode, $langcode) {
  // avoid showing the widget in some node builds
  $exclude_modes = array(
    NODE_BUILD_PREVIEW,
    NODE_BUILD_SEARCH_INDEX,
    NODE_BUILD_SEARCH_RESULT,
    NODE_BUILD_RSS,
  );
  if (in_array($node->build_mode, $exclude_modes)) {
    break;
  }
  if (($can_edit=user_access('use vote up/down on nodes')) || user_access('view vote up/down count on nodes')) {
    $node_type = in_array($node->type, variable_get('vud_node_types', array()), TRUE);
    $widget_showmode = variable_get('vud_node_widget_show', VUD_NODE_DISPLAY_BOTH);
    $tag = variable_get('vud_tag', 'vote');
    $widget = variable_get('vud_node_widget', 'plain');
    $vote_on_teaser = (bool)variable_get('vud_node_widget_vote_on_teaser', TRUE);
    $teaser = $a3;

    $widget_message_code = VUD_WIDGET_MESSAGE_ERROR;
    if (!$can_edit) {
      $widget_message_code = VUD_WIDGET_MESSAGE_DENIED;
    }
    elseif (!$vote_on_teaser) {
      $widget_message_code = VUD_NODE_WIDGET_MESSAGE_TEASER_DENIED;
    }

    if ($node_type) {

      switch ($widget_showmode) {
        case VUD_NODE_DISPLAY_TEASER_ONLY:
          if ($teaser == 1) {
            $node->content['vud_node_widget_display'] = array(
              '#value' => theme('vud_widget', $node->nid, 'node', $tag, $widget, !$vote_on_teaser || !$can_edit, $widget_message_code),
              '#weight' => -10,
            );
          }
          break;
        case VUD_NODE_DISPLAY_FULL_ONLY:
          if ($teaser == 0) {
            $node->content['vud_node_widget_display'] = array(
              '#value' => theme('vud_widget', $node->nid, 'node', $tag, $widget, !$can_edit, $widget_message_code),
              '#weight' => -10,
            );
          }
          break;
        case VUD_NODE_DISPLAY_BOTH:
          if ($teaser == 1) {
            $readonly = !$vote_on_teaser || !$can_edit;
          }
          else {
            $readonly = !$can_edit;
          }
          $node->content['vud_node_widget_display'] = array(
            '#value' => theme('vud_widget', $node->nid, 'node', $tag, $widget, $readonly, $widget_message_code),
            '#weight' => -10,
          );
          break;
      }

    }
  }
}

Implement hook_node_view_alter in your custom module and change the weight to higher value so that it will be displayed at bottom...

In Drupal modules extends permissions by defining them using hook_permission.. You can find list of permissions in "admin/people/permissions" ..

For vote up / down set permissions in above page.. See screenshot below..


Pass variables from html preprocess function to page preprocess function?

You're going to need either a global or static variable to accomplish this...personally I'd recommend going with static and implementing a generic helper function using Drupal's static pattern like so:

function _myTheme_var($var_name, $new_val = NULL) {
  $vars = &drupal_static(__FUNCTION__, array());

  // If a new value has been passed
  if ($new_val) {
    $vars[$var_name] = $new_val;
  }

  return isset($vars[$var_name]) ? $vars[$var_name] : NULL;
}

function myTheme_preprocess_page(&$vars){
  $vars['some_var'] = _myTheme_var('my_var', 7); // Set the value and retrieve it
}

function myTheme_preprocess_html(&$vars){
  $vars['some_var'] = _myTheme_var('my_var'); // Get the value
}

The $vars arrays for each preprocess function are completely different objects in memory so you won't be able to use that array to pass things around. I've seen this sort of pattern used a lot in Drupal core so I think it would be the best way to go.

EDIT

Oh and yes, hook_preprocess_page() is called before hook_preprocess_html()...as far as I'm aware Drupal works in a sort of "inside-out" manner so hook_preprocess_html() would probably be the last one that's run in a page build.


What is the purpose of the "token" custom display setting?

As Neograph734 commented, it allows you to change the output of field tokens without actually changing the default display of the field. You can find more information here: https://www.drupal.org/node/1299662

Actually, a similar question already has been answered: Effective use of tokens view mode?


Vimeo Video Browser While Creating New Page In Drupal

I can advice you this module
https://drupal.org/project/media
https://drupal.org/project/media_vimeo

I wish it helps you.


Elysia cron module does not execute cron job automatically

As I mentioned before Elysia Cron can only schedule the cron jobs not control it when to run.
If system crontabs are set to run every minute elysia cron module can control it from there on.
Check out the drupal page for that module.

  Elysia Cron
  However to get the full potential out of elysia cron and have the full
  control over you tasks a further step is needed: you need to configure
  the system crontab to execute drupal cron every minute.


Bibliography module url search as anonymous user

It sounds like you've practically have solve the problem; the issue is with content display permissions. The question need to ask yourself is what access control is being restricted. Is it node type viewable permission? Is it view unpublished content permission?

If you're looking for way to troubleshoot this see How to debug permissions.


How can I get the node ID from a path alias?

I'm not sure if there's a direct function, but one route is to use the path alias manager service to lookup the internal path then regex it for a valid node id to perform an object load on:

$path = \Drupal::service('path.alias_manager')->getPathByAlias('/this-is-the-alias');
if(preg_match('/node\/(\d+)/', $path, $matches)) {
  $node = \Drupal\node\Entity\Node::load($matches[1]);
}


Need a hook a little later then hook_node_insert

Did you try to make your module's weight higher, to make sure your hooks get executed after all other modules' ? The documentation states that node_insert is called after file_attach_insert so it might be worth a try.


Dynamically populate one select based on another

Try conditional_fields

Update multiple fields with ajax callback in form


How to change field_tags in hook_form_alter?

The field_tags element is likely a widget from the Field API. You can surely alter it from a form alter hook, but be aware that it would not be your average Form API element. The Field API adds post-processor, pre-rendered, etc. functions of its own. These functions may expect things you may want to alter.

You can however, change the default value of the field from the configuration interface of your content type (you need to enable the Field UI module for this). You should also be able to select a different widget (ie. a select box) from there.


D7 - Losing images when moving site location; placeholders point to old absolute path rather than relative path

Have you tried using http://drupal.org/project/pathologic?

Which way are you using to migrate your database and files? I would also suggest that you clear the cache before exporting.


How to pass taxonomy reference field data into a views reference contextual filter arguement with PHP code?

As the help text puts it, you just need to return the value. Of course, your actual question might be to access the term id but you have not specified that.

For example, if you want to show the view as a block on a regular node page, and the node contains the tid, you would use code like this:

// Lets assume that this view will always be shown on a node page.
$node = arg(1);
$tid = $node->field_term_reference[0][LANGUAGE_NONE]['value'];
return $tid;

This code could be improved a lot but it gives the basic idea.

As a side note, if your scenario is as per above, then consider using Panels and pass in the term id using contextual arguments.

Side note 2: Your screenshot shows filter dialog for Term Name whereas your question asks for term ID. I have given the example for the latter. I hope it helps get you started.


Drush was designed for use with bash, not fish.  Would it be an option to make your login shell bash for your remote Drush user?

Your other option would be to submit a patch to Drush to fix this problem.  There are two possibilities:

Modify Drush to use env DRUSH_PHP=... in backend invoke.
Modify Drush to not pass --php when --remote-host is set.

Option (1) may be harmful to remote sites where env is not in the PATH, so it may be a dubious proposition.  It might be okay, though; env is probably in the PATH on most systems.

Option (2) seems better.  There is little reason to think that the path to php will be the same on a remote system as it is on the local system, so Drush probably shouldn't be assuming that the php option is relevant for remote aliases, unless it was set in the alias' %path section.

Either of these actions would require a discussion in the Drush issue queue.


In Drupal Commerce how do you auto login an anonymous user that has completed checkout?

In short summary to the link Clive posted in case if it ever gets deleted on the interwebs:

http://s1l.org/automatic-user-login-anonymous-checkout

Step 1 - Make sure Anonymous checkout is checked on. (Permissions > Access Checkout)

Step 2 - Make sure Commerce Immediate Login module is enabled: http://drupal.org/sandbox/simongeorges/1676742

Step 3 - Add a User Login Action to the default Commerce "Create new account for anonymous order" Rule (Configuration -> Workflow ->Rules)

--- rules/reaction/manage/Create a new account for an anonymous order

Step 4 - Click Add action > Login User (under system) > type "account-created" > SAVE

Step 5 - TEST!


Should a hook_form_alter be firing both on render and when an additional submit handler is fired?

I think the chain of events is different. The form gets cached with no or the wrong redirect_dest set. Then the form is submitted and redirected to the form itself. This is now a new form build, because you didn't request a rebuild. Only in a rebuild you keep the form_state.

Solution:

Drupal has the feature to redirect built in. Add the destination on the page linking to the user login:

Url::fromRoute('user.login', [], ['query' => $destination])

Edit (new module):

To add the destination automatically you can use this module:

https://www.drupal.org/sandbox/gnuget/2824414

This is a js solution, so it doesn't interfere with caching. I think in this case you can use a sandbox module, because the site won't break if the js code stops working.


Is it ok to move the page-title outside of the content div? Or is there a better way?

Use the Blockify module. It will create block for a lot of common drupal elements (including page title), so you can easily place them on a page with a UI, rather than hacking templates.


How to get current language in html.html.twig of theme

Add the following snippet in your .theme file:

function MYTHEME_preprocess_html(&$variables) {
  $variables['lang'] = \Drupal::languageManager()->getCurrentLanguage()->getId();
}

Then, in your html.html.twig file use:

{% if (lang == 'en') %}
  // Your action
{% endif %}


The image module does not exist in Drupal 7 because this functionality is added to Drupal 7 core.

Implementing images as nodes was a clean way to do this in Drupal 7. You may still do this in Drupal 7. However, Drupal 7 has gone a long way and offers the entity alternative. At Drupal 6 'everything can be a node'. At Drupal 7, 'everything can be an entity'.
Nodes were meant to be used for publishing text. They come with a lot of functionality that you may find redundant in your use case. All this extra functionality can slow down your site if you have thousands or millions of entries.

I am not sure I understand why you should not do this. It was probably a suggestion and module specific. In Drupal 7 you can name your content type anything you want.

As I told you before, using entities for storing images is a better alternative, as far as the performance is concerned. But then you should implement your own method of commenting.

EDIT: In Drupal 8 there is some advances made in decoupling the comment module from node. See this issue.


How to use custom modal with ctools and triggered by a button form

Try this:

  $form['ajax_button'] = array(
    '#type' => 'button',
    '#value' => t('New Post'),
    '#attributes' => array('class' => array('ctools-use-modal','ctools-modal-slogan-style')),
    '#id' => 'hs-ajax-button',
    );

Vincent


how to create a grid view with only ONE image from nodes containing multiple images?

You can do it easily, by clicking the "Image Field" and check the Group Multiple Values and set show values as 1 and set starting from 0

see the image below


Probably with hook_form_alter. Change the #weight attribute so credit card lighter than paypal. Set the #default value to credit cards for the radio values.

I haven't used these modules nor have an Ecommerce site live so I cant post example code ...

EDIT

install Devel and implement hook_form_alter for your module. put dpm($form);dpm($form_id); in your form atler implementation ... and goto the page with the form in question. You will then see the PHP array structure for the form on the screen.


Create RSS feed for content type = news?

You can use the Views module to create feeds.  Simply add a new display of type "Feed" and customize the view to contain only the content you want.  Be sure to choose a path for your feed so that it can be accessed.

To add a "Feed" display:

Go to your views administration and select the view you want to edit. Towards the top of the page you will see the "Displays" heading with an "+ Add" button.  Click that and select "Feed" (See image below).  You will then have a Feed display that is using the Default Display's settings.


Views exposed filters without "Apply" button

Under advanced portion of view choose following

**Exposed form**

 Exposed form style: Basic | Settings

Then Choose autosubmit in Settings as shown below

This will hide the Apply button and the select list to work directly on selecting an item, instead of clicking on the Apply button.


create a custom field which is allowing multiple values using custom module

for unlimited set the cardinality to -1  'cardinality' => -1

example:

function _namecards_namecard_installed_fields() {
  $t = get_t();
  return array(
    'namecards_namecard_phone' => array(
      'field_name' => 'namecards_namecard_phone',
      'label' => $t('Phone'),
      'type' => 'text',
      'cardinality' => -1,
    ),
    'namecards_namecard_fax' => array(
      'field_name' => 'namecards_namecard_fax',
      'label' => $t('Fax'),
      'type' => 'text',
      'cardinality' => -1,
    ),
  );

}


Gmap click marker should zoom the map and display other markers

Have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (Google, OpenLayers or Leaflet) with any location storage module of your choice, e.g.:

Get Locations,
Geofield,
Geolocation Field
Location.

This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).
And the Set my location block allows your visitors to locate themselves on the map, either automagically --via the Wifi/GPS device on their mobile-- or by typing an address or landmark, like "Eiffel tower" (bottom screenshot, upper left corner, click to enlarge).
Follow this step-by-step tutorial to create a handy store locator with proximity search, from a list of addresses in a spreadsheet. You'll learn about the Feeds and Display Suite modules too!
Finally IPGV&M provides a set of visitor location retrieval technologies, both IP and HTML5-based, so that you can track where past visits came from and where current visitors are located, superimposing their moving positions as markers on your maps.

Head over to its (impressive) project page for even more information about it.


How can I convert character entities to display as 'normal' characters in Drupal?

Edit your import module to http://php.net/manual/en/function.html-entity-decode.php the text before importing.


Redirect the page after login with using modal form

Add this in your custom module. Hope it works.

/**
 * Implements hook_user_login().
 */
function my_module_user_login(&$edit, $account) {
ctools_add_js('ajax-responder');
$commands = array();
$commands[] = ctools_ajax_command_redirect('YOUR-REDIRECT-PAGE');
print ajax_render($commands);
exit;
}


How about hook_entity_insert

function hook_entity_insert(Drupal\Core\Entity\EntityInterface $entity){
  // do something
}

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_insert/8


Remove default installation profiles with drupal core

You need to add exclusive = 1 line in the .info file of your profile.


Value in my custom base field added to user entity isn't saved

In the end, I mofified my approach using https://www.drupal.org/project/one_time_password as an example. The difference is probably in the installation of the field definition - hook_install() works just fine.


Error 'Cannot redeclare ctools_menu_add_tab()' after migrating website

You have ctools installed twice, in:

sites/all/modules/ctools
sites/all/modules/ckeditor/ctools

Obviously the second path must have been mistake. If you can acces your page, disable ctools and then remove second instance. If you can't, try to do it using drush. If that fails, too, consider re-migration, this time properly. If all else fails, you may try to simply remove second instance and call update.php to perform some cleanup.


Unable to connect to local MySQL db using drush sql-sync

I have faced the same issue.
My solution was to add more rights to mysql user with this comande line :

GRANT ALL PRIVILEGES ON `myDB`.* TO 'mySQLuser'@'localhost' WITH GRANT OPTION

Because previous rights :

GRANT USAGE ON *.* TO 'mySQLuser'@'localhost' IDENTIFIED BY PASSWORD 'pwd'

Do not seem to be enough.


Drupal 7: How can I get path for node or term in drupal with php code?

You can use the l() function to do this.

Example:

$link = l('Link Title', 'node/' . $node_id);
$link = l('Link Title', 'taxonomy/term/' . $term_id);


If you dont like what Drupal is doing by default for this preview feature, override it in your site theme, there is an example of this in the node_preview Drupal 7 API node_preview() comments.

the comment incorrectly titles the function THEME_Node_preview() it should all be lowercase

  /**
   *Output customized node preview on node edit and add forms.
   *
   * @return
   * This just outputs the Full node ignoring the teaser mode.
   */
  function YOURTHEME_node_preview($variables)
  {
      $node = $variables['node'];
      $elements = node_view($node, 'full');
      $full = drupal_render($elements);
      $output = '
';
      $output .= '
' . t('Preview of your posting') . '
';
      $output .= $full;
      $output .= "
\n";
      return $output;
  }

If that still doesn't look right you could try altering this code further to:

provide an override to node.tpl.php or node--preview.tpl.php using theme suggestions for drupal's theming layer functions.
alter the results of $full above using Regular Expressions to hack off the beginning and end of the HTML page content.


How to disable browser autocomplete for the login form

You can try:

$form['account']['name']['#attributes']['autocomplete'] = 'off';


Select field descriptive or numeric keys

The key|label format is for scenarios where you want to present a different, user-friendly, label that differs from the underlying, machine-readable, storage. For example, a country select list that you want represent in the 2-character ISO 3166-1 format while showing the official country names to present to the user selecting it.

In the above scenario, regardless of using the key|label format or not, the underlying data will be represented as a string (VARCHAR) since it's a Field (text) field type. If your underlying data needs to be represented as numeric, then you should use the List (Integer) (or other number types) field type as it will be stored as INT within the DB column.


The error message doesn't specify which field caused the validation error. In this case, the error is caused by setting the init field with a value that isn't a valid email address.
Differently from Drupal 7, in Drupal 8 the init field for the User entity is created using the email datatype. (See User::baseFieldDefinitions().)
$fields['init'] = BaseFieldDefinition::create('email')
  ->setLabel(t('Initial email'))
  ->setDescription(t('The email address used for initial account creation.'))
  ->setDefaultValue('');

Differently from the mail field, it doesn't get further constrains. (Compare the code used to create the init field with the following code.)
$fields['mail'] = BaseFieldDefinition::create('email')
  ->setLabel(t('Email'))
  ->setDescription(t('The email of this user.'))
  ->setDefaultValue('')
  ->addConstraint('UserMailUnique')
  ->addConstraint('UserMailRequired')
  ->addConstraint('ProtectedUserField');

Still, as any entity field whose datatype is email, it has a constrain defined in the annotation of that datatype.
@DataType(
   id = "email",
   label = @Translation("Email"),
   constraints = {"Email" = {}}
)

(The classes defining that constraint are EmailConstraint and EmailValidator.)
Setting the init field for the User entity is optional, but it's generally used from administrators of a site when users claim they created an account for which they cannot retrieve the password they lost.
Depending on the purpose of the code you are using, you can either set the init field, or not. If you set it, it must set to a valid email value.


Author Pane module contains appropriate templates files which control output.
author-pane.tpl.php is something that will help.

Just copy it in your theme directory, flush cache and do whatever you like with this file to customize Auth Pane block.

To remove 'Last seen:' from the pane comment or remove from the file

<?php /* Last active */ ?>
<?php if (!empty($last_active)): ?>

       <?php print t('Last seen'); ?>: <?php print t('!time ago', array('!time' => $last_active)); ?>

<?php endif; ?>

To shorten the display format of 'Join' find appropriate admin page (/admin/config/regional/date-time) and change Short date format to the format you prefer.

 * - $joined: Date the post author joined the site. (Uses shortdate format)


How can I show images upon click in a lightbox using the Full HTML text format?

I think the Lightbox is not really the best choice for Drupal 7. Have a look at the very powerfull Colorbox Module.


How to override user_picture per comment?

A dump of the $variables array is probably causing out-of-memory problems as preprocess variables in D8 can have some heavy depth to them.

Anyway, you can retrieve the image url from $user_picture render array which has a reference to the comment's user:

  $comment_user = $variables['user_picture']['#user'];
  if ($user_image = $comment_user->user_picture->first()) {
    $user_image_uri = $user_image->entity->uri->value;
  }


Commerce 2 - how to get guest user email from custom submit handler?

Found the way over the cart:
$store = \Drupal::service('commerce_store.current_store')->getStore();
$cart = \Drupal::service('commerce_cart.cart_provider')->getCart('default', $store);
$email = $cart->getEmail();


How might I show only the first level of an Exposed Taxonomy Filter in Views?

Add " Taxonomy: Term ID (with depth)" and set the depth to "1" it will show the first level of terms.

For Drupal 6:

Views Taxonomy: limit exposed dropdown by term depth module provides enhanced functionality for the exposed dropdown filter for taxonomy terms in Views.

  Exposed term filters can already be limited to display only terms
  selected in the Views interface. But what if content creators add new
  taxonomy terms? They will have to navigate the Views interface and add
  these new terms to the list of terms shown by exposed filters.


This module might do the trick:

http://drupal.org/project/menu_item_visibility

I've not installed it myself, but it seems to do what you're asking.


How to have two domains for same site, but site working in directory in second domain?

I think you have to check this module  https://www.drupal.org/project/domain
it has the solution for this


I solved the problem with this:

e.g. i have the path alias car/ilx-0 and i can get the tid easily, but what if i want to pass only the ilx-0 to another path view, like: products/ilx-0, the path alias doesn't match anymore so it's not easy to get the tid, to achieve that i used the following code on products/% view:

    <?php
    $pa=drupal_get_normal_path('car/'. arg(1, request_uri())); /* get the ilx-0 from products/ilx-0 and transform to taxonomy/term/tid */
    list($t1, $t2, $t3) = explode("/", $pa); /* Explode taxonomy/term/tid */
    /* $t1 = taxonomy */
    /* $t2 = term */
    return $t3; /* tid, return this value to get tid and pass to context filter*/
    ?>


How to have tpl for parent but not child?

You are editing in wrong template file. You have to make theme changes in user-profile.tpl.php.

For theme hook suggestions:

function themeName_preprocess_page(&$vars, $hook) {
  // Go to user page.

  // Requires devel module.
  dpm($vars['theme_hook_suggestions']);
}

There is a list of theme hooks in this page
Theme implementations is Drupal 7


Drupal 7: Cron claims webform module function to be undefined

That function is in a file that isn't included by default; you just need to include it yourself:

module_load_include('inc', 'webform', 'includes/webform.submissions');


How can I limit the password reset attempts?

You can use the Flood Control module for it.

Flood Control provides an administration interface for hidden flood
control variables, like the login attempt limiters and any future
hidden variables.


You say this happens with "the default Drupal front page" (that content feed). Realizing it now. The below is for those who have this problem with the front page set to display a specific node instead (at /admin/config/system/site-information).

Possible cause: using a multilingual variable for setting the front page content, and forgetting to update it. In that case, when visiting example.com/en, the Finnish version of the front page's node is displaying. However, when accessing that same node via (say) example.com/en/node/1, the English version would show.

Explanation. Normally, one URL is configured as alias for the frontpage at /admin/config/system/site-information. If this points to a content item with translations, they are shown as selected by the path prefix. With the multilingual variables however, one URL is configured per language version of the front page, completely overriding Drupal's normal language negotiation mechanism. The path prefix then selects the node given in the corresponding language version of the configuration option, even if that node is in a language not matching the path prefix. (Which leads to the funny effect that in the code rendering that front page node, $language is "wrong": it is that node's language, here and only here potentially different from the language selected by the path prefix.)

Fix. To fix this condition and preventing it from recurring:

Go through all translations of your frontpage node and set them to the same alias, let's say, home [source]. This should work, as each has a different language path prefix.
Go through the language versions of /admin/config/system/site-information and update all "Default front page" fields to contain home.
You probably have to repeat the last step for a new language after adding it. But I did not confirm this.

This whole multilingual variable thing is only to allow the front page being shown in different languages even when language is not selected by path prefix.

Or disable the multilingual versions of this variable altogether, by following this process in reverse.


control the view access permissions by field.tpl.php in D7

Never put any business logic into tpl files. They can be cached. So unless it's the "if odd, add class odd" type of logic, it may fail you miserably.
If you need more elaborate rules than Field Permissions give you, you need to implement hook_field_access($op, $field, $entity_type, $entity, $account) in your custom module.

Return value
TRUE if the operation is allowed, and FALSE if the operation is denied.

Field Permissions module is open source. You can see it's source to learn how this hook is supposed to be used. Same with User role field module. Both are pretty well commented in code, and can serve as good examples how to write your own custom logic. Just make sure you are not forking one, this may lead to more complications than it's worth - if they are not sufficient, inspire and even copy parts of code, but use your own name and info file.


How to not show a comments field if user logged in

Use hook_form_alter():

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == 'comment_form' && $user->uid != 0) {
    $form['field_email']['#access'] = FALSE;
  }
}


Get site name config value in page.html.twig template

I am only able to get null values when I try to get the value in the preprocess function.

Null values based on doing what exactly?

The site name, logo etc. was moved to a block, that's why it's no longer available out of the box. However, you can always add it back yourself and make it available in twig:

$variables['site_name'] = \Drupal::config('system.site')->get('name');


How do I enable comments for forum like statuses module?

You cant, the statuses module has quite a different concept and doesn't have anything to do with content-types commenting(e.g drupal forum), but if your problem is just to make your forum comments look like statuses, you can simply achieve that via some styling or templating your forum comment tpl file (better approach). for the sake of Ajax, you can use Ajax Comments module, but its not so much stable yet.
if you still need further help don't hesitate to ask!


Add/List/Edit paragraphs while add/edit node

I have been using the Paragraphs Collapsible module for a project with a big list of paragraphs to a node, and it works quite fine.

  Improves the Paragraphs widget by applying CSS tweaks and collapsible feature


how to pull data from view to file and attach to email

You have to use Views PDF module to output of views as PDF.
Use Mime Mail module to send email with attachment.

Write own custom logic to action performed or any rules.

Custom function to send mail as attachment visit here.

You may also check this


Allow all users to view all groups (private or public) with Organic groups, but not private content

List Private Organic Groups Publicly without giving access to the node page?
That post answered my question.  Thanks Damien Tournoud for posting the following answer:

  You can tell Views to ignore the access control of some of the Views.
  On Views 3.x, this parameter can be found under "Query Settings" /
  "Disable SQL rewriting", and is described as:

  Disabling SQL rewriting will disable node_access checks as well as
  other modules that implement hook_db_rewrite_sql(). The full nodes
  will stay private, so you should make sure not to link to them in the
  View so that your users do not land on "Access Denied" (403) pages.


phpcs rule or sniff for detecting usage of the "ksm()" or "kint()" function?

Yes, it is possible by Checking Drupal coding standards. You can configure PHP code sniffer to check for Drupal coding standards by following the instructions from https://www.drupal.org/docs/contributed-modules/code-review-module/installing-coder-sniffer and https://www.drupal.org/node/1587138
Edit: It turns out you can not identify all the debugging functions with standard Drupal Coding standard functions.In my testing drupalcs was able to identify only dpm()and dsm() functions but not ksm() or kint() .
There is an alternative way to identify debugging functions. You can add pre-commit hook to identify the debugging functions.
You can add the below script to git hooks.
#!/bin/sh

#
# Git pre-commit hook that prevents code that is not Drupal coding standard compliant of being committed.
#
# Fork of https://git.io/fNXBi by Dave Hall http://davehall.com.au
#

# Fetch the list of files that have changed.
FILES="$(git diff --staged --name-only HEAD --diff-filter=ACMRUXB)"

echo "Running PHP lint check" >&2
LINT_FAIL=0
for filename in $FILES; do
  if ! php -l $filename; then
    LINT_FAIL=1
  fi
done;

# There is no point in running PHP Code Sniffer on broken files.
if [ $LINT_FAIL -gt 0 ]; then
  echo "Commit aborted. Fix your code. Then 'git add' and 'git commit' again."
  exit 1
fi

echo "Running PHP Code Sniffer Checks" >&2
echo $FILES | xargs phpcs --standard=Drupal --extensions=php,module,inc,install,test,profile,theme,css,info,txt --ignore=node_modules,bower_components,vendor,*.md
if [ $? -eq 0 ]; then
 # Exit executing the git commit.
 exit 0
else
  # Ask what to do, not executing the commit. Source: https://unix.stackexchange.com/a/121255/139407
  read -p "Fix the marked Sniff violations automatically [Y/n]?" line </dev/tty
  case "$line" in
    y|Y) echo $FILES | xargs phpcbf --standard=Drupal --extensions=php,module,inc,install,test,profile,theme,css,info,txt --ignore=node_modules,bower_components,vendor,*.md
      ;;
    *) echo "No automatic corrections made."
      ;;
  esac

  echo "Commit aborted. Make remaining manual code fixes if necessary. Then 'git add' and 'git commit' again."
  exit 1
fi

Source : Drupal git pre-commit hook


Redirect links to nodes of past events to the up-to-date version

Rules and Redirect

Since you're already using Rules to automatically Unpublish past events, you could try adding an Action that creates a Redirect from the unpublished node path to the latest one. You'll need a Redirect module that provides Redirect actions. I haven't tried this but I expect Redirect module to have that.

Match Redirect

Or you could use the standalone solution Match Redirect.

Server side Redirect

Redirects don't have to be handled within Drupal. You could create Rewrite rules in your server configuration too.

But this all might be the solution for the wrong problem.

Better structure within Drupal

If the original event information doesn't change, and you only change the times, maybe you should structure it with 2 different content types, Event and Event instance or something that makes more sense.

The Event would hold everything except the times, and the Instances would only hold times. Then use Entity references to connect Instances to their Events.

Use Views to display Instances information on Events (Block or Attachment), you can use Views to filter out only future dates to display on Event nodes. And when marketing your event only ever share link to the Event node, that will always be showing correct relevant dates through the power of Views.

You can set your robots.txt to not index Instance content nodes on search engines, and in general don't link to them or show them to the users, only use the Instance information on Event nodes.

Or if you have per-date relevant information for the event (comments or similar), store it on the Instance node, and then again with the power of Views you can list past event info on the Event node itself, if anyone wants to read, look at past image gallery or similar.

That way you'd have both the future and past info available to be displayed how you want them, and only one Event link for marketing that would probably even be beneficial for SEO ranking.


Disable ajax from exposed form filter only

You can use better exposed filter module for this
Set Use AJAX to Yes under Advanced -> other section
Set Exposed form style to Better Exposed Filters and keep auto submit option disabled in BEF Settings.


How can I write SelectQuery for SELECT LAST_INSERT_ID()?

Although the original query has no table name, db_select() would expect the table name.
The following works perfectly assuming the insert operation took place in another hook and the last insert id is not available into my hook:

$query = db_select('mytable');
$query->addExpression('LAST_INSERT_ID()', 'last_id');

$result = $query->execute()->fetch();
print $query;
echo '<br>';
echo 'Insert ID: '.$result->last_id;

Query output:

SELECT LAST_INSERT_ID() AS last_id FROM {mytable} mytable


Where does the $node get its field values after a node edit page has been submitted?

It looks like the actual work to attach the fields to entity objects is done in the _field_invoke() function, right at the bottom with these lines:

if ($items !== array() || isset($entity->{$field_name}[$langcode])) {
  $entity->{$field_name}[$langcode] = $items;
}

That doesn't make a lot of sense out of context so it's worth having a look at the whole code for the function.

The basic workflow is:

The node form submit handler calls field_attach_submit()
field_attach_submit() calls _field_invoke_default()
_field_invoke_default() calls _field_invoke()

The entity object is passed through all of those functions and once they're run all fields are attached to the object.

I know it's not much to go on but hope it helps.


How to use Rules to send an email to an email id based on a selected in a registration form?

You should be able to get this to work by creating a single rule using the Conditional Rules module (and Rules of course). The rule should be trigger by Rules Event "after saving a new user account".

For some samples to put together such rule (in Rules export format), refer to my answer to either of these questions:

How to set the values of some fields depending on the value of a list box?
How to specify a Rules condition related to select list values?

The actual Rules Action you want to use, should be pretty similar to the Rules Action included in my answer to "How to send an email via a Rules action using a field key?".


Send Email using rules or other module depending on a field value?

You would need to expose the node's field using the condition "entity has field" as the very first condition. Then Rules will allow you to select the field in the condition "data comparison".


How to store data in database with Form API?

To use your own form submit handler, you should not use system_settings_form in your form, instead just return your form.

If you are just going to save your value in your submit handler, go with system_settings_form.
To get the values, use variable_get('your form field name'). In your case, you can use variable_get('media_skins_test');


IP addresses are stored in the hostname field of the comment entity (which you'd usually find in the comment_field_data table).

This functionality is disabled by default, though (see Stop logging comment IP addresses by default). To enable it, it looks like you need to set the config manually, e.g.

 \Drupal::configFactory()->getEditable('comment.settings')
   ->set('log_ip_addresses', TRUE)
   ->save(TRUE);

After running that, IP addresses will start being logged in the hostname field.


function _get_emp_name(){
 global $base_url;
  $current_url = $base_url . request_uri();
  $url_sub = substr($current_url, 0, explode('&', $current_url));
  $to_array = explode('&', $current_url);
  $ar_name = explode("/", $to_array[1], 2);
  $node = node_load($ar_name[1]);
  $name = $node->title;
  return $name;

}

Then with form_alter I use:

$form['field_employee']['und'][0]['target_id']['#default_value'] = _get_emp_name();


What module is used to create the table of contents in Drupal documentation?

That block is the "Book navigation" block implemented by the Book module in book_block_view(), and defined in book_block_info().

The copyright block that appears right after the "Book navigation" block is implemented in drupalorg_handbook.module, which is a custom module used to run Drupal.org, and its sub-domains.


It depends greatly on which version of Core you are using. The main memory issue is with Token module for Drupal 6, when given a node will generate all possible tokens for that node, regardless of the tokens that will actually be replaced. This means that expensive tokens that need to load or render other objects, etc, in addition with the sheer amount of tokens generated causes the issues.

With Drupal 7, the improved token API only generates tokens that you actually use and greatly improves performance and memory usage. In normal use, Pathauto really only matters when an item is being saved but does not affect "normal" page views.


D8 Views - Contextual Filter by Month & Year? (Content date field)

Remove your date contextual filter, by clicking remove.
click Add a contextual filter, and search for the date field and select the "Year+month" granularity. Then click add.

once you are done you should have your contextual filter look like this:

Now you can go events/201807 and it would give you the same results.

update: this granularity is available for all date fields under the contextual filter option (node.field_somedatefield (year_month) provided the field has been added normally using content types manage fields section:


How to implement a searchable addresses database (for a form)?

My first approach would be to build a basic importer using the BatchAPI and create a custom entity to hold the address data (NOT a content type), combined with Address Field for proper storage.

Then, I would use Search API and Search API Solr to index and store those entities, afterwhich you can build custom forms with Form API or use Views to expose and search the index - which will be much faster than Drupal db queries. Whenever possible, keep MySQL from doing work, as this is what will bog down your site.

This keeps things close to "Drupal native" while solving many of the performance issues you raised with Solr.

You can use Form API to build forms with #ajax callbacks to query and return data from Search API queries as well.

The import will never be lightning fast unless you're not using the Drupal API to store them as entities. When you don't store them as entities, you lose a lot of the flexibility of say, plugging into Views or Search API without a decent bit of work. You couldn't also add fields with field API, at that point it's just flat data, so say goodbye to easy addition of taxonomy fields or using Address Field.

With Solr constantly indexing new and updated entities, having the import be lightning fast isn't really a priority (IMO) as long as it is reasonable. If you have millions of addresses, Drupal will only be able to parse rows so fast, and a lot of this is due to the event system (save an entity, fields attach, hooks fire, alters fire, etc) on every call to entity_save. The price you pay in speed here is paid off later when you want to manipulate or integrate that data with the contrib space.

The gist I linked to was an experiment I was doing with the Data module and CSV files. This loads the entire CSV file and dumps its contents into MySQL using load infile. This will plant data into a database very quickly, but, as I said, you will have a lot more work trying to get Drupal to recognize, communicate with, and extend that data.

Another approach, totally non-Drupal, would be to import the data to a PostgreSQL (9.4+) database or a no-SQL equivalent, possibly even something like Firebase, and execute searches against that. Then again, this is almost the same as doing Search API + Search API Solr, except you'd have to build the wrappers to create and send queries to those servers. So, it is still valid to offload all of this work in a separate system just to crunch data. It really depends on how much programming you feel like doing.

Just to be clear, there are a handful of options here, it just depends on how much you can stomach if it doesn't use Drupal in some way. Personally, I would not want to give up the flexibility the Drupal API provides in terms of understanding your data model, and therefore, I would create a custom entity and start there. It will be slower, but in the end provide more points of integration for you in the module ecosystem.


Some hooks you can call inside template.php, but not all hooks - it really depends on what you're doing. If you keep it mostly theming related (altering data output, adding CSS, form alters, etc), you should be okay. A hook like hook_search_api_query_alter wouldn't work.


AJAXifying content and pagination problems

Try this below solution with views pager ajax enable.

jQuery 1.7+ Version

function runthiscode() {
  $(".pager a").each(function(){
    $(".pager a").addClass("ajax-link");
    $(".pager a").attr('rel', '#content')
  });
}

$(document ).ready(function() {
  runthiscode();
});

$(document ).ajaxComplete(function() {
  runthiscode();
});


How to set Panel to homepage when setting the panel's path as homepage on Configuration > Site Information doesn't work?

I dont know what programes interferring the home page redirect.
However, you can try variable_set('site_frontpage', 'front-page-panel-url');

http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/variable_set


Yes It is possible. Core patch is required to fix this issue. It will fix node JSON structure and attach block_content to json files.
See my comment #63 for details:
https://www.drupal.org/project/drupal/issues/2942975#comment-13315805


assigning a role to a user programatically

$uid = 123;// User ID of user that you want to add role to.
$role_name = 'Role to add'; // The name of the role to add.
if ($role = user_role_load_by_name($role_name)) {
  user_multiple_role_edit(array($uid), 'add_role', $role->rid);
}

Is how you should do it in Drupal 7. See https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_multiple_role_edit/7