How to move a taxonomy term from one vocabulary to another?

Term merge module seems to be what you are looking for. Just adding some features as is from its project page on D.O.

Updating term references in the field values, swapping values from the branch term to the trunk term. We support taxonomy term reference, entity reference, and any other field types that correctly define their foreign keys.
Keeping/Removing branch terms: you decide whether to keep or remove branch terms after the merge.
Merging field values: you can specify a list of fields and during merge the values of those fields from branch terms will be added to the values of the trunk term. This way you can keep field values of the branch terms after deleting them.

So all you'll need to do is to create a new term to that other vocabulary and do a merge with the old term from the other vocabulary. As for the tid I don't think that is possible to be kept or even if there is any meaning in trying to do so since all data will be transferred to the new term.


append settings.php during profile installation

Checkout this post about Collecting and writing configuration settings to setting.php from an install profile.

It describes how a custom task (via hook_install_tasks_alter()) was injected into the installation profile to display a custom form and, upon submission, how drupal_rewrite_settings() can be used to inject the custom settings into settings.php.


How can I hide the title in my user registration form?

Use disable/hide title module. Alternatively, you can disable the title pretty easily with css.
Another way is to disable the title using template.php using drupal_set_title()


How to configure htaccess to redirect ALL traffic through https?

You could use something like this:

 RewriteCond %{HTTPS} !=on
 RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L,NE]


Why can 'Others' read settings.php by default?

The reason for this default, I believe, is because on some hos plans (e.g. bargain basement shared hosting), the web server user is not by default the owner of the file.  On some hosting plans, it may not even be an option to use commands such as chown and chmod to set up things exactly the way you want.

The web server user must be able to read this file to get access to DB credentials, and on such hosting plans, allowing "Other" to read is the only way to achieve that.  (Having 400 as the default would most certainly create a deluge of support requests from people unable to figure out why Drupal can't access their database.)

If you know what you're doing, it is OK to 1) make sure the file is owned by the web server user, and 2) set permissions to 400.


The website encountered an unexpected error due to installing custom module

It looks like a simple naming error. Your route name in the links file is:

route_name : mymodule.admin_form

But in your routing.yml you have:

 mymodule.settings:

Update one or the other so they both match, clear the cache, and it should work.


http://www.webbykat.com/2012/02/creating-monthly-archive-block-drupal-7-views While not taxonomy should work. Change the content type from node to taxonomy and as you create it it will be archived. You may need to ad a date entity to the taxonomy and have rules or trigger put in a creation date since I don't believe they are creation date stamped.


Using Ajax-Callback with ajax_command_invoke to invoke custom jQuery command

Using drupal_add_js() in an AJAX callback will (at best) have weird results. Come to think of it I'm not sure I've ever actually seen it work.

The simplest solution is to add the JS in the form function itself, that way it'll always be available regardless of the AJAX state of the page:

function MYMODULE_some_form($form, &$form_state) {
  // Moved from the AJAX callback to here.
  $form['#attached']['js'][drupal_get_path('module', '<...>') . '/js/jquery_plugins.js'] = array();

  // ... Rest of the form
}


Decryption failed because the HMAC could not be validated while decrypt

I have found below solution. I have un-serialized encrypted data. Found below details.

Used above input to decrypt function.

$options = array();
$method = 'mcrypt_aes_cbc';
$key_provider = 'drupal_variable';
$config = array('provider_settings' => array('method' => 'variable_contents')); // I have updated method name later.
decrypt('encrypted_text', $options, $method, $key_provider, $config); // It works now :)


How to implement Administration UI notifications for new revisions?

Eventually decided on using the Flag module for this since it seems less bulky than other workflow alternatives. It also allows us to use flags for other things as well and am quite happy with how easy it is to setup with Rules. I have to do code some of the display we want but it seems worth it. Thank you for your suggestions!


How can I remove Features modules from a site without affecting functionality?

When you are absolutely sure there is no custom code in the feature module you can safely recreate the feature by going to /admin/structure/features and then change permissions and/or disable modules such as the Overlay module that are declared as a dependency in the feature.

You can recreate the feature and remove the unwanted components:

Go to /admin/structure/features
Click the 'Recreate' button next to the feature
Uncheck all dependencies or other components that you don't want in the Feature.
Click the 'Download feature' button.
Replace the Feature module in your modules folder.

When you are not sure there is any custom code in the feature module do this on a local environment and check all changed code via Git to make sure only the components you deselected are removed from the feature module.


How to deny certain terms from being allowed in autocomplete field?

You should be able to create a custom module that uses taxonomy_autocomplete_validate to validate the input on node_presave and/or node_save. You would just need to define a list of banned terms, either directly in the module, or from an included file that could be more easily maintained.

You could always go one step further and build an administrative interface within the module, but that's probably veering too far away from your question.


I think that in your case, you can insert easyly your own PHP snippets in a common content type to be executed and displayed.

For run your own code from a node you can enable the PHP filter module (it is already in Drupal core, so you does not need download, just enable). this module allows embedded PHP code/snippets to be evaluated. And then, for syntax highlighting of your code, there are several alternatives of modules like:

http://drupal.org/project/geshifilter GeSHi Filter module, for D6 and D7. In this page you will find links to modules alternatives. I have tested this module in drupal 6. Follow the readme.txt instructions. According my test you can show your code (inside respective tags to show code) and run PHP code (copy/paste your code after your code to show, outside the tags to show code). this is an example:

<code type="php">
<?php
echo "hello world";
?>
</code>

<?php
echo "hello world";
?>

and this is the output:

http://drupal.org/project/wysiwyg_syntaxhl (for tinyMCE rich text editor) for D6. This alternative seems not listed in Geshi Filter page.

I hope this information be useful.


drupal site crash and went to maintenance mode

It's quite possible that your server crashed (ran out of memory).  You can start by restarting MySQL, otherwise just restart the entire server to get things going again.


Out of the box, it's stored in the database, in a number of tables names cache_[name_of_bin].

There are lots of other options if one wants to configure it differently.

Memcache
MongoDB A nice feature is that mongo supports replication across multiple databases
APC
Varnish Doesn't replace normal caching, but integrates with Varnish so Varnish can invalidate cache when Drupal does
Boost Can generate static HTML files from content.

Also see Lullabots Beginners guide to caching data in drupal 7 (Thanks  Chapabu!).


Webform 'add element' and 'addpage' buttons do not appear

You need to go to admin/config/development/performance and clear the cache.
Add element and add page will appear.


Display Image logo along with site slogan and site name

I would recommend to use the "Panels" module to do that. Create a "mini-panel" and while editing one of it's panes (boxes of content) choose on the edit menu "Page elements" and then add "Logo, "Site name", and "Site slogan" respectively. Make sure you arrange them as your liking.

The second part of your work is to do some CSS for this. The Panels css system takes some time to learn --- You should use DOM tags carefully to isolate the Id's and classes of the right div's and manipulate them in relation to their upper div's, but it's worth the shot.

If your site is responsive you should add some responsiveness with a Media query, i.e:

@media screen and (max-width:519px) {#panel-col-first {width:100%;} #panel-col-last {width: 100%;}}

In Panels, make sure that after you choose basic details and layout you navigate in "content" tab. Then, Add the aforementioned details - Here is a screen that'll show you how:


Customize Checkout Look and Feel

There was a recent commit that made the checkout process table-less in the Commerce Issue Que. It was reverted in favor of making such a large change to the codebase on a 2.x release. That code still exists and it's all possible using theme_ functions in your template.php

Go here
/modules/checkout/includes/commerce_checkout.pages.inc and look for functions that start with theme_
Add those functions that you
want to your template.php in your theme or a custom module
Change the function word "theme" with your theme name or module name.
Make an obvious change or two
Clear all caches and
then go through the checkout process.


Webform 6x 3.11 - custom code to determine value of webform field

We had exactly the same issue when we were developing a custom job application online form, and we wanted to pass in the job details into the webform in question. How we solved it:

Created (job application) webform node
Created links to the webform node above in the form of /apply-online?n=17
Created custom node-856.tpl.php (856 happened to be the node of the apply online webform) to

first validate the nid as a valid job
validate that the job is published
validate that the job had not closed
format the additional fields into the webform such as title, position etc etc
stop any URL tampering

Created a custom webform validation hook to ensure that only published nodes of type 'job' were allowed to ever be submitted (to stop any form tampering)

Sample code for the validation hook:

/**
 *  Implementation of hook_form_alter()
 *  This function is used to add an extra validation function to the apply online webform
 */
function site_profile_form_webform_client_form_856_alter(&$form, &$form_state)  {
  $form['#validate'][] = 'site_profile_validate';
}

/*
 *  Implementation of hook_validate()
 *  Doesn't exactly validate the webform as that's done in another validation function
 *  This takes the nid from the job_url field and turns it into a url.
 */
function site_profile_validate($form, &$form_state) {
  global $base_url;

  $nid = $form_state['values']['submitted']['job_url'];
  $node = node_load($nid);
  $job_url = $base_url . url('node/' . $nid);
  $form_state['values']['submitted']['job_url'] = $job_url;

  //need this to stop the form losing the nid argument in the url
  if (empty($form_state['values']['submitted']['cv']['_fid']) || empty($form_state['values']['submitted']['cover_letter']['_fid']) || empty($form_state['values']['submitted']['completed_application_form']['_fid'])) {
    drupal_goto('apply-online', array('n' => $nid));
  }
}

Sample code for the node-856.tpl.php:

  // job's apply online node ID = 856, this template was made to theme this
  // particular page

  $job_nid = $_GET['n'];
  if (!is_numeric($job_nid)) {
   drupal_access_denied();
   exit;
  }
  $job_node = node_load($job_nid);
  if ($job_node->type != 'job') {
    drupal_access_denied();
    exit;
  }
<div id="node-<?php print $node->nid; ?>" class="node<?php if (!$status) { print ' node-unpublished'; } ?>">

<?php print t('Job Title'); ?>

<?php print $job_node->title; ?>

<?php print t('Vacancy Number'); ?>

<?php print $job_node->field_number[0]['value']; ?>

<?php print t('Closing Date'); ?>

<?php print $closing_date; ?>

<?php print t('Job Summary'); ?>

<?php print $job_node->teaser; ?>

Hope this helps


How to create a component which has specific content on each page

So, you need admin to be able to add one or two piece of content to a specific page.

Let's say you have content type Product content type.
For the custom content you can create a new content type, let's say Banner. Consists of these fields:

Title
Description
Image
Link
Reference to Product

Then you can simply create a Views which lists all Banners which have a reference to the current Product in the page. (Using contextual filters and the referenced field)

All Admin needs to do is to creates a Banner and indicate the Product to be displayed in.

You can also check Prepoulate module, for letting admin create the Banner straight from the Product edit page.


hook_menu_links_discovered_alter() not being called

Generally, alter hooks are invoked even if they are implemented in themes, but to be sure you always need to check the code invoking the specific alter hook.
In this case, hook_menu_links_discovered_alter() is invoked from MenuLinkManager::getDefinitions. You can see this by clicking on 1 invocation of hook_menu_links_discovered_alter().

That method only invokes the hook implemented by modules, as it uses the following code to invoke it.

  $this->moduleHandler->alter('menu_links_discovered', $definitions);

To allow themes to alter those links, the code should contain a line similar to the following one, where $this->themeManager is an object implementing the ThemeManagerInterface interface.

  $this->themeManager->alter('menu_links_discovered', $definitions);

In short, you can only implement hook_menu_links_discovered_alter() in a module.


How to join a path to a file in code, "windows safe"

Just use / as path separator: It will work on Windows, and any other OS.

PHP defines the DIRECTORY_SEPARATOR constant, but that constant is not used from Drupal core code, and Drupal works on Windows too.
A note on the parameters accepted from basename() says:

  On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).


how to add html/ccs element s inside drupal mail function

Your way will work if you enable the html format for email in your website. By using http://drupal.org/project/htmlmail or http://drupal.org/project/mimemail that will help you format the email in html and choose which method that will use for sending email.


Outputting a link as a button in node.tpl.php

This is what ultimately worked for me. I don't really understand it completely, but if anyone can shed some light on why it worked, I would really like to know.

<a class="btn btn-danger btn-lg" target="_blank" href="<?php print $content['field_amazon_link']['#items']['0']['url']; ?>">Buy Now


Is there a way to show the content of a field taken from the user profile in the comment.tpl.php file?

The comment.tpl.php template file receive a $comment value, which contains the comment object. Between its properties, there is $comment->uid, which can be used to get the user object for the author of the comment, with user_load($comment->uid). If you are instead interested in the author of the node containing the comment, then you can use the following code.

$node = node_load($comment->nid);
$uid = $node->uid;
if ($uid) {
  $user = user_load($uid);
}

In both the cases, the code should be used in the preprocess function, not in the template file used for the comments. In this case, $variables['comment']->uid, and $variables['comment']->nid are instead used.


Allowing HTML in block title - where is $block->subject created?

You may be interested in Block Class Styles, which has an additional feature:

  Allows the ability to set a global text format for custom block
  titles; this allows you to now have HTML in your custom block titles.
  Yes, you can now have block titles that contain HTML markup!


Drupal's Core Url has a static fromUri() method (see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/function/Url%3A%3AfromUri/8.2.x)
With that in mind you should be able to swap out the ['#url'] with a new one thusly:
...['#url'] = \Drupal\Core\Url::fromUri('externalURL');


Why Drupal 7 takes too time in connecting to mysql db? - measured with xdebugger

This is a good group for you to join on groups.drupal.org
http://groups.drupal.org/drupal-windows

Looking at this post it sounds like the issue you are describing: http://groups.drupal.org/node/242443.

  Make sure that your Drupal settings.php connection string uses the IP
  address of your MySQL server (e.g. 127.0.0.1 for your local Windows
  machine), not 'localhost'.


From what i understand, you are most probably doing it wrong :).

If you want to change the node display, have a look at the Display Suite.

If you insist on changing it with views, you might want to switch to a page display, set the path to node/nid to override the default node view and do what you need there.


how to view data row table related to user only?

To create a view that is limited to content created by the current user (logged in) and Admin:

create the view as you normally would
Under Advanced, Relationship, create a relationship to Content:Author
Create a Filter, User:Current, Logged in Yes, using the author relationship
Create a filter, Author ID = admin
Create a Filter Group (click on arrow next to Add on Filter Criteria)
'Create a new filter group' and make it look something like this:

This will limit the view to content only created by the currently logged in user and/or Admin, but does not limit access to the nodes themselves, for that you will need a module such as Node Access:

  Nodeaccess is a Drupal access control module which provides view, edit
  and delete access to nodes. Users with the 'grant node permissions'
  permission will have a grant tab on node pages which allows them to
  grant access to that node by user or role. Administrators can set
  default access controls per content type, and also define which roles
  are available to grant permissions to on the node grants tab.


How to display the rendered entity of entities flagged with a Search API view?

Have you tried to change the configuration of the Format section ?

Instead of "Fields" you might be able to select "Rendered entity" and then under Settings link, you will be able to choose a view mode like "Teaser".


Prepare Drupal to be multilingual in the future

I think the best approach is something similar to your first one.

Install Drupal in English as defaults
Configure your environment for multilingual at the beginning.
Enable Italian Language
Set Italian to default language
When you create entities(Users, Content types, Etc..), configure everything at the beginning. Otherwise you might forget things later.
Enable multilingual support only for other pages excepting admin pages @ admin/config/regional/i18n/select (Under "ENABLE FOR SPECIFIC PAGES" set all pages except "admin/*")
Then do everything in Italian for Italian until you need English language stuffs.

Good luck.


For a personal-use module, what would be good practice for database tables?

Creating tables to go along with a custom module is acceptable and perhaps event "best practice" in the Drupal world. Using a separate database would require an additional connection via PHP which I suspect would be a waste of server memory but an option if you insist on doing so. Often there's no one "right" answer in Drupal. There are of course "best practices" which I encourage you to follow but there's a lot of room for personal style.


The reason for what you experiencing is the default behavior of token_replace() to leave tokens untouched if no replacement value was provided.

In your case, the Token Filter module would have to provide the option 'clear' => true when calling token_replace().

You may want to try to apply the patch in this issue to the token_filter module.


PDOException "column not found" but does exist

Concatenating variables into an SQL query is usually a bad idea (search for SQL injection and you'll see why). The D6 version you're starting with:

$result = db_result(db_query("SELECT value FROM {variable} WHERE name = '%s'", $variable));

uses parameters, you just need to convert that to use the newer query substitution in D7. The docs for db_query() have some good examples, essentially what you need for this particular query is:

$query = 'SELECT value FROM {variable} WHERE name = :name';
$params = array(':name' => $variable);
$result = db_query($query, $params)->fetchField();


How can I serve a separate CSS file for Internet Explorer?

Use drupal_add_css with the option 'browsers'.

drupal_add_css(
  path_to_theme() . '/ie.css',
  array(
    'browsers' => array(
      'IE' => 'lte IE 9',
      '!IE' => FALSE
    )
  )
);

You should add this function call in your theme's template.php file through template_preprocess_html like this:

function MYTHEME_preprocess_html(&$vars){
  drupal_add_css(
      path_to_theme() . '/css/ie.css',
      array(
        'browsers' => array(
          'IE' => 'lte IE 9',
          '!IE' => FALSE
        )
      )
    );
}


How to override theme for quicktabs which actually renders a view

As Sunil says you are probably using view variables in your block template

Perhaps look for another template to override further down in order to find a views template to override and use your html/twig code

Here is what I would do.

Find the first template inside views-view.html.twig in my case it is views-view-unformatted.html.twig (red arrow above) and copy it in your theme templates folder.  Clear cache and make sure it is used and than explore the possibility of renaming it to be specific and used only for the quicktabs block.

See here for more info on how to name your templates


How can I programmatically get the admin theme

This is config and you can get it with the following snippet.

$admin_theme = \Drupal::config('system.theme')->get('admin');
$admin_theme_name = \Drupal::service('theme_handler')->getName($admin_theme);

Or with Drush:

drush cget system.theme admin


AJAX loading of a view on click of a button?

Views Modes

  A Drupal Views display plugin which provides alternate display modes
  that can be switched to for a single View. This allows exposed filter
  parameters or contextual filters to be kept active while switching
  display mode.

Sounds like this module does what you're trying to do. There's only a dev version, but might be worth a look.


Problem installing in local "The translation server is offline"

I think you didn't select English in the first step, and probably your Internet connection is behind a proxy and I guess Drupal doesn't support it.

You can select English and continue or:

Go to Translation server and download the specific language, the Spanish for example

Copy the download file in sites/default/files/translations
Continue with installation


Returning custom array in lazy builder callback

I have to return a custom array from a lazy builder callback

You can return multiple #markup elements nested in the render array, also other render elements like #plain_text, which is more safe to output a title containing user input:
  'title' => ['#plain_text' => $var->getTitle()],

For the body field you need a more complex render element, see How to safely render node body on a custom variable?

and then loop through that array in a Twig template

You can't loop through the array in the theme because you have set-up the variable to be lazy-built. The array doesn't exist at this point, only the placeholder. The array needs to be a proper render array which can be rendered recursively as explained above.

If that's not possible it would be also OK if a lazy loaded the whole
block not just the content inside it.

Blocks are lazy-built by default and placeholdered when meeting the auto-placeholder conditions. See https://www.drupal.org/docs/8/api/render-api/auto-placeholdering


just installed 7.12 - but got stuck - how to access the backend and login

You won't be able to get the password from the database, but you will be able to get the email address for user 1 and then request a new password by email.

Have a look in the users table for the email address for the entry with a uid of 1. Then go to http://mysite.com/user/password, pop in that email address, and wait for instructions to be emailed to you.

After you've re-gained access to the site you can log back in again at any time by going to http://mysite.com/user. The admin backend will most likely be at http://mysite.com/admin, unless someone has changed it (this is unlikely).

The errors you got during install are because of a UNIX limit on the number of open files/file descriptors in the system. Take a look at this article for some suggestions on how to increase that limit so you don't run into the same error again.

It might be that you need to raise this limit and then re-install the site again...I'm not sure if the errors you've received will have stopped the site from being installed properly or not.


How to add an ascending row number (using some token) in front of each row in Views?

In your View add a new Field, Filter by Global and select:

  Global: View result counter

  Displays the actual position of the view result

Click the Apply button and if you want change the output select Rewrite the output of this field in the Rewrite results section, and in the Replacement patterns section you will see the [counter] token as:

  [counter] == Global: View result counter


Extract all images out from each node in content type

Which book runs right before a node is published?

hook_node_update($node) The hook is invoked after the node is inserted/updated in the node table

  What's the best way of saving those URLs in the database?

It totally depends upon your needs, Simply you will have to save in database in your own table(s).

  Which Drupal function do I use to retrieve those URLs?

It is not clear from where you want to retrieve. Database or Node Body.

For database you need to focus on Database abstraction layer
For Node body, you will have to parse some way e.g. PHP Simple Dom Parser


How to programatically resize image and respect aspect ratio when saving a node

image_scale() will do this if you just provide a width or a height rather than both.


Use image scale and crop in custom function

You problem is image_load($img_url) is returning FALSE, which is not an object.

$filename = $bjt_img;
$img_url = "http://www.mydomain.com/uploads/".$filename;
if (isset($myimg = image_load($img_url)) {
  $myimg_scaled = image_scale_and_crop($myimg, 100, 80);
  print '<img src="'.$myimg_scaled.'">'
}
else {
  print 'error'
}

Plus I think it must be a file,  not a url to a file


Stripe_InvalidRequestError: You cannot use a Stripe token more than once

OK I have figured it out, when the form code is running, it runs multiple times, to stop it I added a variable to $form_state so the top of my code above becomes:

Stripe::setApiKey($stripe['secret_key']);

if (!empty($form_state['input']) && !isset($form_state['processed'])) {
  $form_state['processed'] = TRUE;


Give a basic page a different appereance by rendering it with views

The Theme Key module enabled me, to do what I was looking for: enable a different theme per page based on certain criteria (like mobile browser e.g.).


Adding a theme suggestion programatically

A module that implements hook_preprocess_page() or hook_preprocess_node() can suggest new template files by altering the variable $variables['theme_hook_suggestions'].

The code contained in template_preprocess_page() that initialize that variable is the following.

// Populate the page template suggestions.
if ($suggestions = theme_get_suggestions(arg(), 'page')) {
  $variables['theme_hook_suggestions'] = $suggestions;
}

Each theme suggestion needs to match with an entry returned by hook_theme().

In Views, there should be an equivalent preprocess function to use in the similar way, or a way that allows to hook_preprocess_page() that allows to the function to understand if the page is associated with a view.


Why some functionality of my drupal site is different on different PCs?

The origin of the issue was Jquery Conflict. After defining different reference variables, my problem is free.


I want to show the limited amount of products using JCarousel module?

The solution is to add the following code around line 147 of jcarousel.views.inc

if ($view->query->pager->options['items_per_page'] != 0){
    $count = min($view->query->pager->options['items_per_page'], $count);
}

You can read more about the issue at https://www.drupal.org/node/2408883


How do I add conditional shipping cost to an order?

Here the idea,

Using hook_checkout_pane() include your option Residential Delivery Fee as checkbox
Then while saving order check if user selected this option. Use hook_order
If user chose this option, you can add your shipping charge as line item with the function uc_order_line_item_add().

foreg:

function hook_order(){
switch ($op) {
.....................
case 'save':
if($arg1->residential){
//if the checkbox was selected, we add the line item to the order. the following function  will add 100 to order total as shipping charge
uc_order_line_item_add
    (
      $arg1->order_id,
      'shipping',
      t('Residential Delivery Fee'),
      100,
      NULL,
      array ()
    );

 }
}


How to modify user messages without hacking core user module?

You can't override an .inc file by copying it to your theme, but you can override most of the function with your template.php; for example, any form can be altered using hook_form_alter(), or any function whose name starts with "theme" can be override by using  YOURTHEME_functionaname() in your theme template.php.


Creating date field with only month and year

We can make this in a hook_form_alter.
$form['DATE_FIELD_MACHINE_NAME']['widget'][0]['value']['#date_date_element'] = 'month';
$form['DATE_FIELD_MACHINE_NAME']['widget'][0]['value']['#date_date_format'] = 'Y-m';

However, there is still a problem of this way:  instead of first day of the month, current day will be saved. I cannot figure out how to solve.


Its a syntax error, generated because you're missing some parenthesis or other required syntax. Do you have a semicolon at the end of return 'users/'.$user->name?
Should be:
'users/'.$user->name;


Single Sign On Integration with NetCommunity

The last time I looked into BBNC (which was two or three years ago), you had to do a two-fold approach.

First, you need to write an ASP.NET webservice on the BBNC side using their API to expose login.  This may have changed since I checked it out.  Poke around the BBNC forums to see what may already exists.

Two, you wire up authenticate against a non-drupal database.  This is actually fairly easy.  I would look at the LDAP module to see how it does things.  It essentially hook_form_alter's the user_login form to add some additional validation, which checks the external database.

I would also poke through the BBNC forums to see if anyone has an LDAP, OAuth, or OpenID solution for NC.  Then you can use one of the existing solutions.  Those three modules are also good to look through for ideas on how to  do the authentication.

The question that @indrock gives is also a good read about session management.


How to edit content of panels Custom text that was made reusable?

If you go into the panels from the structure menu... you will see "Manage custom content" on the top right.


What's the difference between the "Mime Mail" and "Mail MIME" modules?

There are many more than 2 ways to send mail with Drupal. But, the modules you are showing are not for sending mail at all, they are there only to encode / decode mime content.

The problem you are facing is common in Drupal land: Developers re-inventing the wheel. You will often bump into modules that do similar tasks.

Mime mail has more support, is much more active, and has more features, (it can decode incoming html mail if I understood correctly).   I would go for this over Mail Mime with HTML Mail Pear class.

As for sending the emails, I can strongly recommend SMTP Authentication module if you don't want to use Drupal's built-in mechanism.

Hope this helps, cheers!


This is done in template_preprocess_node() in node.module on line 1451 (http://api.drupal.org/api/drupal/modules%21node%21node.module/function/template_preprocess_node/7).

function template_preprocess_node(&$variables) {
  ...
  $variables['node_url']  = url($uri['path'], $uri['options']);
  ...

You could change it to anything else in your own module in mymodule_preprocess_node() function like so:

function mymodule_preprocess_node(&$variables) {
  $variables['node_url'] = 'some/other/path';
}


Simple: How do I add data into custom field while creating new user with user_save

I had the a similar problem. This code helped me.
I put this code in myform_submit.

$fieldvalue = $form_state['values']['fieldname'];

//Loading the user object

$account = user_load($GLOBALS['user']->uid);

//Gettin the user data

$edit['data']['fieldname'] = $fieldvalue;

//saving the achieved data

user_save($account, $edit);

//Retrieving the user value

global $user;
$whatever = $user->data['fieldname'];


I needed the same thing. Unfortunately there is nothing for it yet so I had to create something for time being. It is not pretty but it works so I don't care.

/**
 * Returns renderable array of taxonomy terms from Categories vocabulary in
 * hierarchical structure ready to be rendered as html list.
 *
 * @param int $parent
 *   The ID of the parent taxonomy term.
 *
 * @param int $max_depth
 *   The max depth up to which to look up children.
 *
 * @param string $route_name
 *   The name of the route to be used for link generation.
 *   Taxonomy term(ID) will be provided as route parameter.
 *
 * @return array
 */
function mymodule_categories_tree($parent = 0, $max_depth = NULL, $route_name = 'mymodule.category.view') {
  // Load terms
  $tree = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree('categories', $parent, $max_depth);

  // Make sure there are terms to work with.
  if (empty($tree)) {
    return [];
  }

  // Sort tree by depth so we can easily find out the deepest level
  uasort($tree, function($a, $b) {
    // Change objects to array
    return \Drupal\Component\Utility\SortArray::sortByKeyInt((array) $a, (array) $b, 'depth');
  });

  // Get the value of the deepest term
  $deepest = end($tree);
  $deepest = $deepest->depth;

  // Create a structured array
  $list = [
    $parent => [
      'items' => [],
      'depth' => -1
    ]
  ];
  foreach ($tree AS $term) {
    $list[$term->tid] = (array) $term;
  }

  // See if we're on a node page and if so open the menu
  // on the proper position.
  $node = \Drupal::request()->attributes->get('node');
  if ($node) {
    $categories = $node->get('categories')->getValue();
    // Go through each category to find out the least deep one.
    // That one will be the one we'll open.
    $open_category = $parent;
    foreach ($categories AS $target) {
      $tid = $target['target_id'];
      if ($list[$tid]['depth'] > $list[$open_category]['depth']) {
        $open_category = $tid;
      }
    }
  } else {
    // See if we're on a term page and set the corresponding item
    // as active so we don't have to rely on JS.
    $term = \Drupal::request()->attributes->get('taxonomy_term');
    if ($term) {
      $open_term = $term->id();
    }
  }

  for ($i = $deepest; $i >= 0; $i--) {
    foreach ($list AS $term) {
      if ($term['depth'] == $i) {
        $item = [
          '#type' => 'link',
          '#weight' => $term['weight'],
          '#title' => $term['name'],
          '#url' => Url::fromRoute($route_name, ['taxonomy_term' => $term['tid']]),
          '#options' => [
            'set_active_class' => TRUE
          ]
        ];
        // If we're on a node page and this category was chosen
        // as active, set the link's class.
        if (isset($open_category) && $open_category == $term['tid']) {
          $item['#attributes']['class'][] = 'active';
        }
        // If we're on term page, set the link's class to 'active'
        // and if this item is a parent, open it.
        if (isset($open_term) && $open_term == $term['tid']) {
          $item['#attributes']['class'][] = 'active';
          if (!empty($term['items'])) {
            $item['#wrapper_attributes']['class'][] = 'open';
          }
        }
        // If this item has children
        if (!empty($term['items'])) {
          $item['items'] = $term['items'];
          $item['#wrapper_attributes']['class'][] = 'parent';
          $item['#prefix'] = '';
          // If any of the child items has 'active' class,
          // or is also a parent and has 'open' class
          // add the 'open' class to this wrapper too.
          foreach ($item['items'] AS $child) {
            if (
              isset($child['#attributes']['class']) && in_array('active', $child['#attributes']['class'])
              || isset($child['#wrapper_attributes']['class']) && in_array('open', $child['#wrapper_attributes']['class'])
            ) {
              $item['#wrapper_attributes']['class'][] = 'open';
              break;
            }
          }
        }
        foreach ($term['parents'] AS $pid) {
          $list[$pid]['items'][$term['tid']] = $item;
        }
        unset($list[$term['tid']]);
      }
    }
  }

  return [
    '#theme' => 'item_list',
    '#items' => $list[$parent]['items'],
    '#attributes' => [
      'class' => ['categories-tree']
    ],
    '#attached' => [
      'library' => [
        'mymodule/categories_tree'
      ]
    ]
  ];
}


Most of the time you will want to try to stay away from modifying the modules directly. This can be done, but it makes it more difficult to upgrade to future versions of the module.

A lot of modules allow for modification, and Drupal itself is designed for you to be able to modify things at many stages in the process of building a page. So if you can inject functionality it is best to do so.

This isn't always possible to do in which case you can either modify your local copy of the module. Or you can create an issue on the modules issue queue with a patch, which may get picked up in a future release of the module.

How to inject behavior is a very broad subject (I am sure specifics are already answered or can be asked on this site).

Most of the time you will want to create a module, and implement hooks which will allow you to modify things.


Automatically creating an organic group for each new user

The Rules module will allow you create new OG node after saving a new user account. Just do the following:

Create your rule and add an "After saving new user account" event to it
In the action section, select create a new entity
In the value section, select node
In the Content type, select the "your group"
Fill the title as you need; you can do this using the token
Fill the author

Hope this will help.


Running Drupal 6 with PHP 5.3 and Maintaining Security

Here are the patches I'm using for D6. Some of these issues will have been committed, thus they don't need a patch anymore.

Views
http://drupal.org/node/853864#comment-6465560 - views_get_default_view() - race conditions and memory usage
http://drupal.org/node/402944#comment-4650020 - Persistent caching for unpack_options() calls from building displays
http://drupal.org/node/1372388#comment-5370432 - Inline/Remove recursion in views_object->unpack_options to improve performance
http://drupal.org/node/465332#comment-4756670 - Strict warning: non-static method should not be called statically
http://drupal.org/node/893128#comment-4894754 - Strict warning: Declaration of * should be compatible with that of views_handler::*
http://drupal.org/node/1265138#comment-4928988 - Notice: Undefined variable: teaser in views_plugin_row_node_rss->render()
http://drupal.org/node/1432242#comment-5807802 - Notice: Undefined index: size in views_db_object->export_row()

Views Bonus Pack
http://drupal.org/node/1223910#comment-4756506 - Strict warning: is_a(): Deprecated

Views Bulk Operations
http://drupal.org/node/1782662#comment-6469236 - Notice: Undefined index: HTTP_USER_AGENT in views_bulk_operations_form()

Views Datasource
http://drupal.org/node/1265190#comment-4929150 - Notice: Undefined property: stdClass::$name in views_plugin_style_xml->option_definition()

Views Slideshow JCarousel
http://drupal.org/node/1885586#comment-6926004 - php notices

Here are some of the more popular modules as well

Calendar
http://drupal.org/node/999514#comment-4761150 - Strict warning errors for views plugins

CCK
http://drupal.org/node/1118792#comment-4358322 - array_keys() expects parameter 1 to be array, null given in content_multigroup.node_form.inc
http://drupal.org/node/1244534#comment-4845816 - Notice: Undefined index
http://drupal.org/node/1247732#comment-4857954 - Undefined index: _remove
http://drupal.org/node/1156096#comment-4868230 - Notice: Undefined index: title/description in content_storage()
http://drupal.org/node/1251146#comment-4871780 - Notice: Undefined index: #children in template_preprocess_content_field()
http://drupal.org/node/1251160#comment-4871816 - Notice: Undefined index: #field_info in fieldgroup_form_alter()
http://drupal.org/node/1265080#comment-4928778 - Notice: Undefined property: stdClass::$broken in content_handler_field->render()
http://drupal.org/node/1316510 - fix undefined index '#id' notice in form_alter hooks
http://drupal.org/node/533610#comment-5157454 - Notice: Undefined index: safe in theme_text_formatter_default()
http://drupal.org/node/1762506#comment-6411880 - Notice: Undefined property: stdClass::$field_* in content_rules_field_has_value()

CTools
http://drupal.org/node/1226098#comment-4765262 - Strict warning: Only variables should be passed by reference
http://drupal.org/node/1334894#comment-5215962 - Warning: Invalid argument supplied for foreach() in views_content_views_content_type_render()
http://drupal.org/node/1510118#comment-5807950 - Strict warning: Creating default object from empty value in views_content_views_content_type_admin_info()

Context
http://drupal.org/node/866208#comment-4845268 - Notice: Undefined property: stdClass::$taxonomy in context_node_condition() on line 352

Date
http://drupal.org/node/802722 - Extra comma in output when using "display from and to dates" on Display fields configuration
http://drupal.org/node/1223956#comment-4756746 - Strict warning: Creating default object from empty value in date_handler_fields
http://drupal.org/node/1948238#comment-7200236 - Strict warning: Declaration of date_handler_field_multiple::pre_render()

Features
http://drupal.org/node/1516900#comment-5833834 - Notice: Undefined index: group in views_handler_dependencies()
http://drupal.org/node/1515878#comment-5833794 - Strict warning: Only variables should be passed by reference in content_features_rebuild()

FileField
http://drupal.org/node/1180508#comment-4872304 - Warning: array_merge() Argument #2 is not an array in filefield_widget()
http://drupal.org/node/1164892#comment-4500360 - Warning: Trying to get property of non-object in filefield_field_sanitize()
http://drupal.org/node/1317424#comment-5146998 - Notice: Undefined index: fid in filefield_widget_process
http://drupal.org/node/1415840#comment-5514392 - Fatal error: Cannot unset string offsets
http://drupal.org/node/1677208#comment-6213652 - Notice: Undefined index: data in theme_filefield_widget_preview
http://drupal.org/node/1775708#comment-6440138 - Notice: unserialize(): Error at offset 0 of 1 bytes in filefield_get_node_files()

ImageAPI
http://drupal.org/node/1189884#comment-4608576 - Allow for custom code to be inserted into the convert command before it is ran
http://drupal.org/node/1201914#comment-4663120 - Add in the ability to "nice" the convert process
http://drupal.org/node/1250348#comment-4868656 - Fix divide by zero errors.
http://drupal.org/node/1766064#comment-6434498 - User error: ImageMagick reported error code 1. Message: convert: no encode delegate for this image format

Imagecache
http://drupal.org/node/1243258#comment-4841244 - use lock.inc instead of a file lock
http://drupal.org/node/1761108#comment-6407780 - Notice: Undefined index: filepath in theme_imagecache_formatter_default()

jQuery Update
http://drupal.org/node/1067290#comment-6516884 - Fix jQuery 1.7 for Drupal 6

Rules
http://drupal.org/node/1250384#comment-4868884 - Strict warning: Only variables should be passed by reference in rules_core_action_execute()

Core patches
http://drupal.org/node/496184#comment-5787602 - db_set_active errors out if db_connect fails. Add in the ability to handle this gracefully (don't always call _db_error_page)
http://drupal.org/node/764726#comment-5787642 - (Shared taxonomy patch) hook_taxonomy_term_presave() is missing
http://drupal.org/node/905156#comment-5791724 - PHP notice in form_builder function
http://drupal.org/node/1006938#comment-4661790 - Remove PHP warnings from legacy PHP4 XML parser for new update status release history XML
http://drupal.org/node/352180#comment-2562140 - Better, multi-site friendly "www." addition/removal in .htaccess
http://drupal.org/node/939810#comment-5791876 - Notice: Undefined index: key in format_xml_elements()
http://drupal.org/node/985814#comment-5791916 - Undefined index: configurable in actions_synchronize()
http://drupal.org/node/557542#comment-4989990 - Cache module_implements()
http://drupal.org/node/1317236#comment-5146174 - Race condition in file_delete: Warning: unlink() No such file or directory in file_delete()
http://drupal.org/node/1004820#comment-5171678 - Notice: Undefined index: type in dblog_build_filter_query()
http://drupal.org/node/1345204#comment-5259212 - Optimize element_children()
http://drupal.org/node/753064#comment-5274348 - _menu_link_translate() might avoid calling _menu_load_objects()
http://drupal.org/node/261148#comment-5798704 - menu_masks variable is empty (race condition)
http://drupal.org/node/1688282#comment-6240944 - Unknown error: Function split() is deprecated in _filter_autop()
http://drupal.org/node/521838#comment-6375266 - Clean up drupal_get_schema_versions()
http://drupal.org/node/1710656#comment-6474030 - If item is hidden in _menu_tree_check_access() skip it right away.
http://drupal.org/node/1882556#comment-6913038 - Notice: Undefined index: REMOTE_ADDR in includes/bootstrap.inc on line 2835
https://www.drupal.org/node/2292125#comment-8912499 - PHP 5.5 - preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in decode_entities() (line 349 of includes/unicode.inc)

Most of the issues I'm following that have the word notice in it
https://www.drupal.org/project/issues/search?text=notice&projects=&project_issue_followers=mikeytown2&status[0]=Open&categories[0]=1&issue_tags_op=%3D&assigned=&submitted=&issue_tags=&&order=field_issue_version&sort=asc

And the ones that contain the word warning
https://www.drupal.org/project/issues/search?text=warning&projects=&project_issue_followers=mikeytown2&status[0]=Open&categories[0]=1&issue_tags_op=%3D&assigned=&submitted=&issue_tags=&&order=field_issue_version&sort=asc

Query used to find the worst offenders for php issues: http://groups.drupal.org/node/170339


How do I pass a variable from a custom module to its template file?

Independently from the Drupal version for which you are writing the module, there are two errors in your code:

You define "Bluemarine" as theme function, but then you call theme('custom'), which would call the "custom" theme function
If you define "custom" as a theme function that uses a template file, then theme_custom() is never called

If you are writing code for Drupal 6, then the code should be similar to the following one. I take the assumption the name for the theme function is custom.
function custom_menu(){
  $items = array();

  $items['custom'] = array(
    'title' => t('custom!'),
    'page callback' => 'custom_page',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function custom_theme() {
  return array(
    'custom' => array(
      'arguments' => array('output' => NULL),
      'template' => 'custom',
     ),
  );
}

function custom_page() {
    $output = 'This is a custom module';
    return theme('custom', $output);
}

function theme_custom($output) {
}

The template file will have access to $output, and to any variables set in template_preprocess_custom(), if your module implements it.
For example, you could implement code similar to the following one:
function template_preprocess_custom(&$variables) {
  if ($variables['output'] == 'This is a custom module') {
    $variables['append'] = ' and I wrote it myself.';
  }
}

With this code, the template file has access to $output and $append.
As example of theme function that uses a template file, you can look at theme_node(), which is defined in node_theme(), and that uses node.tpl.php as template file; the preprocess function implemented by the Node module for that theme function is template_preprocess_node().


Adding a validation handler to the registration form

You need to change this line

 $form['actions']['submit']['#validate'][]  = 'checkout_nationality_form_validate';

to

 $form['#validate'][] = 'checkout_nationality_form_validate';


Ajax callback function must to have an ajax_command_invoke function witch trigger an custom made function in JS side like so:

function form_kalendar_dialog_validate($form, &$form_state) {
  $commands = array();
  $commands[] = ajax_command_invoke(NULL, 'customMethod', array('Custom Method Arg.'));
  return array('#type' => 'ajax', '#commands' => $commands);
}

JS

(function ($) {
  $.fn.customMethod = function(arg) {
    // Custom JS goes here.
    console.write(arg);
  };
}) (jQuery);

The answer whas here: Tlattimore blog


Is it possible to use image styles in Views field rewriting?

I figured it out! What you have to do is include a copy of the second field, set to "Exclude from display" in the options, and arrange the fields such that Image2 comes before Image1 in the list. You can set the image style in the options for Image2, and that information will get carried over when Image1 is empty and gets rewritten using the behavior specified in the "No results" option. Also, you don't have to write <img src="[field_Image2]"> in the rewrite area.  All you need is the token for the other field, like [field_Image2].


How to display more than 10 items in link widget autocomplete?

If you can live with overriding all of the autocomplete limits, you can override a core service in Drupal 8;

The service you need to override is here in core.services.yml:

  entity.autocomplete_matcher:
    class: Drupal\Core\Entity\EntityAutocompleteMatcher
    arguments: ['@plugin.manager.entity_reference_selection']

In your custom module, add a class that implements ServiceModifierInterface

namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceModifierInterface;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

class MyModuleServiceProvider implements ServiceModifierInterface {

  /**
   * Modifies existing service definitions.
   *
   * @param ContainerBuilder $container
   *   The ContainerBuilder whose service definitions can be altered.
   */
  public function alter(ContainerBuilder $container) {

    for ($id = 'entity.autocomplete_matcher'; $container->hasAlias($id); $id = (string) $container->getAlias($id));
    $definition = $container->getDefinition($id);
    $definition->setClass('Drupal\mymodule\Entity\EntityAutocompleteMatcherCustom');
    $container->setDefinition($id, $definition);
  }

}

Then copy EntityAutocompleteMatcher.php into your module at /src/Entity/EntityAutocompleteMatcherCustom.php

Then update the hardcoded 10 to a 50, or whatever limit you'd like:

namespace Drupal\mymodule\Entity;

use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Tags;
use Drupal\Core\Entity\EntityReferenceSelection\SelectionPluginManagerInterface;
use Drupal\Core\Entity\EntityAutocompleteMatcher;

/**
 * Matcher class to get autocompletion results for entity reference.
 */
class EntityAutocompleteMatcherCustom extends EntityAutocompleteMatcher {

  /*
   * {@inheritdoc]
   */
  public function getMatches($target_type, $selection_handler, $selection_settings, $string = '') {

    $matches = array();

    $options = array(
      'target_type' => $target_type,
      'handler' => $selection_handler,
      'handler_settings' => $selection_settings,
    );
    $handler = $this->selectionManager->getInstance($options);

    if (isset($string)) {
      // Get an array of matching entities.
      $match_operator = !empty($selection_settings['match_operator']) ? $selection_settings['match_operator'] : 'CONTAINS';
      // Changing limit from 10 to 50.
      $entity_labels = $handler->getReferenceableEntities($string, $match_operator, 50);

      // Loop through the entities and convert them into autocomplete output.
      foreach ($entity_labels as $values) {
        foreach ($values as $entity_id => $label) {
          $key = "$label ($entity_id)";
          // Strip things like starting/trailing white spaces, line breaks and
          // tags.
          $key = preg_replace('/\s\s+/', ' ', str_replace("\n", '', trim(Html::decodeEntities(strip_tags($key)))));
          // Names containing commas or quotes must be wrapped in quotes.
          $key = Tags::encode($key);
          $matches[] = array('value' => $key, 'label' => $label);
        }
      }
    }

    return $matches;
  }

}

Obviously override core services has some risks, but it's cool that you can do this.

What are the risks of overriding a core service?

1) You may lose the benefits of updates when you update core.  If there is a critical security fix in the service, and your altered copy has the security hole, you will not benefit from the community updating that code.

2) Other modules you install may have dependencies to the original service with its original feature set.  So let's say there is some code in another module that will break if the number of autocomplete entries are greater than or less than 10, you won't know about it, until it affects you.

3) It makes your codebase harder to maintain.  You have to remember that you are not using core Drupal, but an extended version.  Other developers who join your project after you left may have a hard time figuring out why a service is behaving in a non-standard way.

Is this hacking core?

Depends on how you look at it.  It's not going into the core module and changing code.  It's not even creating a patch and applying it and tracking it with a package manager such as composer.  It's more of a one-off customization that alters a sites core behavior, similiar to an ALTER hook. It's more self-contained that a core hack, because it's within your own custom module on your site.  So core updates to the original service will not be affected, the same way as if you patched or hacked the original service code.

But it does have some of the same risks as hacking core, as mentioned above.

In the original question, the issue was the node titles are not unique enough.  The better solution, other than changing the limit globally on drop downs would be solve the uniqueness problem.

What I would suggest is to add a new field field_display_title and use that on the page, and if you need it another field field_teaser_title for display on list pages where you need a shorter title.  Then the actual title that gets pulled into entity reference select dropdown can be useful to your editors and be unique, such as "My Article (page 1)" if the issue is each page has the same title.  Then you don't have to override a core service.

When you come across a problem with Drupal, try to find the solution that requires the least amount of custom code.  This makes your site more stable, easier to maintain and saves you time.


Can DS manage "admin tabs" placement for a node?

After some looking around, I've found the following two approaches:

Use DS's 'dynamic field'
Use DS's 'preprocessor field'

Dynamic Field

Create a Dynamic Field (in /admin/structure/ds/fields) for Node entities.
Go to the 'manage display' of your content type and place the dynamic field somewhere.
Click 'Select Content' on the field settings (through manage display)
Select 'Page Elements'
Select Tabs, and save

Preprocessor Field

Not 100% working for me right now, however just to give the basic idea:

Create a preprocessor field in DS and add the field to your content type.
In your template.php file, instantiate the field:

function YOURTHEME_preprocess_node(&$vars) {
  $vars['nameoffield'] = print render(menu_local_tabs());
}

I'm currently getting some errors with the preproccessor approach, however the dynamic field approach is working fine.


Duplicating commerce kickstart's product types view modes

In Commerce Kickstart, Commerce Kickstart Product (commerce_kickstart_product) and Commerce Kickstart Product UI (commerce_kickstart_product_ui) modules provide the extra view modes. And are not available as a separate module.

So, you can use Entity view modes (entity_view_mode) to create your custom view mode.


Add meta tags on a page generated by a custom module

I've tested successfuly Metatag Routes module for Drupal 8. The module adds a button in the default metatag dashboard page. The user can configure metatags for custom controllers generated by code.


is it possible to search for user names with solr?

Regarding the Content Profile module, as long as anonymous users have access to view the profile nodes, the content should be able to be indexed by Solr.  You can use the Automatic Nodetitles and Token modules to ensure that the username is set as the Content Profile node's title. You might want to set the field bias for the title to a higher value so more importance is placed on it when ranking search results.

Normal users probably can't see the core User search because they don't have the "access user profiles" permission.  If they are granted that permissions they should be able to use the core User search.


The solution that worked for me in this case was easier than I thought.

Solution:

In the configurations of the view

1.-
Select settings Style ->
Customize HTML field -> None

Uncheck Add default classes

2.-
In Rewrite results -> Select Strip HTML tags


In Drupal 7, you should use a queue for such type of operations. In short, what happens is the following:

An item is added to the queue
An item in the queue is processed, and removed

In the case of cron tasks, there is a hook (hook_cron_queue_info()) that tells Drupal which queues need to be handled when drupal_cron_run() is executed, and which function handles the items contained in the queue.

function mymodule_cron_queue_info() {
  $queues['mymodule_update_node_popularity'] = array(
    'worker callback' => 'mymodule_update_node_popularity',
    'time' => 20,
  );

  return $queues;
}

For how to populate that queue, I see two possible cases:

The field is updated for every node that is updated
The field is updated for every node, once
The field is updated for every node that is created, or updated

In all the cases, the following function should be used, together the hook I previously shown.

function mymodule_update_node_popularity($nid) {
  $node = node_load($nid);

  // Calculate the new score for the node.

  $node->field_popularity_score[LANGUAGE_NONE][0]['value'] = $new_value;
  // Replace the previous line with the following one, if the value should be different for each language.
  // $node->field_popularity_score[field_language('node', $node, 'field_popularity_score')][0]['value'] = $new_value;

  node_save($node);
}

The parameter received from the worker callback (in this case, mymodule_update_node_popularity()) is the one that is passed to $queue->createItem().

In the first case, I would implement the following code.

function mymodule_node_update($node) {
  if ($node->type == 'content type to handle') {
    $queue = DrupalQueue::get('mymodule_update_node_popularity');
    $queue->createItem($node->nid);
  }
}

In the second case, I would implement the following code.

function mymodule_cron() {
  $args = array(
    ':type' => 'content type to check',
    ':created' => variable_get('mymodule_last_checked', 0),
  );
  $queue = DrupalQueue::get('mymodule_update_node_popularity');

  $nodes_result = db_query('SELECT nid, created FROM {node} WHERE type = :type AND created >= :created ORDER BY created ASC', $args);
  foreach ($nodes_result as $node) {
    $queue->createItem($node->nid);
    variable_set('mymodule_last_checked', $node->created);
  }
}

The reason I am not using "SELECT nid FROM {node} WHERE type = :type" as query is that such query would cause mymodule_cron() to always add the same nodes to the queue (except for those nodes that have been deleted). mymodule_cron() needs a way to filter out the nodes that have been already handled, and the query I wrote is a way to achieve that.
The value passed to $queue->createItem() can also be an array, or an object, and that value would be passed to the worker callback.

In the third case, I would use the following code.

function mymodule_cron() {
  $args = array(
    ':type' => 'content type to check',
    ':changed' => variable_get('mymodule_last_checked', 0),
  );
  $queue = DrupalQueue::get('mymodule_update_node_popularity');

  $nodes_result = db_query('SELECT nid, changed FROM {node} WHERE type = :type AND changed >= :changed ORDER BY changed ASC', $args);
  foreach ($nodes_result as $node) {
    $queue->createItem($node->nid);
    variable_set('mymodule_last_checked', $node->changed);
  }
}

This code works because, when a node is first created, both $node->created, and $node->changed are set to the same value.

In the first case, when you need to update the field value when the node is updated, you could implement hook_field_presave(), instead of using a Drupal queue.


Set the permission to view taxonomy term pages basing on the vocabulary

Use hook_menu_alter() to customize the access_callback on $callback['taxonomy/term/%'].


Get field value and label for a content type using REST API

In the foreach you add just title so it's normal to have only title displayed:
you should populate your array result with the values from your entity, something like:

  foreach ($nodes as $entity) {
    $result[] = [
      'nid' => $entity->id(),
      'title' => $entity->title->value,
      'FIELD_NAME_1' => $entity->FIELD_NAME_1->getValue(),
      'FIELD_NAME_2' => $entity->FIELD_NAME_2->getValue(),
       // And so on with other fields.
    ];
  }


menu item  does not get class expanded nor active-trail when at homepage

Go to admin/structure/menu/manage/[your-menu-name] and Enable the show as expanded checkbox in your parent menu item settings.


There is a reason that they have made it like that.
Take a look at this page, it describes why.

Onsite Payment Gateways always store credit card info
Payment gateways have different capabilities. Some support storing a user's card in the gateway. Others have an "offsite" flow, sending you to their site to collect card info and then returning you back to the commerce site when done.
An "Onsite" payment gateway is one that keeps the visitor on the site, collects the card numbers and posts it from the site to the gateway. In Drupal Commerce 2, the payment flow for onsite gateways is completely different than in Commerce 1, Ubercart, or many other shopping carts: it now stores the credit card in the gateway first, and creates a "Payment Method" associated with the user that contains the token from the gateway. It can then use that token for any future charges (as long as the gateway continues to honor it).


If you have changed the content type to allow for commenting, it does not back-propagate to existing nodes. So, check to see the individual comment settings on each of nodes that it does not appear on to make sure they are indeed enabled.


Use an Address Field with 3 lines for the street

I found a (partial solution), but new ideas are always well welcomed.
I used the field organization as third row and then I rearranged the weights of the fields in this way:

function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    if ($form_id == 'specific_add_form' || $form_id == 'specific_edit_form' ) {
        $form['field_address']['widget'][0]['address']['#after_build'][] = 'mymodule_weight_change';
    }

}

function mymodule_weight_change($element, $form_state) {
    $element['country_code']['#weight'] = -10;
    $element['address_line1']['#weight'] = -7;
    $element['address_line2']['#weight'] = -5;
    $element['organization']['#weight'] = -2;
    $element['postal_code']['#weight'] = 5;
    $element['locality']['#weight'] = 10;

    return $element;
}

Endly I put the css of the organization label as display: none.


What is the Drupal API for reading Drupal configuration files (.info .make etc.)?

You want drupal_parse_info_format.

  Data should be in an .ini-like format to specify values. White-space
  generally doesn't matter, except inside values.

  key = value
  key = "value"
  key = 'value'
  key = "multi-line
  value"
  key = 'multi-line
  value'
  key
  =
  'value'

  Arrays are created using a HTTP GET alike syntax:

  key[] = "numeric array"
  key[index] = "associative array"
  key[index][] = "nested numeric array"
  key[index][index] = "nested associative array"

  PHP constants are substituted in, but only when used as the entire
  value. Comments should start with a semi-colon at the beginning of a
  line.

I actually know this because the Profiler module uses it to parse out its .info file for profile configurations.


Is there a token for the key of a text list?

You could use roborew's sandbox: Entity Token Display

  This simple module was created to handle the formatting of entity
  tokens.

  When using certain field entities the entity token module will provide
  formatting and data sanitisation for display. However, there are times
  when you need the default value of the original field.


dpm function doesn't display results for arrays

hook_menu_alter() is fired directly in the same call that flushes the caches - and only once. If you do that via drush cc all the result is never displayed.


Programmatically update or add a user's avatar

The file gets stored to file_managed table like this:

// Programmatically create files.
use Drupal\file\Entity\File;
$file = File::create([
  'uid' => 1,
  'filename' => $_FILES['file_id']['name'],
  'uri' => 'public://pictures/' . $_FILES['file_id']['name'],
  'status' => 1,
]);
$file->save();

And I manually updated user__user_picture table which is referring to the fid in the above table.

Finally I ended up with move_uploaded_file to store the image to the filesystem.
I'll proceed with this approach until I find a better way to do the same.

http://www.drupal8.ovh/en/tutoriels/47/create-a-file-drupal-8


User profile form make custom form required

Try the following code to set a field to required.

$form['field_company_name']['und']['0']['value']['#required'] = TRUE;


You cannot just push a newer version jQuery by adding/replacing the  tag. Drupal and some modules bundles their own JavaScript that rely on that specific version of jQuery, updating jQuery may break these JavaScript. Most of these script require the jQuery object (from jQuery 1.2.6) to be binded to $.

If really needed, you can load an newer version of jQuery in noConflict mode, treating the old jQuery as a an other library. So $ will still be the old jQuery object for the existing script. Andyou can use newer jQuery version using jQuery in your script. Properly written plugins and libraries should access the jQuery object using jQuery instead of $ and so should be loadable (after calling the noConflict() method). IF not, you may need to fix them.


Create a list of events where an event can have more than one date

Add the date field and then in that fields settings uncheck Display all values in the same row (found in the Multiple Field Settings section).


Pathauto bulk update for taxonomy terms with unchecked “Generate automatic URL alias”

As I know there is no simple SQL query to update "Generate automatic URL alias" status for nodes and terms for Drupal 8.
Data contained in table key_value but I don't think it's possible to use it directly.


If you are using panels node view template for your node view then your template file and node theme declarations would be overruled by panels.

If you want to verify, disable the panel node view. Make sure to flush your caches then visit a node you have and your theme override/addition will be there.


how to make conditional fields work with MEDIA

It was giving an error on getType when it was a media object.
I fixed it by changing line 208 in conditional_fields.module to

if (method_exists($entity, 'getType')) {
      $bundle = $entity->bundle();


Drupal Ubercart to Commerce Migration: any solution for uc_file (file downloads)?

Well as it turns out, no code was needed.

In case anyone runs into this issue, here's what you need to do:

Download the dev version of commerce_migrate_ubercart and apply the payment patch if it hasn't already been applied.
Disable all Ubercart modules
Carefully follow the instructions in the README.txt file. You'll
want to migrate every available table starting with products, and
working your way to payments (transactions). Save the database early
and often along the way.
Download/configure commerce_file and commerce_license.
Be sure you are able to go end-to-end with your cart and download privileged files in your user/uid/my_files tab.
Download/enable commerce_vbo_views and views_bulk_operations
Edit the rule "Activates licenses of an order", and add the event "After updating an existing commerce order".
Go to your Store's order list page, select the desired order states
that have completed orders, then select all rows in the table, then
click modify order values, and just set the exact same state as
selected before. What we're after here is to force a re-save of the
order to trigger our rule.
You should now be able to view a user and click the "Files" tab to see their downloads assuming permissions are correctly set and the migration worked.
Edit the rule again to remove the added event and you're done.

Easy peasy :)


Yes, this is a common problem. A spam bot has crawled your site, realizes it's a Drupal site, and it going through its functions to spam content (e.g. user register & node posting). This isn't exclusive to Drupal; there many kinds spam bot software that target specifics CMSes and any other comment/content submission forms.

You should look into various Drupal spam prevention modules like CAPTCHA, Botcha, etc.


How do I update Drupal 8.2.3 REST configurations for an entity?

To answer your second question, you'll want to remove the imported configuration from the database and then reimport it with an included UUID - after which you can overwrite the config by re-importing it as many times as you like.

But first, when you upload a config, you should give it a more meaningful ID; rather than 'entity.node', you want something like 'my_config_for_this_thing'.

So in steps:

In your DB, find the config you uploaded (and see note about about the config ID):

select name from config where name like '%entity.node%';

Copy the full name that matches your config.  It will be something like 'migrate_plus.migration.entity.node'.
Delete that row from the database

delete from config where name = '*paste that name here*';

In your yml file, include a uuid. You can generate one locally or using a web tool such as https://www.uuidgenerator.net.  This will look something like

id: some_meaningful_identifier
label: 'A label to describe my config'
status: true
uuid: ac1d69cc-382f-49d2-921e-bb0673fd62ea

Clear your Drupal cache
Then re-import and you should be in better shape.


Can I insert the version number in the info file of a module for internal use?

If you host your module outside of drupal.org, including a private Git repository, or a local computer from which the module is copied on the site, you can set the version key in the .info.yml file for the module.
If the module updates are handled differently, the module could also implement hook_update_projects_alter() to tell the Update Manager not to check for that module updates, for example implementing the code shown in the documentation.
function mymodule_update_projects_alter(&$projects) {
  // Hide a site-specific module from the list.
  unset($projects['site_specific_module']);
}

As for the number N used in hook_update_N(), that number isn't related to the module version. It's just a progressive number, used from Drupal to verify which hook_update_N() implementation has been already run. hook_update_N() explains the convention for the four digits used for N.

1 or 2 digits for Drupal core compatibility (for example, 8 for compatibility with Drupal 8, 10 for compatibility with Drupal 10)
1 digit for your module's major release version (for example 1 for the 8.x-1.3 release)
2 digits for a counting number, starting from 01

To use an existing project as example, the pathauto.install file for the release 8.x-1.11 defines, as last update hook pathauto_update_8106(); the same file for the release 8.x-1.5 has pathauto_update_8107() as last update hook, which is the latest update hook also for the release 8.x-1.8.
Note that the digit for the major version release isn't sufficient to describe the version release (which would include also the minor version), but it's not sufficient also for a major version that is higher than 9.
Note also that Drupal core won't report any error whether (for example) a 8.x-2.3 release contains mymodule_update_8133() as update hook. What described is a convention for which only the Drupal compatibility digit is required.


OK, so I solved it myself.

Open and edit the webform.submissions.inc file in the includes folder of the module

In the Return all the submissions for a particular node. section find the code with the comment "// Join to the users table to include user name in results."

 // Join to the users table to include user name in results.
  $pager_query->leftJoin('users', 'u', 'u.uid = ws.uid');
  $pager_query->fields('u', array('name'));
  if (isset($filters['u.uid']) && $filters['u.uid'] === 0) {
    if (!empty($_SESSION['webform_submission'])) {
      $anonymous_sids = array_keys($_SESSION['webform_submission']);
      $pager_query->condition('sid', $anonymous_sids, 'IN');
    }
    else {
      $pager_query->condition('sid', 0);
    }
  }

To add my country section I had to find the table in phpMyAdmin that contained my taxonomy data. In this case it was "field_data_field_counrty" (I've spelled country wrong i know but I couldn't change it after).

From that I figured out that the entity ID was the the user ID in the Users table. This is because I had used the country taxonomy on the registration form.

The syntax for the inner join query is 'Table, Table Alias, Condition, Arguments'.
From that my innerjoin became,

 $pager_query->innerJoin('field_data_field_counrty ', 'fld_Country', 'fld_Country.entity_id = ws.uid' );

The field syntax is 'Table Alias, Field Name', so my field selection became,

$pager_query->fields('fld_Country', array('field_counrty_tid'));

This gave me the country ID number that had been assigned to the taxonomy term. I then had to cross reference that field with the taxonomy data table to retrieve the name of the country the ID referred to. That was done with another innerjoin.

$pager_query->innerJoin('taxonomy_term_data ', 'taxonomy_Country', 'taxonomy_Country.tid = fld_Country.field_counrty_tid' );

This time the field I needed to retrieve was called name. However, 'name' had already been used further up in the original code for the user name. So to add an alias to the field I had to use addField instead of fields. The syntax for addField is 'Table Alias, Field, Alias'. My code became,

 $pager_query->addField('taxonomy_Country', 'name', 'tax_name');

The code as a whole is:

 // Join to the field country table to include Country ID in results.
  $pager_query->innerJoin('field_data_field_counrty ', 'fld_Country', 'fld_Country.entity_id = ws.uid' );
  $pager_query->fields('fld_Country', array('field_counrty_tid'));
  $pager_query->innerJoin('taxonomy_term_data ', 'taxonomy_Country', 'taxonomy_Country.tid = fld_Country.field_counrty_tid' );
  $pager_query->addField('taxonomy_Country', 'name', 'tax_name');

Further down in the code is the section:

 $result = $pager_query->execute();

  $sids = array();
  foreach ($result as $row) {
    $sids[] = $row->sid;
    $submissions[$row->sid] = new stdClass();
    $submissions[$row->sid]->sid = $row->sid;
    $submissions[$row->sid]->nid = $row->nid;
    $submissions[$row->sid]->serial = $row->serial;
    $submissions[$row->sid]->submitted = $row->submitted;
    $submissions[$row->sid]->remote_addr = $row->remote_addr;
    $submissions[$row->sid]->uid = $row->uid;
    $submissions[$row->sid]->name = $row->name;
    $submissions[$row->sid]->is_draft = $row->is_draft;
    $submissions[$row->sid]->preview = FALSE;
    $submissions[$row->sid]->data = array();

In this section I added the line:

        $submissions[$row->sid]->CountryID = $row->tax_name;

To display the data, we now need to edit the webform.report.inc file. Find the section near the top that says,

 foreach ($submissions as $sid => $submission) {
    $row = array(
      $submission->is_draft ? t('@serial (draft)', array('@serial' => $submission->serial)) : $submission->serial,
      format_date($submission->submitted, 'short'),

    );
    if (webform_results_access($node, $user)) {
      $row[] = theme('username', array('account' => $submission));
      $row[] = $submission->remote_addr;

I then added the following line after the format_date section to add my new column after the submitted column.

      $submission->CountryID,

To  add the header for the new column find the section with the comment,

 * Theme the header of the submissions table.

I then added the following line after the submitted section,

    array('data' => t('Country'), 'field' => 'tax_name'),

Save both files and view a webform results page (providing it has a submission).
Your new column should now display.

I hope this helps anyone else that is confused on this subject!

Happy new year everyone!!!


From the screenshots I could see that you are using acquia marina theme, and these errors are related to that theme.

Please make sure that, you installed/configured the theme properly.

Related issue in acquia marina theme issue queue - http://drupal.org/node/1057002


Use this:

/**
* Get all product types
* @return array
*/
public function getProductTypes() {
   $product_types = \Drupal\commerce_product\Entity\ProductType::loadMultiple();
   return array_keys($product_types);
}


How to list 5 most view nodes without using the Statistic module?

The simple and best solution which work with views is node view count. Which works with views and play around it.


add an additional item to an array in Drupal Settings javascript from php

Your first declaration should indicate that you are passing a setting to drupal_add_js():

drupal_add_js(array('your_module' => array()), 'setting');

Then you can add other properties to your array in hook_node_view():

function your_module_node_view($node, $view_mode, $langcode) {
    $your_array = array(
      'vimn_video' => array(
        'embedded_videos' => array($node->nid), // NOTE: $node->nid as an array
      ),
    );
    drupal_add_js(array('your_module' => $your_array), 'setting');
}

You can retrieve the properties from javascript as:

Drupal.settings.your_module.vimn_video.embedded_videos; // an array with node ids.


Attach file to post using C# RestSharp and Drupal Services

I have figured it out this way, sorry for late posting the answer:

// FIRST LOGIN
var client = new RestClient("http://....../");
var request = new RestRequest("user/login.json", Method.POST);
request.AddHeader("Content-Type", "x-www-form-urlencoded");
request.AddParameter("username", username);
request.AddParameter("password", password);
var restResponse = client.Execute<Login>(request);

Now upload a picture:

public string UploadPic(string path, Login login)
{
    var request = new RestRequest("file.json", Method.POST);
    request.RequestFormat = RestSharp.DataFormat.Json;
    request.AddCookie(login.session_name, login.sessid);
    request.AddHeader("X-CSRF-Token", login.token);
    request.AddParameter("uid", login.user.uid);
    string filevalue = System.Convert.ToBase64String(file_get_byte_contents(path));
    request.AddParameter("file", filevalue);
    request.AddParameter("filename", path.Split(new Char[] { '\\', '/' }).Last());
    var response = client.Execute<DFile>(request);

    return response.Data.fid;
}

static byte[] file_get_byte_contents(string fileName)
{
    byte[] sContents;
    if (fileName.ToLower().IndexOf("http:") > -1)
    {
        // URL
        System.Net.WebClient wc = new System.Net.WebClient();
        sContents = wc.DownloadData(fileName);
    }
    else
    {
        // Get file size
        FileInfo fi = new FileInfo(fileName);

        // Disk
        FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        sContents = br.ReadBytes((int)fi.Length);
        br.Close();
        fs.Close();
    }

    return sContents;
}

Where the class Login and DFile are the following:

public class DFile
{
    public string fid { get; set; }
    public string uid { get; set; }
    public string filename { get; set; }
    public string uri { get; set; }
    public string filemime { get; set; }
    public string filesize { get; set; }
    public string status { get; set; }
    public string timestamp { get; set; }
}
public class Login
{
    public string sessid { get; set; }
    public string session_name { get; set; }
    public string token { get; set; }
    public User user { get; set; }
}


Before Field Layout was added to core this functionality was provided in contrib by Display Suite. With these modules you can configure layouts in UI instead of theming them in node/block/paragraph templates. This is not about one versus the other, this is more about the skill level needed to change the layout. You can use both methods at the same time. However, when you install one of these modules they add a new layer to theming, so you need to adjust any existing node/block/paragraph templates which changed the field layout.


print title and contents on a custom tpl.php template?

A different approach would be to:

Use the Block Class module - which will also allow you to add
more classes per block.
Use CSS to apply the same styling to all blocks in the sidebar:

.sidebar .block { border: 1px solid #ccc}
.sidebar .block-title {color: blue}


Yes, you can use hook_node_access to control access to add/edit for the node.

For example, you can check the value of:

$language = \Drupal::languageManager()->getCurrentLanguage()->getId();

and return the access result accordingly


profile2 - change default edit path to custom profile

Well actually you can, there is a submodule of the profile2 called "profile pages"

  With profile2 user account settings and user profiles are conceptually
  different things, e.g. with the "Profile pages" module enabled users
  get two separate menu links "My account" and "My profile".

Via the included "Profile pages" module profiles can be viewed and edited at their own page and get their own menu link, e.g. "My profile".

with the profile menu paths already setted up for your custom profile then you need to remove the edit tab that points to the default profile edit page of drupal. For delete this tab follow this tutorial http://www.zyxware.com/articles/4159/solved-drupal-how-to-hide-menu-tabs-and-menu-links-in-drupal-7

Then you can add your own edit tab that will link to your custom profile edit page https://www.drupal.org/node/1578582


programmatically enable and disable theme from update hook

Use the theme installer service to enable and disable themes .

Install a list of themes:

\Drupal::service('theme_installer')->install(['mytheme']);

Uninstall a list of themes:

\Drupal::service('theme_installer')->uninstall(['mytheme']);

Reference: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Extension%21ThemeInstaller.php/function/ThemeInstaller%3A%3Ainstall/8.2.x

Instead of writing to the config you can use the theme handler to set a default theme:

\Drupal::service('theme_handler')->setDefault('mytheme');


How can I tell if a config entity hasn’t been saved yet?

isNew();

this core test confirms it:

// Config is no longer new once saved.
$this->config->save();
$this->assertFalse($this->config->isNew());

(from core/tests/Drupal/Tests/Core/Config/ConfigTest.php)


Using hook_form_alter on an existing form element

Not sure which checkout form you try to alter, however, I've used mytheme_form_commerce_checkout_form_checkout_alter(&$form, &$form_state, $form_id) and mytheme_form_commerce_checkout_form_review_alter(&$form, &$form_state, $form_id) successfully.

And if I understand it correctly, the element 'edit-account-login-mail' already exists in your form. Therefore, I think you might want to add the size property instead of overwriting the form element, for instance:

$form['edit-account-login-mail']['#size'] = 40;


How to send out email based on matching taxonomy terms in user profiles?

Even though your question doesn't say so, from the format of your exported rule it's clear it is about D7. A possible answer to your question is by replacing the Rules Action in the rule you already have, and by also using the Views Rules module, as further detailed below.
1. About the Views Rules module
The Views Rules module makes Views data available in Rules, enabling intuitive rule configuration for dynamic data. Some details from its project page:

... provides two types of elements in Rules, configured with a "Rules" view display:

Views loop: A views loop is similar to a regular Rules loop, but allows looping over rows of view results.

Collect view result rows (action): This action collects each variable in all view result rows into list variables for use in Rules.

Tip: When selecting the data type for variables in the view, if the field is an entity identifier (e.g. Node ID), you can set the data type to the entity type (i.e. Node) to directly use the variable in Rules as an entity!

2. Create a view of display type 'Rules'
After you enable the Views Rules module, you can use Views to create a view of those users that you want to send an eMail to. Add of view of display type Rules (important, that's the key to make it work!). Here is how you can add such display:

Next configure the row variables, by using the link that says "edit field info", as shown here:

You probably want to use one or more of the variables similar to those that are shown in this screenprint:

3. Create a rule using the view of display type 'Rules'
Replace the Rules Action in your current rule, using these guidelines:

Use the link that says Add view loop to add a Views loop, and select the "Rules" display created in the previous step.
Configure the parameters and variable names.
For each user contained in your Views loop, perform a Rules Action "Send an eMail", using the variables you configured at the end of the previous step (you may have to revisit the previous step to add more similar variables there if needed). If you created the Rules row variables as suggested in the previous step, your actual eMail can use tokens such as [usermail:value], [username:value], etc.


That code won't work.  The first line is using the $tid to load the term, obviously that won't work if you don't know the Term ID in the first place.

You don't need to use any PHP to get a taxonomy terms ID. Just goto the edit page of that term and look at the url. It will be /taxonomy/term/TID/edit


REST interface to custom entity type getting constant 403's

The answer is quite simple but easy to miss.

The URL I used when I made the GET request; http://apps.dev/app/apps_user/1?_format=hal_json is not the same as the URL required to make POST requests.

To make a POST request, you change it to http://apps.dev/entity/apps_user?_format=hal_json

None of the URL's in the returned _links property are correct for POST requests.


hook_mail_alter() - how to access the "contact admin" form fields?

Try doing this in hook_form_alter() instead of hook_mail_alter(). You can likely then run your own parameters into drupal_mail().

I would recommend not using this contact form, though, since it's terribly limited in terms of functionality. Why not use a Webform at /contact where you can specify all of these settings and do potentially cooler things too, like pre-filling fields for logged in users?


Unique Fields with the ability to be a reference to multiple records

I would envision this as

Create a rule that post a node each time the form from anonymous user is submitted.
Create a condition before creating a node - the condition will loop through all entered node telephone numbers if they found that the user has already entered the data don't do anything other wise post the node with phone, name and email information.


Ideas...

1) create custom config entity like "products_not_on_sale"

2) Alter node view to hide the fields if referenced in above ^

--- or ---

1) add new field of type bool to say item on sale or not.

2) alter node view to hide fields if value is checked.


Context for panel not activating for custom menu item

I like to test a panel answer before I post it, but will be gone for a couple days, so I'll give you my speculation on what may be causing this.  I suspect your page panel path is /course/%course and so that is the only path that is intercepted.  It does not matter that you have a variant for resources because it never gets tested. The basic panel definition has already rejected it.  Try changing the basic path to /course/%course/!other.  The !other variable is optional so the panel should intercept 2 and 3 level paths matching the pattern.  Your variant should then be triggered.

The variable labels in the path (%course & !other) are used to identify associated contexts listed on the context/relationships tab for defining the variant and the specific label name does not matter.  Hope this works. If not, I'll check back in a couple days.


Making File Size visible to anonymous users

Permission should be given for that file type in case of anonymous user.

Because if size is visible to authenticated user and not to anonymous user, then it must be a permission issue.


What's the proper way of working locally with freshly created features?

How features store settings

Features that are created locally have all there setting and content in the database as they where there before you export them to the feature, as an example if you created a view it will reside in the database even if you exported it to a feature.

as for features enabled on another site it will store every thing in the database when enabled except for ctools exports, which in this case even if you disable or uninstalled the feature those sittings will persist in the new site database, an example a strongarm (variable) will still be set even after you uninstall the feature.

as for settings using ctools exports they will not be added to the database unless you have override them, as an example if you had a view exported through features it will disappear if you have disabled the feature since it only exist in code.

Conclusion

Features do not delete any thing in your database if uninstalled, except for true exportables that can only reside in code without the need to be in the daatabse to work.

Suggested features workflow

When creating a feature on you local development machine it is a good thing to enable it to see if the settings in your database and the settings in the feature does match and be aware if they do change.

As for removing things added by the feature you can add a hook_uninstall manually to your feature .install file and remove or delete what ever you like just like a proper module will do when uninstalled.

More info about this issue:

https://www.drupal.org/node/1732766#comment-6382244
https://www.drupal.org/project/configuration


Creating a table with pagination in a Node Edit form

You can use tableselect instead of details something like:

   $query = \Drupal::database()->select('node', 'n')
      ->condition('type', 'article', '=');
    $query->fields('n', ['nid']);
    $query->innerJoin('node__field_articles_category', 'category', 'category.field_articles_category_target_id = ' . $categoryId);
    //For the pagination we need to extend the pagerselectextender and
    //limit in the query
    $pager = $query->extend('Drupal\Core\Database\Query\PagerSelectExtender')
      ->limit($limit);
    $article_ids = $pager->execute()->fetchAll(\PDO::FETCH_OBJ);
    $rows = [];
    foreach ($article_ids as $index => $article_id) {
      $article = Node::load($article_id->nid);
      $rows[$index + 1] = [
        'title' => $article->getTitle(),
        'url'   => Drupal::l($article->getTitle(), $article->toUrl()),
      ];
    }

    $form['related_articles']['table'] = [
      '#type'    => 'tableselect',
      '#header'  => ['title' => t('title'), 'url' => t('Url')],
      '#options' => $rows,
      '#empty'   => t('No users found'),
    ];
    // Finally add the pager.
    $form['related_articles']['pager'] = array(
      '#type' => 'pager',
    );

Result will be like:


What's the difference between !, %, and @ in replacement tokens?

From the format_string() docs:

@variable: Escaped to HTML using check_plain(). Use this as the default choice for anything displayed on a page on the site.
%variable: Escaped to HTML and formatted using drupal_placeholder(), which makes it display as emphasized text.
!variable: Inserted as is, with no sanitization or formatting. Only use this for text that has already been prepared for HTML display (for example, user-supplied text that has already been run through check_plain() previously, or is expected to contain some limited HTML tags and has already been run through filter_xss() previously).


What's the best way to create variables that are available to every single URL on my site, based on node id or taxonomy id?

I've found a very satisfactory solution using function matchtheme_preprocess(&$variables, $hook) which will always supply variables to page and node templates.

The more complicated bit was finding an appropriate way to get this function to collect the data I need (nid or tid) properly regardless of whether it was the page or node template making the call.

Essentially (this is the cut down version) I just did this:

if ($hook == "page"){
    // supplies variables to page.tpl.php
    // the page template can cover anything, including a node and taxonomy
    if (arg(0) == "node"){
        $nidToCheck = arg(1);
    } else if (arg(0) == "taxonomy"){
        // already a taxonomy page, the term id is the category
        $hasParents = arg(2);
    }
} else if ($hook == "node"){
    // supplies variables to node.tpl.php
    $nidToCheck = $variables['elements']['#node']->nid;
}

From there if ($nidToCheck) allows me to use the nid to generate $hasParents for nodes, and then I can move on handling all nodes and taxonomy terms to do what I want (all this bit is essentially the same as in my question).

Finally I feed back to the template an array of variables in much the same way as they were set before.

So glad to have this sorted as it caused quite a headache. Would love to hear whether or not this is an efficient or clever way of dealing with it. The most obvious issue to me is that the array of variables (and of course the whole function) will get run twice on node pages - once for the page template and once for the node template - which is a touch inefficent. I guess I could contain the whole thing in an if (!isset...


Is there a way to set the pager's page number programmatically without the page being in the url?

You can use AJAX to call a new request so you will not have the page in the URL
or, if you use Views, select "Use AJAX" under the Advanced Settings, and it will enable AJAX on your pager.


get taxonomy terms of specified language

I had some difficulties with printing tags in the current language in code too. This is what worked to get ONLY the translated terms of a vocabulary:

$vocabulary = 'MY_VOCABULARY_NAME';
$language =  \Drupal::languageManager()->getCurrentLanguage()->getId();
$query = \Drupal::entityQuery('taxonomy_term');
$query->condition('vid', $vocabulary);
$query->sort('weight');
$tids = $query->execute();
$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);
$termList = array();

foreach($terms as $term) {
    if($term->hasTranslation($language)){
        $tid = $term->id();
        $translated_term = \Drupal::service('entity.repository')->getTranslationFromContext($term, $language);
        $termList[$tid] = $translated_term->getName();
    }
}

// To print a list of translated terms.
foreach($termList as $tid => $name) {
     print $name;
}

To link the tags, see https://drupal.stackexchange.com/a/243160/71941


How to migrate using explode with occasional empty array

I solved this by creating my own migrate plugin that sets the multiple flag to false if we get an empty array, like this:

/**
 * The Get plugin causes issues for us when it fetches and array that is empty.
 *
 * It sets multiple to true which prevents the skip_on_empty plugin from being
 * triggered.
 * @see https://www.drupal.org/node/2905929
 *
 * @MigrateProcessPlugin(
 *   id = "get_array_fix_multiple",
 *   handle_multiples = TRUE
 * )
 */

class GetArrayFixMultiple extends ProcessPluginBase {

  /**
   * Flag indicating whether there are multiple values.
   *
   * @var bool
   */
  protected $multiple;

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
      $array = is_array($value);
      $empty = empty($value);
      $this->multiple = $array && !$empty;
      return $value;
  }

  /**
   * {@inheritdoc}
   */
  public function multiple() {
    return $this->multiple;
  }

}

Either the bug is in the get plugin or then skip_on_empty should support multiple.