What is the Features specific data in a Features module's .info file

Some of the documentation is sparse (still!?) https://drupal.org/node/1720098

The entries in your .info file tell Features that that item of your configuration is controlled by Features and not say Drupal core. You'll see stuff like ctools or views in there. In the main features.inc file the features info hook will require those API dependancies.

Based upon other lines in the info file such as:

features[ctools][] = strongarm:strongarm:1
features[ctools][] = views:views_default:3.0
features[user_permission][] = create features_test content
features[views_view][] = features_test

These lines would say, features uses Strongarm to read/write configuration of variables, and Ctools integration. Then there is some view features_test and some user permission exported create features_test content.

From the documentation page i linked these .info configuration values then:

  They are called during hook_module_enable/disable to fire the right
  stuff in the right places.

By Features itself. The info file contents tells Features what its managing. The .inc files include the dynamic configuration values needed per .info item entry (usually in terms of plain Drupal hook_info configuration definitions that'd you basically be making in code anyways).

I recommend reading the Features API and Readme:

http://drupalcode.org/project/features.git/blob/refs/heads/7.x-1.x:/API.txt

http://drupalcode.org/project/features.git/blob/refs/heads/7.x-1.x:/README.txt


Do I need to use drupal_mail after the hook_form_contact_site_form_alter?

You should use hook_mail_alter().

hook_mail_alter() allows you to modify the email cleanly before it is sent. The Contact module passes the entire form state to drupal_mail(), so you have access to it in this alter hook via the params key.

A quick example. I haven't tested it:

function my_module_mail_alter(&$message) {
  if ($message['id'] == 'contact_page_mail') {
    $phone = $message['params']['phone'];

    $message['body'][] = "Phone number: " . check_plain($phone);
  }
}

Let me know if that works.


What is the best practice or easiest way to import product types from their content type derivatives?

It sounds like you have your "content type" confused with your "product type". With Drupal Commerce, you need to add "products" which are of a particular "Product Type". Each product has at least a title, a SKU, and a price, but you could have more fields like size for example. You then attach the products to a product display node so that they are visible in the shop. A Product Display Node is a regular content type node with a product reference field that points to the product type entity.

You may be asking why do I need both product entities and product display entities? This is for the situation where you have multiple products included with each display. So if you have a clothing article that comes in small, medium and large sizes and is also available in either blue or green, then you have 6 SKUs for this clothing article. You would have 1 product display entities with product references to the 6 SKUs.

Your content type that is the product display should include the name of the product, the general description of the product and maybe an image of the product, etc. Your product type will have the SKU, the price, and any other fields that are unique to the SKU.

Read more (and probably better constructed examples) at the Commerce Guys site


How to use hook_form_alter in the .theme file to alter the form fields?

If you want to alter a specific form, and you know the ID, use hook_form_FORM_ID_alter() rather than the generic version:

function THEMENAME_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Add alterations specific to the user registration form
}

Make sure you clear the cache after renaming the function.


You don't need to do a full migration. You can initialize the Upgrade process by connecting to the old site and it will create migrations. Then you can, instead of executing them automatically, run just some of them with the UI provided by the upgrade_tools project ( I think?).

However, migrations have dependencies. To be able to run the node migration, by default you have to run a few others, e.g. users, text formats and also the fields.

You can try to change that by editing the created migrations either with drush cedit or export/import. I believe someone is also working on an UI for it.

You can also customize any mapping and how fields are migrated. The default behavior is that every field and configuration is migrated 1:1 but  to be honest, I can't imagine that's what most sites will want to do. Instead, I imagine they build a new D8 site and then import the content.

See the migration documentation. There are also plenty of blog posts available already around that topic but it's not a trivial thing to do.

https://drupalize.me/blog/201511/simple-drupal-7-drupal-8-migration
https://www.advomatic.com/blog/transforming-data-in-a-drupal-8-migration-step-by-step

Alternatively, you can try to export/import your content, as mentioned in the Comments, Feeds is not quite ready yet, but you could use a views export and import by writing some custom code.


There is a hook for that hook_entity_base_field_info(). The code could look something like this

/**
 * Implements hook_entity_base_field_info().
 */
function module_name_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'taxonomy_term') {
    $fields['new_field'] = \Drupal\Core\Field\BaseFieldDefinition::create('string')
      ->setLabel(t('Label'));

    // You can add more options about visibility configuration etc.

    return $fields;
  }
}

The above could add "hidden" field, (not visible in display or edit mode and not configurable). You need to do the same thing as when creating base fields in a custom entity.


Field Template Loop Counter Override Problem

I just tested this and it works for me:

   {% for item in items %}
        {% set counter = ( counter | default(0) ) + 0.2 %}

{{ item.content }}

      {% endfor %}

This renders as:

...

...

Note, I did not get the repeating depth numbers as you did above.


Latest Best Practise: Reusing content/functionality between Drupal 7 sites

There are two more options to consider:

User Drush make to create your own distribution:

  Drush make is an extension to drush that can create a ready-to-use
  drupal site, pulling sources from various locations. It does this by
  parsing a flat text file (similar to a drupal .info file) and
  downloading the sources it describes. In practical terms, this means
  that it is possible to distribute a complicated Drupal distribution as
  a single text file.

Run your sites in a multi site environment. This way you can easily reuse all installed modules and themes.

  If you are running more than one Drupal site, you can simplify
  management and upgrading of your sites by using the multi-site
  feature. Multi-site allows you to share a single Drupal installation
  (including core code, contributed modules, and themes) among several
  sites.


How to avoid calling FieldCollectionItemEntity::deleteRevision

Copy and Paste your own version of the FieldCollectionItemEntity class file and call it like FieldCollectionItemEntity2. Then simply like have FieldCollectionItemEntity::deleteRevision return or do a NO-OP. Use the new class in your migration instead of the default one you're using now.

For when the migration completes; implement like a PostImport() function to delete all but the most recent revision.

To my knowledge there is no Queue of revision items. A node/entity Save (and revisioning) I thought is done in a sql transaction statement.


Add an entity reference select to a form

Basing on the OP solution, I would suggest the follow code.

$options = [];
$goal_nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
  'type' => 'goal',
]);

foreach ($goal_nodes as $goal_node) {
  $options[$goal_node->id()] = $goal_node->label();
}

$form['commitment']['goal'] = [
  '#type' => 'select',
  '#title' => t('Goal'),
  '#options' => $options,
];

This has still two issues:

Entities are not translated
Bundle label ('Goal') is not  programmatically coming


Add a form between shipping method selection and order review

The payment panes makes this kind of interaction possible through a "details form" that open when you select the payment method that has this configured, and this is great because everything happens on the same page via ajax. But i don't know if Commerce Shipping has this too.
If not, i think that the best way for you to make this is to create a Checkout Page specific for your Shipping Method and create a Checkout Pane with your form to be in this page.

You can take a look at how https://drupal.org/project/commerce_correios handle this situation, because it's a Shipping Method too, so the API should have a lot in common with what you need.


When using views to create a list of nodes, how can I eliminate the link from the node title?

When you select node style, it uses your node.tpl.php file to create the node, so if that has a link in the title, it's gonna be there.  You can choose the "style" of node, eg, teaser or full, to change this behavior, and include or not include links and comments, etc.  Or, as you ask, go to Fields and have a lot more flexibility.


How to get the body trimmed when loading nodes programmatically?

You can get the trimmed summary using text_summary() which will allow you to pass the text, input format and choose the text size (length) you want.


Dynamically fill field when adding a new node

I don't know a clever way to link, so I would probably use the NID from campaign as a reference.

I'd create a integer field in order which would store the NID from the campaign on creation. i.e. The custom form would create a node of type order and automatically fill the value.

Then both objects have the same number which will function as a connection. You can use EntityFieldQuery to find the related objects whenever you have the campaign nid.

This is pretty crude though, hopefully there is a smarter way.

Here is some sample code (untested, probably will need a little debugging, paths are from memory).

function my_create_a_node_form() {
  //form stuff goes here.

}

function my_create_a_node_form_submit() {
  //menu_get_object retrieves the current objects that loaded. We're storing it
  // we're storing it in a variable.

  $currentcampaign = menu_get_object();

  //we collect the nid from the campaign.
  $currentnid = $currentcampaign->nid['value'];
  global $user;

  $values = array(
    'type' => 'order',
    'uid' => $user->uid,
    'status' => 1,
    'comment' => 1,
    'promote' => 0,
  );
  $entity = entity_create('node', $values);

  $ewrapper = entity_metadata_wrapper('node', $entity);
  $ewrapper->title->set('YOUR TITLE');

  //here we store the nid in our pre set-up order field.
  $ewrapper->field_my_order_ref->set('$currentnid');

  //the rest of this is just standard create a node stuff.
  $my_body_content = 'A bunch of text about things that interest me';
  $ewrapper->body->set(array('value' => $my_body_content));
  $ewrapper->body->summary->set('Things that interest me');

  $my_date = new DateTime('January 1, 2013');
  $entity->field_my_date[LANGUAGE_NONE][0] = array(
     'value' => date_format($my_date, 'Y-m-d'),
     'timezone' => 'UTC',
     'timezone_db' => 'UTC',
   );

  $ewrapper->save(true);
  entity_save('node', $entity);

}


Drush ignoring `$options['config']` statement in drushrc file from the 'drush' folder at the root of the current git repository

As Clive said, the snipped goes in $HOME/.drush/drushrc.php, not in the drushrc.php file in your site folder.  The drushrc.php in your site folder does not get parsed until Drush bootstraps your site; by that time, it's too late to add items to the 'config' list, as it has already been processed.

Also, in place of:

$repo_dir = drush_get_option('root') ? drush_get_option('root') : getcwd();

... it would probably be better if the snippet used:

$repo_dir = drush_get_context('DRUSH_SELECTED_DRUPAL_ROOT') ? drush_get_context('DRUSH_SELECTED_DRUPAL_ROOT') : getcwd();

Finally, rather than setting the 'config' option, which is gitchy and a little high-strung, you could just include your drushrc.php directly.

Replace:

$options['config'] = $repo . '/drush/drushrc.php';

with:

include $repo . '/drush/drushrc.php';

Then you could go back to putting this snippet in your sites/all/drush/drushrc.php, if that's working better for you.


List publications by same Author on Staff page

use views and add a relationship to the author inside the view


Best Method to Separate Drupal Website from Customized Scripts

There's no way to use Drupal Apis from a separate server. Your best bet would be to use the web service module and process your request via json.

You'll have to do more work but on second hand, you'll end up with a nifty setup that'll allow you to leverage many other frameworks such as angularjs, backbone, and even mobile development.


Extract the CSS class depending on the user type

If $user is the user object, then $user->roles is an array containing all the roles the user has. Drupal doesn't have the concept of user type, and the user roles are the closest it has.

If you want to check if the user has the "editor" role, for example, you can use code similar to the following one:

$global $user;

if (in_array(array_values($user->roles), "editor")) {
  // The user has the "editor" role.
}

Depending on what you are trying to achieve, you could also be interested in checking if the user has a specific permission, which is what is normally done in Drupal, where instead of checking the role assigned to a user, it is checked which permission the user has (using user_access()).

As for hiding a form field, this can be done implementing hook_form_alter(), or hook_form_FORM_ID_alter() and altering the property "#access" of the form field.

Supposing that "example_form" is the form ID for the form you want to modify, and "file" is the ID for the form field to change, then you can use code similar to the following one ("mymodule" is the name of the module; change it to match the name of the module that contains the hook):

function mymodule_form_example_form_alter(&$form, &$form_state) {
  $form['file']['#access'] = user_access('administer file');
}

"Administer file" is the permission that the user needs to have.
Alternatively, if you want to only check if the user has the "editor" role, you can use code similar to the following one:

function mymodule_form_example_form_alter(&$form, &$form_state) {
  global $user;

  $form['file']['#access'] = in_array(array_values($user->roles), "editor");
}

The global variable contains the user object for the currently logged in user.


How to create Page variant Selection rule "if URL contains"?

Try under Variant -> Selection rules, in the pulldown Select:URL Path then Add. In the new dialog box, select "Allow access to the following pages" then enter "cars/*" in the textarea, then save. According the description below the textarea which says

The '*' character is a wildcard. Example paths are blog for the blog page and blog/* for every personal blog.


Validation when having 2 webform in same page?

Try changing the field name of one of the 'name' fields to that they are unique across both forms.
You'll need to copy the webform-submissions.tpl.php from the Webform module into your theme, and update the link at the bottom.


How to add author's user role as CSS class to comments?

This can be done pretty easily by preprocessing your comments.

But first of all, very important: don't edit any of Bartik's files (or any core files in general). Create a sub-theme, copy the comment.html.twig to your sub-theme's templates directory and edit that file.

Second, depending on your CSS setup comment_author_is_administrator doesn't seem like a legit CSS class. Normally, underscores are not allowed to be used that way. And maybe you can make it a little bit shorter. Maybe just author-administrator.

Finally, simply place the following snippet in you sub-theme's *.theme file and replace MYTHEME with your actual theme name.

/**
 * Implements template_preprocess_comment.
 */
function MYTHEME_preprocess_comment(&$variables) {

  // Get the comment.
  $comment = $variables['comment'];

  // Get its owner.
  $owner = $comment->getOwner();

  // Check for administrator role.
  if ($owner->hasRole('administrator')) {

    // Append CSS class.
    $variables['attributes']['class'][] = 'author-administrator';
  }
}

Alternatively, you could simply append each comment's author role as CSS class like following.

/**
 * Implements template_preprocess_page.
 */
function MYTHEME_preprocess_comment(&$variables) {

  $comment = $variables['comment'];
  $owner = $comment->getOwner();
  $roles = $owner->getRoles();

  // Let's pop the roles array to only
  // get the last (highest) role of all.
  $role = array_pop($roles)

  $variables['attributes']['class'][] = 'author-' . $role;
}


Attach behavior only to the file upload button

You can simply be more specific with your jQuery selector. For example, you could theme_file_managed_file to give your upload button it's own class and then change your jQuery('input.form-submit', context) line to include that class in the selector.

jQuery('input.my-upload-class', context)


Will "features" be overwritten when there is a distribution update?

Yes, they will be marked as overriden.
The Features Override was designed for this use case, so try it and report back.


how to reinitiate a default field value every time the content edition is loaded?

You need to use hook_form_alter

    use Drupal\Core\Form\FormStateInterface;

    /*
     * Implementation of hook_form_alter()
     */
    function mymod_form_alter(&$form, FormStateInterface $form_state, $form_id) {
      if($form_id == 'node_evenement_edit_form'){ // target a specific form
        $form['field_notif']['widget']['#default_value'] = 0;
      }
    }


You may need to enable the Display Suite Extras module. (comes with display suite)

Go to manage display, scroll all the way down. Click on custom fields, add a block field.


Migrate: Create term(s) if they do not yet exist

Wow, ok, getting better at parsing the docs/code for migrate plus. I found it as soon as I posted. The entity_generate plugin will do this behavior.

  field_paper_jel_codes:
    plugin: entity_generate
    source: jel_codes

Now I have a system full of taxonomy.


Here's a simple example of creating a node in Drupal 8.

$data = [
  'type' => 'article',
  'title' => 'My new title',
  'uid' => 1
];
$node = Drupal::entityTypeManager()
  ->getStorage('node')
  ->create($data);
$node->save();

Updated to remove deprecated function as per comments from @mradcliffe. Thanks!

FYI, for testing out little snippets of code like this, the drush core-cli command works great. See: http://www.drushcommands.com/drush-7x/core/core-cli


Custom template for a specific page within module for Drupal 7

I believe the original template name you had with the percent symbol was correct. The problem is you are doing it in a module, not in a theme.

By default, you have to put the template in your theme for it to be picked up automatically.

Also, in module info files, the use of files[] = something.ext is only for files that contain classes, so Drupal can autoload them. Files like template files, module files, installation files, etc. don't go in there.


Use datefield year as condition in Entity Query

Assuming the data in the database looks like this: "2015-10-12T21:30:00", you can use a like query

->condition('field_date', $year . '%', 'like')

Your code revised with the change:

$year = 2015;
$query = \Drupal::entityQuery('node')
  ->sort('field_date', 'DESC')
  ->condition('type', 'news')
  ->condition('field_date', $year . '%', 'like')
  ->range(0, 10);


How do I check the version of a third-party module?

You can use system_get_info('module',  'devel') function and split version to get number after 7.x-
Or goes with this aproach parsing info file here is a solution from stackoverflow get a module version


Have a look at this, rather basic, rule (in Rules export format):

{ "rules_check_taxonomy_term" : {
    "LABEL" : "Check Taxonomy Term",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_issue_type" } },
      { "list_contains" : { "list" : [ "node:field-issue-type" ], "item" : "4" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "A node containing the tag [node:field_issue_type] just got created or updated." } }
    ]
  }
}

Here is what this rule does:

Rules Event: After saving new content, After updating existing content
Rules Conditions:

Entity has field "field_issue_type", which is the machine name of the term reference field I want to check for.
List contains item "node:field-issue-type" and with Taxonomy term identifier value "4" (which is the term id of the term I want to check in this Rules Condition).

Rules Action: Show a message on the site (which is "A node containing the tag [node:field_issue_type] just got created or updated." (with [node:field_issue_type] the actual term with term id = 4).

What is crucial in the above rules example in the context of this question, are the 2 Rules Conditions. Especially because of your extra comment "field_issue_type is a multiple value" (only "List contains item" is the Rules Condition that will do the trick ...).

Use the Rules UI to import the above rule in your site. Here are the tweaks you'll need to make it fit your case:

Within the Rules Conditions, adapt the "term id" (= "4") to fit your case.
Replace the Rules Action by what you want to happen as per the "set the next Issue Dates content type to be unpublished" in your question, which should really be a different (followup?) question.

PS: This answer applies to D7.


how to migrate a multi-value term reference field?

Yes. The migration of term doesn't allow to migrate multi-value. You have to process the source ahead.

Create a new migration and import the data to terms of vocabulary named 'voc_features' at first.
Add a dependence to your current migration using previous migration. Such as $this->dependencies = array('MigrateXXXMigration');.
The field mapping should be like this,$this->addFieldMapping('field_features', 'Features')->arguments(array('source_type' => 'tid'));
In the function prepareRow($row), you should prepare the Features field and put it into your $row variable. $row->Features=array(tid1,tid2,tid3);. The 'tid1','tid2' and 'tid3' should be replace the live tid from your term tables.


MySQL Error: Duplicate Entry on indexing taxonomy structure with Search API

I raised an issue in the Search API queue which then got patched. Forgot to post about it here. My bad.

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


Note that Drush and Drupal use different php.ini files.  This behavior is inherited from php, which allows for different configuration for commandline tools vs. web servers, so that your web server can be more locked down than your dev tools.

Use the drush status command to see the path to the php.ini file that Drush is using.

Use the drush status-report command to see the commandline equivalent of the reports -> site status page.  This will show you the real memory limit that is set for Drush.

Odds are, all you will need to do is change the memory limit setting in the php.ini file that Drush is using, and all will be well.


How to change a field value in a product variation when someone edited the order manually?

Is there any event when order items is edited?

You could use hook_ENTITY_TYPE_update

/*
 * Implements hook_ENTITY_TYPE_update()
 */
function mymodule_order_update(\Drupal\commerce_order\Entity\OrderInterface $order) {
  // your code goes here
}

If you don't want to use a hook, then consider using the Hook Event Dispatcher module.

  This module dispatches events for several Drupal core hooks. This
  allows you to use the D8 Event Subscriber system, instead of the
  outdated hook system, to react on certain events. The module includes
  events for the most common hooks.


Commerce- How can I track order details (products, quantities) in PayPal?

Right now, Commerce PayPal does not itemize order information for PayPal WPS. We implemented itemized order details for Express Checkout in the 2.0 branch, but we currently just have a patch in a feature request to add this support to WPS. If you'd like to review it or follow along, the issue is here: https://drupal.org/node/1301570

In the meantime, your alternative could be to create a View inside your Drupal site that uses Views Bonus Pack to generate a CSV in the same format for your completed orders. That might even be a preferable long term solution, as it will work regardless of what payment method a customer uses to buy from you (in the event that you add additional methods).


Active trail not producing expected results

It looks like your adding $people to the end of the array, you have to insert it in second place, using http://php.net/manual/en/function.array-pop.php you can do something like this (untested):

$name = array_pop($active_trail);
$active_trail[] = $people;
$active_trail[] = $name;


How to import an external database to D8 and create a search form?

The best and most flexible option at your disposal will be to use the Drupal Migrate module. It's included by default in D8.

The steps you'll have to follow is as below:

Migrate your data from MySQl to a Drupal content type or an entity. You could also consider exporting your data to CSV and import from the CSV.
If you are not expecting very large traffic, use views and exposed filter to implement your search form with filters. If you are expecting the more traffic and scale user search_api and use something like Solr in the backend.

Some of the links where you can get started:

Migrate to Drupal 8 from MySql.
Migrate to Drupal 8 from CSV file.
Official Migrate API documentation.

I am assuming you already know what content type, entity, views, exposed filters etc are. In case you don't know any of it, plenty of resources are available online.


How to grant permission to a node for an user programatically?

You may want to program it yourself, you can have something like this, probably implementing hook_init():

function my_module_init() {
  global $user;

  $nid = 85; // We'll check node 85.

  // Users with access:
  $uids = array(
    3,
    9,
    11,
  );

  $node_path = 'node/' . $nid;

  // Check if the user is in the node detail.
  if (current_path() == $node_path) {
    // Check if the user is not in the list of allowed users.
    if (!in_array($user->uid, $uids)) {
      drupal_access_denied();
    }
  }
}


How to add "browse" button in image in CKE Editor?

May be IMCE  module will solve your problem !

  IMCE is an image/file uploader and browser that supports personal
  directories and quota.


How can I render HTML tags in a variable in a twig template?

my variable was rendered through
  \Drupal::service('renderer')->render()

Don't do that - Drupal sets Twig up to understand render arrays. Just use:

{{ original_description_render_array }}


Why are URL encoded values in $_GET variables broken?

Sounds like your incoming data is ISO-8859-1, not the other way round. Drupal is always in UTF-8 (and utf8_encode converts from ISO-8859-1 to UTF8).

This is what I get when urlencoding Ü.:

$ drush ev 'var_dump(urlencode('ü'));'
string(6) "%C3%BC"

And when urldecoding and utf8 encoding %DC:

$ drush ev "var_dump(utf8_encode(urldecode('%DC')));"
string(2) "Ü"

Makes all perfect sense to me.


How to use DataDefinition::create('list')?

ItemList is a generic base class. List is used here in the context of multivalued field items. Because Drupal has no separate class for single value fields (they are multivalued fields restricted to one value), this generic list data type is used in all Drupal fields.

When you look at the list of field types

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21Annotation%21FieldType.php/class/annotations/FieldType/8.4.x

you'll find ListStringItem, where List is used in the context you are probably looking for and you can use this as an example for this kind of field types implementing OptionsProviderInterface.


You get a more link (that links to the node) if your view lists nodes in the teaser view mode. For any other case the situation is more complex.

Ongoing discussion about this issue: https://drupal.org/node/823380 "More link is always visible on teaser".

Perhaps the best solution for the time being:
https://drupal.org/project/readmorecontrol


.htaccess error on local site in docksal

There is a directory in the root of the Acquia project, config/default.So, all you need it's make it writable.

or you can  change $config_directories['vcs'] and $config_directories['sync'] in your settings.php to somewhere which will be writable .


How do I customize the location of a webform for a node type?

You were almost there. Use the following code.

<?php print render($content['webform']); ?>

Bear in mind that if you are rendering the webform before the line containing print render($content);, you would need to hide the output of $content['webform'] first, and then render it manually. In this case the code would be similar to the following one.

<?php
// This would go at the beginning of the .tpl.php file, for better readability.
// Hide the webform from rendering, because we will do it manually.
hide($content['webform']);
?>

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

<?php print render($content['webform']); ?>

Generally speaking, I think it is a good practice to always hide elements you want to render separately, just in case at some point you move them before the render($content) line.


How to use the Rules module to publish all nodes authored by a user when the user's role changes?

Yes this can be done with the Rules module. Here is a summary of what you'll need to get it to work:

Keep track of all node IDs of a user that still need to be published later on (after the user approves the cellphone number). For this add an entity reference to the user's profile (multiple values allowed). And each time such unpublished node get's saved you need to add the reference to that node as an extra value in this entity reference field (= Rule 1). So basically this is the "queue" of nodes for a user that need "post processing" after the user approves the cellphone number. It is will serve as your entry point starting from the user's id to "access (find) the exact node ids again later on".
Create a rules component (= Rule 2, though of type "component") with parameter just a "node id". All this Rules component has to do, is to "publish" the node indicated in the parameter. But you can add any Rules "Conditions" also if you'd need any (already now or later on if requirements change). E.g: check that the node is not published yet, only for specific content types or user roles, etc.
Create a rule (= Rule 3) containing a Loop that should be triggered after the user approves the cellphone number. The goal of this rule is to loop over each of the nodes in the reference field from Step 1, and in each iteration of that loop you use an action which is to invoke the Rule Component as detailed in Step 2 (and which uses the node id as a parameter). By using a Rules Component, you'll be able to add any "Conditions" you might need inside the "Loop".

Video tutorials

If you're not familiar (enough/yet) with using Loops in rules, then watch the video about List and loops.

For a video that is fairly similar to what's needed in step 2 and step 3, refer to the 2nd video (= Solution video) about Creating multiple back links. Some more details about how your scenario slightly differs from what is shown in that solution video:

You are creating an entity reference to nodes also, but from a user (not a node).
You only need the first parameter (= Node to link to) in your Rules component (you don't need the 2nd parameter).


How to render a node on behalf of another user (as an admin or without accessCheck)

Thanks to the comment of @No Sssweat I could find a solution:
Summary: the problem appeared when emails were sent via a queue in a cron. The cron is running as an anonymous user, and, in this case, the drupal viewBuilder/Rendering system doesn't have enough permission to display some fields/nodes.
Solution: Adapt the processItem function of the QueueWorker in order to switch the current user into an admin user at the beginning of the process and switch back at the end.
I my use case, I overrode the QueueWorker provided by another module. Here is my code with the injection of the switcher service: (feel free to comment)
/**
 * The account switcher service.
 *
 * @var \Drupal\Core\Session\AccountSwitcherInterface
 */
protected $accountSwitcher;

public function __construct(array $configuration, $plugin_id, $plugin_definition, SubscribersInterface $subscribers, AccountSwitcherInterface $account_switcher)
{
    parent::__construct($configuration, $plugin_id, $plugin_definition, $subscribers);
    $this->accountSwitcher = $account_switcher;
}

public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition)
{
    return new static($configuration, $plugin_id, $plugin_definition, $container->get('message_subscribe.subscribers'), $container->get('account_switcher'));
}

public function processItem($data)
{
    $this->accountSwitcher->switchTo(new UserSession([
        'uid' => 1,
        'name' => 'cron_admin',
        'roles' => ['administrator'],
    ]));
    parent::processItem($data);
    $this->accountSwitcher->switchBack();
}


Allow multiple instances of reCAPTCHA on the same page

The issue was first open for the developer version 7.x-1.x-dev, which contains that file; then it was updated for 8.x-2.x-dev, and then 7.x-2.x-dev. You need to install the developer version, and apply the patch for that developer version.


Is there a way to expose the pager fields?

Yes, you can do that with Views.

In the pager settings for the View, select to expose the number of items to the user.

Make sure the textfield with available items per page options includes the default number of items per page.


How to add alphabetized pager using glossary view?

There is a module, Views Glossary, which provide different options to glossary views. According to the docs, it provide following features:

  A special kind of layout to glossary view (which is available by
  default with views) or any view, see in screenshot.
  Providing pager with selectbox and textbox.
  A default view is added for example.
  Making items per pager independent of expose form submit. (A usability
  improvement)


You can add such a clause manually:

$not_exist_query->where('ur.entity_id = u.uid');


Restrict node to be shown only in a view and not by its url?

The purpose of the Rabbit Hole module is exactly that, even if it doesn't apply just in the view case.

  Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.

  Perhaps you have a content type that never should be displayed on its own page, like an image content type that's displayed in a carousel. Rabbit Hole can prevent this node from being accessible on its own page, through node/xxx.

The module has a version for Drupal 7 and Drupal 8, although the later is still a beta version, on December, 2019.


Difference between $form_state['values'] and $form_state['input']

The crucial difference here is that in most cases you should be using $form_state['values']; since the data on the $form_state['input'] array is raw and unvalidated.

$form_state['input'] is useful for multi-step forms, assuming you are familiar with how to safely handle raw input.... See form_builder for more information...


As CommentStorage::loadThread adds comment_filter tag to its query, you may use hook_query_TAG_alter hook to change comments order:

/**
 * Implements hook_query_TAG_alter() for comment_filter tag.
 *
 * @see CommentStorage::loadThread().
 */
function mymodule_query_comment_filter_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  // Change comment order to DESC for 'comment' field.
  if ($query->getMetaData('field_name') == 'comment') {
    /** @var \Drupal\Core\Database\Query\SelectInterface $query */
    $order_by = &$query->getOrderBy();
    // 'c.cid' is for flat comment lists.
    if (isset($order_by['c.cid']) && $order_by['c.cid'] == 'ASC') {
      $order_by['c.cid'] = 'DESC';
    }
    // 'torder' is for threated comment lists.
    if (isset($order_by['torder']) && $order_by['torder'] == 'ASC') {
      $order_by['torder'] = 'DESC';
    }
  }
}


apply css for particular node and do not apply for particular node

This is the sort of thing that I'd do by code, but that's because that's just the way I roll.

In the template.php you will want something like:

function MYTHEME_preprocess_node($vars) {
  if (drupal_get_path_alias(current_path()) == 'node/add') {
    drupal_add_css(drupal_get_path('theme', 'MYTHEME') . "/css/foo.css");
  }
}

I hope this helps.. :)


How to give different permissions for different domains

Is seems that Domain Strict, a Domain Access submodule, may help you, as stated in this issue:

  DA is a node access module (which is designed to enhance what 'access
  content' means), and you should be able to do this now by using Domain
  Strict and configuring user behaviors.

  Domain Strict forces people to be members of a domain in order to view
  its content. You would enable the module, then you will note:

  1) Anonymous users cannot access any content. This is because they
  cannot be assigned to a domain (since thiey have no account).

  However, you can use the User Defaults setting page to assign
  anonymous users to the primary domain.

  2) Use the same User Defaults setting to assign all 'authenticated'
  users to the domain(s) you prefer.

  Under this setup, anonymous users would still have the 'access
  content' permission, but can only see nodes posted to the primary
  domain.

  See section 4.10 of README.txt and the README for Domain Strict.

Check also README.txt from Domain Strict.

  [Domain Strict] it changes the default Domain Access behavior.  This
  module makes the grants given to a user specific to the domains that
  the user is registered to see.

You'll have to deal with User Defaults setting to set permissions for anonynmous users since initially they don't have domain assigned.


This is not the normal Drupal behavior.  In this case, what you need to do is start disabling modules one at a time.

Disable a module that you think might be causing the problem (just take a guess) and then create a piece of content to see if two pieces of content are created.  If you disable a module and then create content and you only get one piece of content, you know you have found the problem module.

Once you find the problem module, try to locate the source of the problem in the module configuration.  If you can't find it yourself, try asking again on this site.

Without knowing what module is causing the problem, it is very hard to answer your question, as there are too many potential modules that can cause problems.


I wound up doing this to solve this case:

<?php

namespace Drupal\mymodule\Plugin\migrate\destination;

use Drupal\migrate\Plugin\migrate\destination\EntityContentBase;
use Drupal\migrate\Plugin\MigrationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\node\NodeInterface;

/**
 * We need rollback support for deleting files.
 *
 * @MigrateDestination(
 *   id = "myplugin"
 * )
 */
class MyPlugin extends EntityContentBase {

  /** @var string $entityType */
  public static $entityType = 'node';

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
    return parent::create($container, $configuration, 'entity:' . static::$entityType, $plugin_definition, $migration);
  }

  /**
   * {@inheritdoc}
   */
  public function rollback(array $destination_identifier) {
    $entity = $this->storage->load(reset($destination_identifier));

    // Delete attached files on Working Papers.
    if ($entity && $entity instanceof NodeInterface) {
      if ($entity->bundle() === 'working_paper') {
        $fid = $entity->get('field_paper_working_paper')->target_id;

        if ($fid) {
          $storage_handler = \Drupal::entityTypeManager()->getStorage('file');
          $entities = $storage_handler->load($fid);
          $storage_handler->delete([$entities]);
        }
      }
    }

    // Execute the normal rollback from here.
    parent::rollback($destination_identifier);
  }

}

In the migration yaml definition, point destination at this instead of entity:node:

destination:
  plugin: myplugin
  bundle: working_paper

The $entityType member and create method seemed to be required as well, otherwise Migrate did not seem to know how to parse this into a node of a particular type, despite extending from EntityContentBase.

The reason for wanting to do this is that its cumbersome especially while developing that files are not removed along with their entity on rollback. In my case, I have strictest confidence in that the rollback of this entity does not affect anything else because this is the only place this file will ever appear.

Is this the best way to add this type of behavior?


Automatically generate product variations

Well, I did have a look around I could not get Commerce Bulk module to install.
Then I saw https://www.drupal.org/project/commerce/issues/2755529, which will be a sweet feature when it has been merged. I could not get the patch to apply so I ended up creating a sandbox module based on this and here we go:
https://www.drupal.org/sandbox/taggartj/3104497

Judging by your rank you will know how to get the code.

https://git.drupalcode.org/sandbox/taggartj-3104497/commit/7997ee4

This module will give you a route (no link yet):

You need to create at least one Product variation manually, then go to:

"/product/PRODUCTID/variations/VARIATIONID/bulk-generate"

or example /product/331/variations/1/bulk-generate, for it to allow you to bulk generate your variations.


disable comment module
uninstall comment module
enable comment module


The Form API is your friend. Take a look in the Form API Quickstart Guide, how to change a form for your needs.


Newbie Simple D and Views question about grouping and "exclude from display"

What was the problem? After adding "Grouping", I mistakenly thought Filter might contain the Exclude solution. I added it. Then, I recall, clicking Remove, but evidently I did not, or whatever.

Next, I found the correct setting: "Fields: Exclude from display", and then saved. But, what I saw on my end-user page (not preview) between changes was, 1) Grouping take effect, 2) Filter do nothing, 3) Exclude make a "blank page". I'm thinking there are some changes which take effect on the end-user page right away and other that do not.

I'm going to try a new Views Development Workflow: 1) Export often, 2) Use save between each change, 3) Roll Back when things get weird. Repeat. And use the Preview instead of looking at my end-user page.


How can I remove the title in a specific node?

You can use  the Automatic Nodetitles module.

  "auto_nodetitle" is a small and efficient module that allows hiding of the content title field in the form. To prevent empty content title fields one can configure it to generate the title by a given pattern.

If you want to hide the title for the particular node or content type, then you should use hook_form_alter().


Change where the theme gets its files from

drupal_get_path and path_to_theme are the two functions that will be usefull for u.


Trying to write my own Views filter handler

In your specific case, since "taxonomy_term_hierarchy" already exists in the views data, you want to implement hook_views_data_alter() instead, making your implementation much simpler (untested):

function foo_views_data_alter(&$data) {
  $data['taxonomy_term_hierarchy']['has_children'] = array(
    'title' => t('Has children terms'),
    'help' => t('Check if the term has direct children'),
    'filter' => array(
      'help' => t('My Help'),
      'handler' => 'views_handler_filter_term_children',
    ),
  );
}

As far as what filter to extend, a good one might be views_handler_filter_boolean_operator but you can just start from views_handler_filter too.


rule to remove "Public files directory Not fully protected" in nginx?

The .htaccess file won't have any effect in Nginx. You'll need to add your own rules to prevent PHP execution in the files directory.

e.g:

# Allow access to index.php only
location = /index.php {
  include fastcgi.conf;
  fastcgi_pass    127.0.0.1:9000;
}

# Any other attempt to access PHP files returns a 403.
location ~ \.php$ {
  return 403;
}

However, to fix that error message, you can actually just delete the old .htaccess file and Drupal will recreate a new correct one.

Note: the check is in system_requirements with the line

if (!file_exists($htaccess_file) || !($contents = @file_get_contents($htaccess_file)) || strpos($contents, 'Drupal_Security_Do_Not_Remove_See_SA_2013_003') === FALSE) {

It only checks for that line, Drupal doesn't currently validate an actual PHP request to the relevant directory to test the handler.


How to add a cck email field as default value in webform

If you are using the Email Field module then it is possible.

In your view choose your email field , on Format option choose the Email contact form option.  It won't expose the email.


How to solve the "The following module is missing from the file system" error?

If you have Drupal Console then a quick way to fix this is to generate a module with the same machine name, then uninstall it.

$ drupal generate:module

Then type the machine name at the appropriate prompt and accepts defaults for everything else.

$ drush pm-uninstall

Then you can delete the newly generated module from the file system and continue with your day.

(NB you may find need to keep that generated module, else the error will return. In that case, if you need to install a contrib module with the same name, remove the generated module after adding the contrib module. Then clear the cache.)


Creating a dynamic URL in node--resource.tpl.php

The title is defined for a node.tpl.php file as $title, and the node id can be retrieved with: <?php print $node->nid; ?>  therefore, it should read something like this:

  <a href="/content/specific-resource-feedback?nid=<?php print $node->nid; ?>&title= <?php print $title; ?>">
  Trouble with this resource? Let us know.


The easiest way to avoid the standard field divs is to only print out the first delta. That works well for single-value fields, for multiple, you'd need to loop over it yourself.

So, just do this: {{ content.field_year.0 }} and it will only print out the actual field content, without the wrapping field type. Might not work for every formatter, depending on what they do, but it should work for most of them.


Set dropdown list programmatically in exposed view filters

Add the following to your form_alter implementation:

$form['field_1hour_currency']['#multiple'] = FALSE;
$form['field_1hour_currency']['#size'] = 0;


unable to migrate site from one server to another

Have you tried backup migrate?

http://drupal.org/project/backup_migrate

Make sure you have a vanilla drupal install working perfectly, then copy the sites/all folder from your first server, enable backup migrate and then restore the backup from the first server.

Basically, it will be a lot easier to troubleshoot if you're on a vanilla install and backup migrate is perfect for this.


Use webprofiler to see entire query from view

Check the saved profiles by the Webprofiler module via /admin/reports/profiler/list.

Go to the profile with the the same URL as your view and open it. Select the Database option on the left and search (CTRL+F) for the following string: D\v\ViewExecutable::execute.

You will find queries executed by the ViewExecutable class which is responsible for the data generation and query execution of your view.


How to create a drag & drop sorting interface programmatically?

Here is a drupal_add_tabledrag function using which you can add draggable functionality programmatically.

  Assists in adding the tableDrag JavaScript behavior to a themed table.

  Draggable tables should be used wherever an outline or list of
  sortable items needs to be arranged by an end-user. Draggable tables
  are very flexible and can manipulate the value of form elements placed
  within individual columns.

See this blog for example. You may need to imprement theme function.

$element = $vars['element'];
drupal_add_tabledrag('sample_table', 'order', 'sibling', 'item-row-weight');

$header = array(
  'label' => t('Attribute'),
  'checkbox' => t('Enabled/disabled'),
  'weight' => t('Weight'),
);


Any idea on how to include a an option in display handler in views

Since you want to add the configuration of the display (which is a plugin), you have two options:

Create a new display plugin
Change the class of the existing page plugin.

The two options are essentially the same, in the sense that you need to create a custom plugin class for views display. The only difference is if you alter what the plugin manager has stored or if you define a new one.

You should extend the existing \Drupal\views\Plugin\views\display\Page class.

Most of the stuff, you don't need to worry about, but you need to extend the following methods:

defineOptions
buildOptionsForm
submitOptionsForm

A very simple implementation of a new plugin class (totally untested code, but should work with small alterations)

use Drupal\views\Plugin\views\display\Page

/**
 * Custom page display to add more options.
 *
 * @ViewsDisplay(
 *   id = "custom_page",
 *   title = @Translation("Custom Page"),
 *   help = @Translation("Display the view as a page, with a URL and menu links."),
 *   uses_menu_links = TRUE,
 *   uses_route = TRUE,
 *   contextual_links_locations = {"page"},
 *   theme = "views_view",
 *   admin = @Translation("Custom Page")
 * )
 */
class CustomPage extends Page {

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['custom'] = [
      'contains' => [
        'checkbox' => ['default' => FALSE],
      ],
    ];
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
    // A bit tricky, since views uses a concept of sections. Either you need
    // to define your own section or you can just add your config to an existing
    // section. If you use an existing it will be a lot easier.
  }

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

    switch ($form_state->get('section')) {
      case '?':
        $values = $form_state->getValue('?');
        $this->setOption('custom', $values);
        break;
    }
  }
}


Create new content type with a user reference

Your user selection/search process may need some custom work to implement the various node-reference modules in the way you've described, but there are several modules that may do what you need out of the box. The References module will be easier to implement while creating new content, but the Relation module may be more agile as you can add fields to your relations, 'user report' for example.

I would be happy to elaborate if you'll clarify your user selection process.

1 - References

This adds a field to an already created content type.  Generally simpler to implement.

  This project provides D7 versions of the 'Node reference' and 'User
  reference' field types, that were part of the CCK package in D6, at
  functional parity with the D6 counterparts. See
  http://drupal.org/node/533222 for details.

Video Series (NodeOne) Using the Reference module

2 - Relation

Rather than being a 'field' on an already created content type this is for all intents and purposes a new content type.  Relations are fieldable as well, so adding the 'report' fields you need will be easy.

  Relation is an API module and storage model for both simple and the
  most complex relations between entities. The module can handle both
  directional and symmetrical relations very well.

Video Series (NodeOne) Learn the Relation Module


You don't need any changes to your database, with HS Or SHS you already store enough data to built a template answering your needs.

From my point of view, once your view is configured, you can alter the display of your field while overriding the default TPL file.

From the view edit page, if you go into "Theme: Information", you can find the name of the file you need to create and place into your theme folder.

The file name should look like this:

views-view-field--name-of-your-view--name-of-your-field.tpl.php

As a base for you file, you should use views-view-field.tpl.php (located in sites/all/modules/views/theme). In that template, there's some variables available to help you build what you want (like $row or $field).

If you have Hierarchical Select installed, you can simply render the field, it will display data the way you want.

Here's some untested code:

$field = field_view_field('entity_name', $fully_loaded_entity, 'your_field_name');
print render($field);

For that chunck of code to work, you need to specify if you're working with a node, user or term, pass the loaded entity and give the corresponding field name.

The rendered HTML should be enough to build something like this (made with the exact same method):


There is a property on the node object called "created". This is what you are after and can be used in the exact same way you have used "changed".

<?php print format_date($node->created, 'article'); ?>


imagecache_presets

Get an array of all presets and their settings.

Parameters

reset: if set to TRUE it will clear the preset cache

Return value

array of presets array( $preset_id => array('presetid' => integer, 'presetname' => string))


How do I specify the debug_mail_directory for the devel maillog?

You should use

$config['devel.settings']['debug_mail_directory'] = 'private://mydirectory';
$config['devel.settings']['debug_mail_file_format'] = 'mypattern-%to-%subject-%datetime.mail.txt';


The reason the Samsung Air Conditioner Unit was not showing as we clicked on the category was because we inserted as  Product Categories\Air Conditioner\Air Conditioning Unit instead of Product Categories\Air Conditioning Unit.

The subcategory Air Conditioner was not defined.  So, drupal did not know how to display it.  Once we moved to Product Catogoies\Air Conditioning Unit, it displayed.

Now, the task is how to create the subcategory Air Conditioners so that we could insert Air Conditioner Unit there instead of inserting it directly under Product Categories.


Devel dsm() function in Drupal 8 page.html.twig

Why not just do it in hook_preprocess_page() instead.

<?php
function MYMODULE_preprocess_page(&$variables) {
  dpm($variables);
}


There are several ways to specify which Drupal site Drush will target; the alias is probably the simplest.

The second option is more verbose, but it does not require an alias file.  Run:

$(drush --root=/path/to/drupal --uri=http://mysite.com dd my_theme)

You can do the same thing with a slightly different syntax:

$(drush /path/to/drupal#mysite.com dd my_theme)

You can also specify the Drupal site implicitly, by setting the cwd to the folder that contains the settings.php file for your site:

cd /path/to/drupal/sites/default # or /path/to/drupal/sites/mysite.com, as appropriate
$(drush dd my_theme)

A distant fourth option would be to use the site-set command; that would be a bad idea, though, as it uses the current process id to identify the filename that stores the current Drupal site.  If your bash script created any subprocesses (e.g. by wrapping sections of the script in parenthesis, using $(), using backticks, etc.), then commands inside the subprocess will "forget" the currently set site.

For example, the following script will only print the site that was set once; the portion of the script inside parenthesis fails to find the set site:

drush site-set @foo_alias
echo "process $BASHPID"
drush ev 'return drush_sitealias_site_get();'
(
  echo "subprocess $BASHPID"
  drush ev 'return drush_sitealias_site_get();'
)

In a script, you are better off putting the site specification into a variable, and explicitly use that variable with every invocation of Drush.


How to structure repetitive data under an entity type bundle?

You could always make another view to supplement or replace your content list.  If you're using Entity Reference for the relationship between book and author you can create an easily filterable list of books.

Alternatively, 2c is a viable option.  You can create a group of fields on Author called book using field collection and set the group to have unlimited instances.


There is a format_number API module, which may eventually handle this for you. And possibly will make it into D8.

For the moment I think the function you are looking for is number_format()


using sass to generate RTL & LTR css files in Omega 4

I guess it depends on what you define as being convenient.

The SASS part is easy, since sass support is already setup in Omega. You just need to setup some sort of a sass structure to write the CSS.

To change the language settings, you'll want to invoke the template_preprocess_html() function to override the html that's rendered.
function template_preprocess_html


Term reference list with a field for extra information

As far as I know you can achieve that in two ways.

Using the combination of Double Field and Field group modules.

  Use "Double field" for to make list of checkbox and textfields, and Field Group to make all of them a Group.

There is another option to achieve this. Try the Composed Field module

  Composed Field is an implementation of core's Field UI that allows you to split a single field into as many sub-fields as you like.

This seems very close to your requirement. I've used this one of my project and working fine.


You can achieve this with calendar module and Date API. The default mini calendar is redirecting to a new page, but you can override it in your template file. I would suggest to use ajax link api module to load your content in a div you would like. You can do something like the following

/**
 * Alters link url in calendar events block in order to filter events at /events
 *
 * @see template_preprocess_calendar_datebox()
 */
function <themeName>_preprocess_calendar_datebox(&$vars) {
  $date = $vars['date'];
  $view = $vars['view'];
  $day_path = calendar_granularity_path($view, 'day');

 //$vars['url'] = 'exhibitions/calendar/' . $date;
  $vars['link'] = !empty($day_path) ? l_ajax($vars['day'], $vars['url'], '#block-system-main') : $vars['day'];
}

l_ajax function is used to load contents via ajax. Let me know if you need any help.


How to login-redirect users to their profile page on specific days only?

You could do it simply by rules module (no extra module required):

Create a new rule.
Select event - user has logged in
Could add in a condition, check for a role for eg. This step is optional, and can be ignored if not required.
Select an action - Page redirect, and add the url /user to the destination.
Make sure you enable the rule.
Test, test, and test ;-)

If you want to schedule this view to run on a particular day you could check on Scheduling rules. There is also a very good video from nodeone about the same.


How to have separate private comments for nodes apart from the general comments?

For Drupal 7 see the Reply module. It lets you create your own set of "comments" attached to any Entities you want.

With some custom code you could limit the field to a specific user role or set of users. Be sure to read the README in the module.


feed import module: is it possible to have a feed importer without unique field

Check out Feed Tamper module. It allows you to modify the imported data before it is saved. For example, you can specify a token as the default value for the field or add a placeholder which then you can replace when you generate SKU.


File in /sites/default/files/ gives 404 error

Yes, it is a permission issue. Did you move the website to a different server? Sometimes, after you change the server (maybe from localhost to production) some files can have permissions issue.

That's a Drupal generated file, so you can make a backup of it, remove it, flush all caches, cross your fingers and load the page again. Hopefully Drupal will create the file with the correct permissions and the issue is solved.

If this doesn't work, check the watchdog again and check what's the problem again. Maybe there is a different problem... like that your Temporary directory is not writable.

If you still receive the same error. Try to flush all caches. Then, try to flush CSS and JS cache (this can be done with administration menu module in the first link in the left).

If that doesn't work, you must check the file permissions directly, so lets check if the user and group are configured to what they should be.

Then lets check if the file is accesible, maybe modify the permissions to 644 and check again. If this doesn't work, then change it to 664, If still doesn't work, 666; it should work now, but the user and group of the file are not well configured.

EDIT: Permissions updated as suggested by @Clive.


What MPD is saying is change this line:

$("#edit-field-i-need-help-with-und-printer-ink").change(function ($) {

to this:

$("#edit-field-i-need-help-with-und-printer-ink").change(function () {

You have declared two functions as $ and that may be killing the script.


Module/code to automatically generate an id number for title of page

Have you seen the Automatic Nodetitles module? From the description:

  "auto_nodetitle" is a small and efficient module that allows hiding of
  the content title field in the form. To prevent empty content title
  fields one can configure it to generate the title by a given pattern.

  When the token module is installed it's possible to use various node
  data for the auto generated title - e.g. use the text of a CCK field
  (since 5.x).

  Advanced users can also provide some PHP code, that is used for
  automatically generating an appropriate title.


Create a content node from another content

If both your content types are defined for Plannning and Appointment already, you can easily create appoint nodes on-the-fly when a Planning node is saved.

You want to look at the following 2 references:

hook_node_insert()
Programmatically create nodes

It would look something like this (NOT TESTED):

function mymodule_node_insert($node) {
  if ($node->type == 'planning') {
    foreach (element_children($node->field_appointment_dates) as $a_single_appointment_date) {
      $appt_node = new stdClass();
      $appt_node->type = 'appointment';
      node_object_prepare($appt_node);
      $appt_node->language = LANGUAGE_NONE; // Or your language type ...
      $appt_node->title = 'Some new appointment';
      $appt_node->field_appointment_date = $a_single_appointment_date[0]['value'];
      node_save($appt_node);
    }
  }
}


How do I switch node templates based on arbitrary critera

Indeed, in D7 the template suggestions are an array of suggestions, in the order of importance. You've got 99% of it, but your dashes need to be underscores. Try:

function THEME_preprocess_page() {
  $vars['theme_hook_suggestions'][] = 'page__whatever';
}

function THEME_preprocess_node() {
  $vars['theme_hook_suggestions'][] = 'node__whatever';
}

Why underscores instead of hyphens? From the Drupal API docs:

  // Hyphens (-) and underscores (_) play a special role in theme suggestions.
  // Theme suggestions should only contain underscores, because within
  // drupal_find_theme_templates(), underscores are converted to hyphens to
  // match template file names, and then converted back to underscores to match
  // pre-processing and other function names. So if your theme suggestion
  // contains a hyphen, it will end up as an underscore after this conversion,
  // and your function names won't be recognized.


Remove Side Menus on certain pages in Drupal 7

Did you added the menu on the left side menu bar using blocks or printing directly from the template?

On the first case you can hide the blocks on specific pages in many ways. The easiest is to configure the visibility from the blocks configuration (Administration > structure > blocks). On every block settings you can specify in which pages hide or show the block.

If you're printing the menus from the template you've to use some php in order to select when print them, like "if current page is x, then print" or something similar.

:-)


What you're looking for there is not a menu but faceted search, the best way to do this is to install and configure Apache Solr Search and Facet API.


How do I remove the colon from a form element's title - D7?

Well easiest solution is to use this module . But I am not sure you would be interested to install a module for this small task.

If not you need to do the following steps:

You need to copy the field.tpl.php to your theme folder.
Now in the template file you can find the code that outputs the colon.
Please remember to clear the cache.


How do I add multiple links in each table row form table?

After a long research i was able to acheive this as follows:

$approve_link = Link::fromTextAndUrl(t('Approve'), Url::fromRoute('vacation_forms.operations', ['ID' => $result->id, 'action' => 'approve']))->toString();
$reject_link = Link::fromTextAndUrl(t('Reject'), Url::fromRoute('vacation_forms.operations', ['ID' => $result->id, 'action' => 'reject']))->toString();
$mainLink = t('@linkApprove | @linkReject', array('@linkApprove' => $approve_link, '@linkReject' => $reject_link));

and then use $mainLink in foreach loop.
Thanks for all your help.


Change placement of 'Read more' link in a teaser

I figured out how to move the 'Read more' link to display below the body text for each teaser.
In my Drupal site, I went into 'Structure' in the main administration menu > 'Content types' > Selected the content type I created (in this case, it was: 'Blog post') > Manage display > and then went into the 'Teaser' tab. I was then able to move around the fields so that the 'Read more' link displayed below the body text.


drupal commerce multiple products on one page

On your Product Display field setup a multivalued  entity reference field of type 'node'. Now as per your example

you add a product for date 18, in reference field add reference to other dates as well.
For all dates will have reference to each other.
Now with view create a block display to show related nodes using relationship on reference field and take node id from context filter.
Put this block on product display page so it can take node id from context and show related products.


Extract info from profile insert into node creation

In broad strokes, you could intercept the node edit/add form via hook_form_alter()  to remove the fields from the form and then you could implement their population via the hook_node_presave() to grab all the information from the node owner's profile and save the fields in the new node.

Caveat:  if the user can change this information in his/her profile, it won't automatically update any of the node fields unless you add in that logic as well on the saving of this new information to all the nodes already created.


Conf_path is deprecated but what is its replacement?

One of two change records for conf_path() is Bootstrap refactored to use the kernel. This states that

  Note: In D8, instead of using conf_path(), \Drupal\Core\DrupalKernel::getSitePath() instead. If the kernel is unavailable (such as above, where the code shows the booting of the D8 kernel) or the site path needs to be recalculated then Drupal\Core\DrupalKernel::findSitePath() can be used

So if you have access to the DrupalKernel object, then calling getSitePath() on that object will work. This is probably not the case.

However, there is a service for this called site.path that can be injected into a class that you need it. I think the change record could be updated to reference this factory class.

Using the global Drupal object:

$conf_path = \Drupal::service('site.path');


Is there any gain using Memcached module when APC is running good on large Drupal 7 site (one server)

Putting the cache_form on the database is a good idea. I will help to prevent errors like this: http://drupal.org/node/500646

APC vs Memcache when it comes to the drupal cache mainly comes down to a persons preference. Mine is towards memcache because it allows for a multiple web head server setup. Performance wise APC will usually be a touch quicker, but my vote is still for memcache even on single server setups.


Found the answer myself minutes after posting the question... so it goes :).
  $members = $group->getMembers();
  foreach ($members as $member) {
    $user = $member->getUser();
    $userids[] = $user->id();
  }


I assume you will have to store that unique code somewhere because the user is going to use it and you will have to verify it against something?

I'd suggest to define a field for that unique code, you can use the field permissions module or a custom hook_field_access() to hide from the user. Then you generate that unique code in hook_user_presave() for new users and save in that field. The advantage of this is that you can then enable the token.module and you get tokens for all fields for free.

Alternatively, you can also store it in a custom table or $user->data and define hook_token_info() and hook_tokens() yourself. Instead of directly defining it as a token, you can also define it as a property (hook_entity_property_info()) to entity.module and it will automatically be available as a token as well if the entity_token module is enabled.

So yes, whichever way you chose, in the end it will be a token and you can use it in the mail.


How to set checkbox if validation fails?

All form validations should be done in form validate function and not in submit function. Read this article

Hope it helps. :)


Exposed filters of a view printed in different places

My first instinct would be to create a custom template for that specific View. However, based on the screenshot, it looks like you only want to move 2 of the 3 exposed filters to the side.

Had you wanted to move all of the exposed filters to the side, it likely could have been done with a custom views-view.tpl.php file.

Perhaps give the  Better Exposed Filters a try!

I haven't personally tested this module, but a Google search lead me to this. Hope this helps.


How to call a controller of custom module when a node is published?

The purpose of controllers is just providing output for a route, not implementing hooks. If you need to write code that is invoked when a node is published, you need to implement one of the following hooks:

hook_ENTITY_TYPE_presave(), invoked right before the entity is saved
hook_ENTITY_TYPE_update() (invoked after an entity is updated and saved in the database) and hook_ENTITY_TYPE_insert() (invoked after an entity is created and saved in the database)

hook_node_presave(), hook_node_update(), and hook_node_insert() get a Node object as parameter, so obtaining the body value is pretty easy.

use Drupal\node\Entity\Node;

function mymodule_node_presave(Node $node) {
  $body = $node->get('body')->value;
  $summary = $node->get('body')->summary;
}

Getting the taxonomy term from a reference field of a node can be achieved with code similar to the following one.

use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;

function mymodule_node_presave(Node $node) {
  $term = Term::load($node->get('field_tags')->target_id);
}

To that, you need to add the code to verify the node has been published.

use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;

function mymodule_node_presave(Node $node) {
  if ($node->status()) {
    // The node has been published.
    $body = $node->get('body')->value;
    $summary = $node->get('body')->summary;
    $term = Term::load($node->get('field_tags')->target_id);
    $term_name = $term->getName();
  }
}

If the taxonomy reference field is not field_tags, replace field_tags with the right machine name of the field.


Viewing all the options listed on https://drushcommands.com/drush-8x/sql/sql-sync for drush sql-sync command, it seems you can apply limitations on a table level only. So you might want to build a custom code for syncing data as there is no way to push nodes and field data using Drush sync per their published statuses.


Preserve views exposed filter options when back button is pressed

You'll have to turn off ajax to get this to work until this issue is resolved. See http://drupal.org/node/1248332

Then edit your exposed filter(s) and check off "Remember last selection".


Can I have separate playlist for each node?

It sounds like you want a second content type called episodes. You can do this by adding a relationship between the audiobook and episodes with an entity reference field. When creating the field you can define how the relationship works. Episodes can then be ordered and you can setup a single view to display the episodes for a particular audiobook in which ever way you choose. The view would accept the audiobook node id as an argument selecting episodes by relationship for extra ease of development and simplicity.

You could also use the inline entity form module to add and edit related entities.


You can wrap the fields in a Paragraph with the paragraphs module. I.e. create a new paragraph type, repeatable_date, with two fields: date and comment. Then add a new paragraphs reference field to your article and set cardinality to unlimited. This will allow you to add unlimited repeatable date items, each with date and comment.
Or you can create a new custom field type that has a date field and a comment field. This is more difficult to do, but may be preferable if the paragraphs route doesn't suit you. See How to create a new field type for details.


Create a zip file from a list of selected files and make the zipped file downloadable in Drupal 8

Use the ArchiverManager and get the instance by calling the getInstance() method. A Zip class is returned. The Drupal Zip class uses PHP's ZipArchive class to perform the heavy lifting.

Example (edited after remark @Clive):

$file = \Drupal\file\Entity\File::load($fileId);
$fileUri = \Drupal::service('file_system')->realpath($file->getFileUri());

$zip = \Drupal::service('plugin.manager.archiver')->getInstance(['filepath' => '/foo/bar.zip']);
$zip->add($fileUri);


Are there cases where a third-party module would need to use its own file similar to xmlrp.php, cron.php, or authenticate.php?

If you examine these files you will see that they share the bootstrap process, but the rest is different.

index.php calls menu_execute_active_handler, which is a fairly heavyweight function.  It essentially does everything to render a page (lots of hooks get called).

cron.php just calls drupal_cron_run, which is fairly lightweight (it just calls everything that implements hook_cron and also bumps up the execution time via set_time_limit.  This can decrease the memory footprint for expensive tasks (like rebuilding search indexes).

Addendum to address comment

Routing everything through index.php is good (front controller pattern).  However, I see it being acceptable to have an extra script entry point for maintenance tasks that essentially run a single hook.  I think of this as tasks that could normally be handled by drush, but need to be web-accessible or if a site doesn't have CLI capabilities.  I have also run into a few cases where a site would bootstrap, but abort because of major problems (like a severely damaged menu cache).  A maintenance script can fix this, if drush can't be used.  It is worth noting, though, that extra precaution needs to be taken to lock down the scripts against malicious access and use.


I believe in owning the silliness, when you're being silly.  I answered my own question in the process of posting the question.

Using MMenu module, I simply took my animated divs and put them in a block and loaded the block as content for mmenu.  The js scripts work and the content looks great, only one last hurdle.  But I will do that is an actual question if I can't find a solution.


Custom content entity template preprocess doesn't contain any variables

I needed to remove the #

/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return [
    'my_module' => [
      'path' => $path . '/templates',
      'template' => 'my-module',
      'variables' => [
        'my_entity' => '',
      ],
    ],
  ];
}

now i have my entity and can work on :)


Aggregator custom template file is not overriding the default one on Drupal 7

I don't think it uses template files.

Just override the function in your template.php.
(replace 'mytheme' with your theme's name).

/**
 * Returns HTML for an individual feed item for display in the block.
 *
 * @param $variables
 *   An associative array containing:
 *   - item: The item to be displayed.
 *   - feed: Not used.
 *
 * @ingroup themeable
 */
function mytheme_aggregator_block_item($variables) {
  // Display the external link to the item.
  return 'link) . '">' . check_plain($variables['item']->title) . "\n";
}


Unable to choose an installation profile on a multi-site installation

In the .info.yml file, do no put distribution statement, ss mentioned in this guide:

# Optional: Declare your installation profile as a distribution
# This will make the installer auto-select this installation profile.
# The distribution_name property is used in the installer and other places as
# a label for the software being installed.
distribution:
  name: Distribution Name


How update user info using its UID in a custom module?

You can equally use either user_save() or field_attach_update().

// Load the user's account.
global $user;
$account = user_load($user->uid);
$edit = $account->field_my_custom_field[LANGUAGE_NONE][0][value] = $new_value;
user_save($account, $edit);
// field_attach_update
$account->field_my_custom_field[LANGUAGE_NONE][0][value] = $new_value;
field_attach_update('user', $account);

The difference between using one function or the other is that user_save() will update all the user fields whereas field_attach_update() will update only the specified field.


Question about steps to convert from Ubercart to Drupal Commerce

The two projects are incompatible because of the lack of name spacing in Drupal 7. Your best bet will be to completely delete all of the Ubercart related content and uninstall all of its modules. For obvious reasons, I'd recommend not doing this on your client's live site. Create a copy from a backup and perform your test / research in that.


Easiest way to add x-webkit-speech to the search block's input element

use hook_form_alter on the search_form and add an HTML attribute via the #attributes for x-webkit-speech.


How to change page title of Manage Fields screen based on bundle name?

You need to replace the static title with a dynamic title.

Reference: https://www.drupal.org/node/2067859

This describes how to define dynamic titles for new routes in yaml files. You need to change the existing route entity.node.field_ui_fields in a route subscriber:

$route->setDefault('_title_callback', '\Drupal\mymodule\Controller\MyController::getTitle');

Reference: https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones


How to implement side-by-side translation?

There hasn't been a whole lot of public work on this that I can find.

Some module options:

Side-by-Side Translation (no code)
Entity Translation Side-by-side Editor (code, no release)
Dual-Language Editor (code, no release)

liquidcms helped me find that last one.

I'd recommend trying the latter two and seeing how far you get.  Post patches for missing functionality as necessary.

Also, see the issue Create Node With Multiple Translations Using Single Form.


This small Views user: comments relationship patch should be just the ticket: http://drupal.org/node/1773966

  ...I ended up creating a "User: Comments authored" relationship. Very
  useful. Combined with aggregation and using "count distinct" it allows
  a user view to include # comments authored and # of nodes authored.

Direct link to patch: http://drupal.org/files/views-uid_comment_relationship.patch


Adding CCK fields to Simplenews email newsletter

Try this - it's pretty in deoth on what files and variables you can use with simplenews and cck in Drupal 6: http://drupal.org/node/268404


Add location to to profile2 just after the user registers

Try using hook_user_insert instead. The $account will have $account->uid set at that stage.

P.S wrapping hook_user_presave in that condition looks wrong and probably won't work with the hook registry cache.


Identifying drupal installation on windows

You can achieve this by implementing the php_uname() function:

$os_name = php_uname("s");
if($os_name == 'Linux') {
  return TRUE;
}
//can apply additional checks for other OS
else {
  return FALSE;
}


Is there any easy way to set the default author for a node being edited to the current author if it is currently anonymous?

Option 1 - Adapt node author after editing it

If you have the Rules module enabled, you can simply use a rule that looks like so:

{ "rules_change_anonymous_user_to_current_user" : {
    "LABEL" : "Change anonymous user to current user",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "node-unchanged:author:uid" ], "value" : "0" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:author" ], "value" : [ "site:current-user" ] } },
      { "drupal_message" : {
          "message" : "Be aware: this was a node with an anonymous author. Since you just edited it, you are now considered as the author of it.",
          "type" : "warning"
        }
      }
    ]
  }
}

After you enable the Rules UI, you should be able to import this rule in your own site.

Just in case it's not clear what this rule does:

Rules Event: after updating existing content.
Rules Conditions:

Author of node being edited has uid=0.
User editing the node is logged in.
User editing the node does NOT have role "administrator".

Rules Actions:

Set node author to current user.
Display a (warning) message like "Be aware: this was a node with an anonymous author. Since you just edited it, you are now considered as the author of it.".

Done! ... with Option 1.

Option 2 - Adapt node author after flagging it (instead of editing it)

As per your requirement like "...whenever someone (preferably someone who is not the administrator) edits a node that has the anonymous author ...") the previous option has a disadvantage I think: the node has to be edited. But what if the node content is actually fine, and does not need any edits at all? Therefor I'd recommend a possible alternative, which you either use together with the previous option, or as a replacement of it. Read on for more details ...

You could also use the Flag module to create a (non-global) flag that are allowed to be used by authenticated users. Let's say you define a flag labeled like "I am the author", with machine name "i_am_the_author". With such flag in place, you can use a variation of the rule from Option 1, which looks like so:

{ "rules_change_anonymous_user_to_flagging_user" : {
    "LABEL" : "Change anonymous user to flagging user",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_i_am_the_author" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "flagged-node:author:uid" ], "value" : "0" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "flagged-node:author" ], "value" : [ "site:current-user" ] } },
      { "drupal_message" : {
          "message" : "Be aware: this was a node with an anonymous author. Since you just flagged it, you are now considered as the author of it.",
          "type" : "warning"
        }
      }
    ]
  }
}

After you enable the Rules UI, you should be able to import this rule in your own site.

Just in case it's not clear what this rule does:

Rules Event: after a node has been flagged, under "I am the author".
Rules Conditions:

Author of node being flagged has uid=0.
User flagging the node is logged in.
User flagging the node does NOT have role "administrator".

Rules Actions:

Set node author to current user.
Display a (warning) message like "Be aware: this was a node with an anonymous author. Since you just flagged it, you are now considered as the author of it.".

Done! ... with Option 2.

Option 3 - Heading for the golden cradle

If you'd implement Option 2 (using the "I am the author" flag), you could even replace the rule from Option 1 by a variation of it, which is that you simply disallowed edit attempts of nodes that (still) have an anonymous user. Here is a summary of how such rule could look like:

Rules Event : Drupal is initializing.
Rules Condition: Current path is like /node/nid/edit (using a regular expression).
Rules actions:

Perform a redirect (to any path that fits, eg some help page to explain the reason for the direct).
Set a Drupal message to indicate that edits are only allowed by a user who flagged the node first by ... you guessed it ... the "I am the author" flag.

Voilà!

Option 4 - Resolving node author disputes

No matter which solution (option) you'd use, there is always a chance that multiple users might claim to be the node author.

To also take that scenario into consideration, you could create a variation of the rule from Option 2. Some details about such rule:

Replace 1st Rules Condition by "node author of flagged node is NOT uid=0.
Replace both Rules Actions with sending an eMail to (eg) the site administrator, to indicate that some type of conflict about a node author came up (and adapt the message being shown accordingly).

Game over!?!?


Print views fields in a custom view page template

You are using template for display, here you will do theming for overall display, the $fields variable is not available here.

If you want to change how fields are printed relative to each other, row style, then you should use views-view-fields.tpl.php, in your case the name will be like views-view-fields--yourpagename.tpl.php.

but if you want to theme individual fields then you have to use views-view-field--yourfieldname.tpl.php.


WSOD when trying to configure menu with many items

A fiddly workaround:

On the "list links" menu page, you can visit, rearrange, enable/disable, edit, and delete all menu items. Except for visiting the node, all this is possible from a single menu item’s edit page.

But how to access the menu item edit page without being able to access the parent’s menu page listing all those items?

Visit the node whose corresponding menu item you want to edit.
Open its HTML source code.
Search (Ctrl+f) for active menu-mlid. You’ll find a class value like menu-mlid-218. 218 is the menu item ID.
Visit /admin/structure/menu/item/218/edit.


Creation of a Grid/Matrix using views in Drupal 7

There is a module for that - if you are using Drupal 7 check this:
Views Responsive Grid


You can add a GROUP modifier right to the end of the string:

$queryPrice->groupBy('b.startBooking WITH ROLLUP');

With the rest of your query Drupal produces:

SELECT  b.*
FROM
{booking} b
GROUP BY b.startBooking WITH ROLLUP


How to remove a taxonomy term with an empty required field without having to fill it?

I usually write out code when I need to bypass validation for deletion. You can use taxonomy_term_delete to remove the items and bypass validation:

$tids = array(); //Add your term ids that you need deleted in the array
foreach($tids as $tid) {
  taxonomy_term_delete($tid);
}


How to show cart with number of items in Ubercart?

As for D8 latest version, it looks like uc_cart_get_contents is not working anymore.  So here is how I managed to do it :

/** @var \Drupal\uc_cart\CartManager $cartManager */
$cartManager = \Drupal::service('uc_cart.manager');
$items = $cartManager->get()->getContents();
$variables['nbr_cart_items'] = count($items);


Display only last item in multifileld (files by media)

You shouldn't unset array elements in tpl files. Instead, use hide() function:

Hides an element from later rendering.
The first time render() or drupal_render() is called on an element tree, as each element in the tree is rendered, it is marked with a #printed flag and the rendered children of the element are cached. Subsequent calls to render() or drupal_render() will not traverse the child tree of this element again: they will just use the cached children. So if you want to hide an element, be sure to call hide() on the element before its parent tree is rendered for the first time, as it will have no effect on subsequent renderings of the parent tree.


If you just want to create a node where a user writes a question to which the other users answer using comments, then you can use a content type that Drupal has by default. For example, with Drupal 7 the "Article" content type has already what you need; an article appears as in the following screenshot:

The only things that would need to be changed are the subject of the comment, that should not be entered, and the string "Add new comment" that should be changed in "Add new answer."
For the first, you need just to change the settings for the content type.

If you deselect the highlighted checkbox, the user will not be able to enter a title for the comment.
The other option to which you could be interested is the following one:

When it is selected, any comment for a comment is shown indented. As the comments for the node are the answers given to the question, any comment for the answer should be indented, or it would not be possible to understand when a comment is an answer, or a comment for an answer (or a comment to a comment given to an answer).

For changing the string from "Add a new comment" to "Add a new answer," you need a custom module that changes that string. For this reason, I would create a content type copying the setting used for the "Article" content type.

You don't need to alter the page.tpl.php file to show the comments together the node: That is what Drupal normally does. There is a module that allows to shows the comments in a different tab, but without that module, Drupal shows the comment in the same page where a node is shown. You will eventually need to change a template file to change the layout of the comments, though.

If you are using the word block to mean Drupal block (e.g. you want to show a block for asking a new question), then that is not possible without using third-party modules. I am not sure there is already a module for that.


How can I get Beautytips Module to work with Views field output?

You can do this with the BeautyTips module but its not the default behaviour as it does not have Views integration built-in. Fortunately, your BeautyTips use case is rather simple so the approach outlined here will work for you. Specifically, you want to edit your 'Title' field to rewrite it to add a custom trigger class like this:

[title]

and then add this to the header of the view:

<?php
drupal_add_js (
  '$(document).ready(function()
  {
    $(".btytp").bt();
  }); ',
    'inline');
?>

However, by doing this you're effectively bypassing the BeautyTips module altogether and won't be using the built-in styles the module provides. Fortunately, this is easy to fix. If you look in the modules file, you'll see all of the styles defined as Arrays that are then converted into a javascript array and used to instantiate the beautytips instance. So for example, if I were using the Hulu style, I would find this array:

  $styles['hulu'] = array(
    'fill' => '#F4F4F4',
    'strokeStyle' => '#666666',
    'spikeLength' => 20,
    'spikeGirth' => 10,
    'width' => 350,
    'overlap' => 0,
    'centerPointY' => 1,
    'cornerRadius' => 0,
    'cssStyles' => array(
      'fontFamily' => '"Lucida Grande",Helvetica,Arial,Verdana,sans-serif',
      'fontSize' => '12px',
      'padding' => '10px 14px'
    ),
    'shadow' => TRUE,
    'shadowColor' => 'rgba(0,0,0,.5)',
    'shadowBlur' => 8,
    'shadowOffsetX' => 4,
    'shadowOffsetY' => 4,
  );

All of the values here are what you need to pass to javascript when you invoke it on your own. So, to do this using the code we already have with the Hulu style, that would look like:

<?php
drupal_add_js (
  '$(document).ready(function()
  {
    $(".btytp").bt({
        fill: '#F4F4F4',
        strokeStyle: '#666',
        spikeLength: '20',
        spikeGirth: '10',
        width: 350,
        cornerRadius: 0,
        cornerPointY: 1,
        strokeWidth: 0,
        cssStyles: {
                fontFamily: '"Lucida Grande",Helvetica,Arial,Verdana,sans-serif',
                fontSize: '12px',
                padding: '10px 14px'
        },
        shadow: true,
        shadowColor: 'rgba(0,0,0,.5)',
        shadowBlur: 8,
        shadowOffsetX: 4,
        shadowOffsetY: 4,
        shadowBlur: 8,
    });
  }); ',
    'inline');
?>


Moving from subdomain to top level, link/image paths incorrect after manual edit

Is this Drupal 7 or 8? Not sure that it matters, but take a look at around line 102 of your .htaccess file, should look like this:

# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
# RewriteBase /drupal

The issue you describes sounds like the RewriteBase is incorrect. What does your .htaccess say?

Can you also tell me what your settings.php file has for the base URL value?

# $base_url = 'http://www.example.com';  // NO trailing slash!


How to add text or description in a form without writing a module?

You are on the right track:

Create a new field in your content type of type "Long Text", call it something like Ingredients Text ("ingredients_text") for the machine name --  the text that will be within this field can change per node as you like.
Then, go to your Dependencies tab in this content type.
Click "Add new dependency" and choose your newly created Textfield as the "Dependent".  Choose your select / radio button as the "Dependee". (Leave the other two settings as is.)
Click "Add Dependency"
You are in a new screen, take the defaults
For Node View setting of the edit screen, try "Hide the dependent if the dependee is not viewable by the user and the dependency is not triggered".
Now when you the user is in the node, he can choose the radio button and the new text field will appear!

You will need to play with the settings but this does work, I just set this up on a site for a client.  Note, the options in step 6 may vary depending on your particular setup.


Is it possible to add help text to addressfield module fields?

When editing the field settings there should be a Help text field where you can enter "Instructions to present to the user below this field on the editing form".

If you want to provide additional instructions, use the Markup module to add a "field" containing the additional instructions. To keep the address field and the markup field in the same fieldset, use the Field group module to group the two fields into a single fieldset group.


Sort content in a view by taxonomy term and use terms as headlines in drupal 8

To do this you need a Taxonomy term view with a Content using field_xxx relationship.

Here are the steps needed:

Create a new view with Show: Taxonomy terms of type: Book category (or whatever your vocabulary is called).
Under Advanced settings add a Relationship of type Content using field_bookcategory
Under Fields, Add a Content Title field to the view. A relationship to your field_bookcategory should be automatically selected at this point.
You now need to group your results by taxonomy term. Do this under under Format: Settings and set Grouping field Nr. 1 to Taxonomy term: Name
Lastly, you'll want to hide the term name in the results, since you're already displaying it in the group heading. To do this set the Taxonomy term: Name field to Exclude from display


Not sure why you insist on using Form API for this, but form element labels are rendered in theme_form_element_label(). You may want to override that function in your theme's template.tpl.php file to produce the desired markup.


The best way is to use the Entity Reference Module.

Install the module
At the Product add a field My Product Group and Field Type: Entity Reference. If you have many Products use the autocomplete widget.
On the next page chose Target type: Node and then the as Target bundles the Product Group.

Now when you add a ‘Product’ you can assign the parent ‘Product Group’.

Do the same for Application and Product.

The final structure will be:

- Product Group
- (have) Product
-- (have) Application

To display the results is another story. You can go to ‘Manage display’ of the content type and Render the entity. Or you can use views if you like something more complex.