If you want to alter how a submission is rendered, for example adding a table, you need to implement hook_webform_submission_render_alter(). The hook receive the data for the submission in $renderable['#submission'], and the node in $renderable['#node'].

An example of hook_webform_submission_render_alter() is webform_webform_submission_render_alter(), which contains the following code.

function webform_webform_submission_render_alter(&$renderable) {
  // If displaying a submission to end-users who are viewing their own
  // submissions (and not through an e-mail), do not show hidden values.
  // This needs to be implemented at the level of the entire submission, since
  // individual components do not get contextual information about where they
  // are being displayed.
  $node = $renderable['#node'];
  $is_admin = webform_results_access($node);
  if (empty($renderable['#email']) && !$is_admin) {
    // Find and hide the display of all hidden components.
    foreach ($node->webform['components'] as $cid => $component) {
      if ($component['type'] == 'hidden') {
        $parents = webform_component_parent_keys($node, $component);
        $element = &$renderable;
        foreach ($parents as $pid) {
          $element = &$element[$pid];
        }
        $element['#access'] = FALSE;
      }
    }
  }
}

The purpose of hook_webform_submission_insert() is inserting the submitted data in a database. You can use that hook to save the data in a database, and show those data in a page rendered from your module, but hook_webform_submission_insert() is not thought to render any data.
To make a paragon, hook_webform_submission_insert() is equivalent to hook_node_insert() that is invoked when a new node is saved, but that should not render any page.


Change the filter to "Provide default value", and then choose the node ID from the URL.


Search api autocomplete with commerce kickstart

I got it working by using this example jQuery Autocomplete

If anyone else get stuck in this just ask me and I'll try to help out


Setting the default value of an entity form radio button using hook_form_FORMID_alter

Can u please try below code:

$form['field_sem_pledge_currency']['und'][0]['#default_value']['value'] = 'currency_bitcoin';


How can I rename uploaded files programatically? (auto-rename image files)

Assuming you are talking about the core file functionality, you can modify the filename in hook_file_presave() and modify the filename property.

function mymodule_file_presave($file) {
  $parts = pathinfo($file->filename);
  $file->filename = $file->uid . $file->timestamp . '.' . $parts['extension'];
}

Drupal will handle changing any other properties that need to be changed.

Some issues to be aware of:

Upload forms will expose the new name to the user after he clicks 'Upload'. It may be confusing to upload a file with a regular filename and see it changed to a string of numbers.
There is a note on the hook_file_presave documentation that the hook "doesn't distinguish between files created as a result of a copy or those created by an upload." If you do need to distinguish, check out the $file->source property or try calling menu_get_object() to figure out if the user is on a page with an upload form or not.
Consider using a dash between the uid and the timestamp for your naming convention. Your timestamps will all start with 1 (until 2033 anyway), and users with UIDs ending in 1 (e.g 11, 21, etc.) will make the filename confusing to read.


Call javascript right after the form elements are rendered

You need to wait for the DOM to be ready (i.e. when then browser has finished comprehending the HTML).

Drupal's javascript API provides a natural place for your code, in the form of a behavior, e.g.

(function($) {
  Drupal.behaviors.mymoduleFoo = {
    attach: function(context, settings) {
      $('#priority-6').show();
      // ...
    }
  };
})(jQuery);

The attach method is invoked when the DOM is ready, and also at other points in the page execution when something might have changed (e.g. when an AJAX call is made), to give you the opportunity to respond to any new/change elements that might affect your code's functionality.


What options are there to allow users who have not logged in to see content on the home page?

What kind of permission module are you using ? Is it possible you implement yourself these permission ?

I would restrict node access to anonymous user using a custom module implementing hook_node_access() and allow them to see the nodes on the front page (using the function drupal_is_front_page()):

function MYMODULE_node_access($node, $op, $account) {
  if ($op == 'view' && $account->uid == 0) {
    if (drupal_is_front_page()) {
      return NODE_ACCESS_ALLOW;
    } else {
      return NODE_ACCESS_DENY;
    }
  }
  return NODE_ACCESS_IGNORE;
}


Naming convention for field type templates?

The naming convention for field templates is documented here, Twig Template naming conventions

  field--node--[field-name]--[content-type].html.twig
  field--node--[field-name].html.twig
  field--node--[content-type].html.twig
  field--[field-name].html.twig
  field--[field-type].html.twig field.html.twig

But field--text-with-summary.html.twig is one of those that is harder/trickier to figure out from just looking at the Field Type.

To make Drupal life easy for this, you can enable Twig Debug. See Locating Template Files with Debugging

Now when you inspect element with browser, you can see which template file is being used (the one with the "x") and what other available template file names (the ones with "*") you could use.


How to change the author of a node after payment using the rules module?

This seems like a variation of the question "Change node author on node save with rules". And the accepted answer there (with the comment added to it) seems the answer to it.

Does this answer your question?


clear boost cached pages as the content is changed

You can use the Cache Expiration module to expire caches when content is updated.

The expire module provides the events that fire when content is updated and other caching modules hook into those events and clear their caches.

The boost module supports the expire module's events.

Once installed, you can configure the module at admin/config/system/expire.


There is no need to create your own Client or ClientFactory service.

Because ClientFactory::fromOptions() has

$config = NestedArray::mergeDeep($default_config, Settings::get('http_client_config', []), $config);

You can specify default options to Guzzle for all clients created by Drupal via your settings.php.  Core only provides an example of proxy settings, but you could alter the user agent via

$settings['http_client_config']['headers']['User-Agent'] = 'Foobar 1.0';

To create a single client with different options, (which will override settings from both ClientFactory::fromOptions() and settings.php), you can use the factory service directly:

\Drupal::service('http_client_factory')->fromOptions([
  'headers' => ['User-Agent' => 'Foobar 1.0'],
]);


How to load library only on one twig template?

Just remove the reference from mytheme.info.yml.

That's adding it any time the theme is loaded (every page), whereas attach_library will add it only when that specific template is used.

You'll need to rebuild cache for the change to take effect.


How can the -value be passed as a param in a filtered url for a View?

I suddenly realized that the passed value probably has to match one of the values in the select-options. I just had to look at the source of user page. The value for the Any-option is All. So this works:

view_name?status=All


Your question looks like a perfect fit for the Group module, which can be used to create collections of content (nodes) that can be accessed by sets of users and with variations of access levels, such as none or read only.

Have a look at the answer to What are the alternatives for the Organic groups module? for a brief introduction to the Group module.

For this specific question, here is a blueprint of how it could be used/configured:

Group Type: Collections
Group Roles (refer to "What are the various roles supported by the Group module?" for more details):

Group Owner
Group Fans (or whatever fits), used for those who have access to a selected collection.

Groups (adapt the group titles to fit your collection names):

Collection 1 of user A.
Collection 2 of user A.
Collection 1 of user B.
Collection 2 of user B.
Collection 3 of user B.
...
Collection I of user X.

If a user creates a new group, then automatically assign role "Group Owner"-role to the user who created the group.
Group permissions: grant permission to the user with role "Group Owner" to perform actions like "Add members" or "Invite members to join".

To use the Group module from within a custom module, start from its Development guide and/or have a look at its API for D7 or API for D8.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".
Other questions tagged with the group tag.

PS: Even though this question is tagged for D8, this answer applies for either D7 or D8 ...


Node Access - Change ownership of node before loading

One possible solution might be to add a User Reference field to the node and add the Users you want to grant access to. Then in hook_node_access, check for that field, and return the proper access for view/edit/delete. Don't forget the value of the author field too, to preserve the original functionality. Basically, if the current UID is in the list of referenced users, return TRUE.

I feel like I have done this in the past in 7, but can't locate any code examples at the moment.


I'm not sure if this solution works and I'm not able to test it right bow, but download and install views_php module. it allows you to add a field which is fill by any php code. so in your views you must select fields instead of content. search for php then you can add this field. in this field try

drupal_set_title('TITLE');

if this works then you can put your php code there. If not you must modify the template file.


You can use hook_user_insert, in which you can easily execute CURL, in hook_user_insert you will have all your data regarding the user.


Loop trough a list of referenced nodes in order to get a specific field value

the "target_id" is the nid (node id) of the referenced entity, now if you want to get the values of a specific field of the referenced entities you can do the following:

$values = array();

foreach($tpl as $field_item){
$values[] = node_load($field_item['target_id'])->field_your_field;
}

you just need to load the entity and then get the field you are looking for. Devel module will make your life easier in that purpose

If the entity you are referencing is not a "node" so you can load the entity using entity_load() and then use entity_metadata_wrapper() for get the fields and all the info you need from each entity.


How do you replace text surrounded by a custom delimeter with  around it?

You can use preg_replace as the following in your custom module:

<?php

$string = '[=waves=] words
 words
 words [=jumps in air & rolls in ground=]
words
';
$pattern = '/\[=(.*?)\=]/i';
$replacement = '*$1*';
print preg_replace($pattern, $replacement, $string);

which return:

*waves* words
 words
 words *jumps in air & rolls in ground*
words


How to render specific block from template without rendering entire region

Almost there it's block_view not blockview

$block = module_invoke('user', 'block_view', '2');
print render($block['content']);


just to make you aware in case you're using the Pathauto module and you didn't notice:

  Changes to path aliases and a critical note for sites using the Pathauto contributed module
  If you have the contributed Pathauto module enabled, you must update to the latest version of Pathauto before you update to Drupal 8.8.0. Failure to update Pathauto before updating core could result in data loss. Drupal 8.8.0 declares a conflict with Pathauto 8.x-1.5 or lower for this reason.

https://www.drupal.org/project/drupal/releases/8.8.0

Can't say anything about your specific error though.


Depends on what type of block your need the js for. If it's a custom block you created in a module, you can just tack drupal_add_js into the block definition function.

If your trying to add it to a block was created by someone else's module, or drupal created (IE, you didn't create it with a module), you could create a simple module that uses hook_block_view, which is fired whenever a block is loaded. You should be able to check from there if that is the block you want, then use drupal_add_js to load your js from that module.


How and where to add google analytics tracking code?

Easiest and most admin-friendly way is to use Google Analytics module:

  Adds the Google Analytics web statistics tracking system to your website.

Just install it, turn it on and configure.

(source: drupal.org)


How to display the user's preferred language in a User profile page

I think I could answer myself to most of my questions:
1-The Language code field store the initial language of a user... it looks like it can't be changed after all. For my use case, it is an useless field.
2-The Language settings options display the Preferred language widget and the Administration pages language widget. I think that this last widget is there only if you check Account administration pages language setting. in admin/config/regional/language/detection
3-The most important part: How to display the preferred language of a user in the the display user page (/user/xxx)
You can do it with this hook:
function mymodule_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type->id() == "user") {
    $fields['preferred_langcode']->setDisplayConfigurable('view', TRUE);
  }
}

I really don't know why it is not a default... (don't hesitate to add any information on this point)


I'm not ruling out mystery module that I am unaware of,  but I can give some insight.

The first obvious choice is the API, just reference the hooks in :   /modules/contrib/inline_entity_form/inline_entity_form.api.php

You can also add a FieldWidget in your module like: YOUR_MODULE/src/Plugin/Field/FieldWidget/IEFPagination.php,  then you would select it under Manage Form Display.

namespace Drupal\YOUR_MODULE\Plugin\Field\FieldWidget;

use Drupal\inline_entity_form\Plugin\Field\FieldWidget\InlineEntityFormComplex;

/**
 *
 * @FieldWidget(
 *   id = "ief_paginated",
 *   label = @Translation("IEF - Paginated"),
 *   field_types = {
 *     "entity_reference"
 *   },
 *   multiple_values = true
 * )
 */

class IEFPagination extends InlineEntityFormComplex {

 public function formElement(\Drupal\Core\Field\FieldItemListInterface $items, $delta, array $element, array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {

    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    /* Adjust element here */

    return $element;
}

 public static function buildEntityFormActions($element) {

    $element = parent::buildEntityFormActions($element);

    /* Or here */

    return $element;
 }


I think I would just add a quick jquery script myself that converts to the right format and autofills it into the field on the 'change' event.

I dont know your level of expertise on jquery, but if needed i can provide you a small example


You need to set ckeditor configuration setting

config.enterMode

to proper value

(1) The default creates a paragraph element each time the "enter" key is pressed:

config.enterMode = CKEDITOR.ENTER_P; // inserts

(2) You can choose to create a "div" element instead of a paragraph:

config.enterMode = CKEDITOR.ENTER_DIV; // inserts

The setting that you are looking for *

(3) If you prefer to not wrap the text in anything, you can choose to insert a line break tag:

config.enterMode = CKEDITOR.ENTER_BR; // inserts

The application developer indicates that using the ENTER_BR setting is not recommended.
http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html#.enterMode

There are three more settings that are somewhat related to this subject:

config.fillEmptyBlocks
config.forceEnterMode
config.ignoreEmptyParagraph

A complete list of the available configuration options can be found here:
http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html


Contextual filter for an indirect taxonomy term?

To rephrase (to see if I understood correctly):
You have a content type pointing to term reference #1, that is pointing to term reference #2. You want to show the content that points to term #1, with the context being term #2.

In that case, you'd need to create a relationship (see Using Views Contextual Filter and Relationship to display reference on referenced node)

(The following explanation would work best with entity reference instead of term reference - I don't use that field type so I'm not sure the relationship exists with it)

But in short, you'd create a relationship to "referencing entity from field_term_reference" (the field on term #1 pointing to term #2). From there you could create the "referencing entity" relationship from the field on the content type pointing to term #1. The contextual filter would be to the term ID #2 using that relationship.


Does the Data Export module support exposed filters?

When you create a Data Export view, there is an option to attach it to another view. You can choose to attach it to another page in the same view and all the filters used would be affected by the export. A new icon would be shown at the bottom of the view to download the exported data.

In the following screenshot, I attached it to a view page.


How to set form type as 'hierarchical_select' programatically?

I think its better to use hierarchical_select for element as it gives a FORM API that is really easy to use. Check the following snippet as reference

$form['hierarchical_select'] = array(
    '#type' => 'fieldset',
    '#prefix' => '
',
    '#suffix' => '
',
    '#attributes' => array(
        'class' => array('hierarchical-select'),
    ),
);
$form['hierarchical_select']['select_subject'] = array(
    '#type' => 'hierarchical_select',
    '#title' => t('Select the tag you wish to use.'),
    '#size' => 1,
    '#config' => array(
        'module' => 'hs_taxonomy',
        'params' => array(
            'vid' => 13 //The vocab id
        ),
        'save_lineage' => 1,
        'enforce_deepest' => 0,
        'entity_count' => 0,
        'require_entity' => 0,
        'resizable' => 1,
        'level_labels' => array(
            'status' => 1,
            'labels' => array(
                0 => t('Grade'),
                1 => t('Subject'),
                2 => t('Main Topic'),
                3 => t('Sub Topic'),
                4 => t('Standard'),
                5 => t('Sub-Standard'),
            ),
        ),
        'dropbox' => array(
            'status' => 0,
            'title' => t('All selections'),
            'limit' => 0,
            'reset_hs' => 1,
        ),
        'editability' => array(
            'status' => 0,
            'item_types' => array(),
        ),
        'animation_delay' => 400,
        'special_items' => array(),
       'render_flat_select' => 0,
       'path' => 'hierarchical_select_json',
    ),
    '#default_value' => 0,
);

I hope this helps.


How to compare text input with a user password stored in the database?

The only advisable approach would be to use user_check_password:

$account = user_load(123);
$valid = user_check_password($password_from_form_submission, $account);
if ($valid) {...}

If you desperately need to do it manually, just copy the parts of that function that make sense for your requirements.


After some research I managed to answer my own question by implementing the hook_views_pre_view in my custom module. The method set_item is used to set the configuration of an item (field/sort/filter/etc) on a given display. The $print variable bares the content to be rendered in the view header, it is just an example and it can be replaced by anything. Apparently now I can take advantage of the Drupal API or even set/unset any view item conditionally.

/**
 * Implementation of hook_views_pre_view.
 */
function my_module_views_pre_view(&$view, &$display_id, &$args) {

  $path = $_GET['q'];
  // Construct the print link.
  $print = l(t('Display a printer-friendly version of this page'), '/print/' . $path . '/print-friendly',  array(
    'attributes' => array(
      'class' => array('print-friendly'),
      'target' => '_blank',
      'title'=> t('Display a printer-friendly version of this page.'),
      ),
    )
  );

  if ($view->name == 'my_view_name' && $display_id == 'my_view_display') {
    // View's header declaration.
    $item = array(
      'id' => 'area',
      'table' => 'views',
      'field' => 'area',
      'relationship' => 'none',
      'group_type' => 'group',
      'ui_name' => '',
      'label' => '',
      'empty' => 0,
      'content' => $print,
      'format' => 'filtered_html',
      'tokenize' => 0,
    );
    // Render the header.
    $view->set_item($display_id, 'header', 'area', $item);
  }
}


How do I edit a complex entity via dynamically loaded AJAX-forms?

The forms that FieldAPI can build for you automatically are useful but not terribly flexible. If you're interested in building out a really dynamic form, you're probably better off creating your own from scratch and simply creating/saving the entity programmatically once the finished form is submitted.


How to check if a user has ever ordered a product/list of products

Here's an alternative approach, using an SQL query

$ordered = FALSE;

$node_wrapper = entity_metadata_wrapper('node', $node);
$product_ids = array();
foreach ($node_wrapper->field_products as $product) {
  $product_ids[] = $product->product_id->value();
}

// Query order details for products
// Note this is the line item product reference table
$query = db_select('field_data_commerce_product', 'p');
// Example if you want more fields, but would need to change ->fetchCol()
// $query->fields('o', array('order_id', 'order_number', 'uid', 'mail'));
$query->fields('o', array('uid'));
$query->innerJoin('field_data_commerce_line_items', 'l', 'l.commerce_line_items_line_item_id = p.entity_id');
$query->innerJoin('commerce_order', 'o', 'o.order_id = l.entity_id');
$query->condition('p.commerce_product_product_id', $product_ids, 'IN');
$query->groupBy('o.order_id');
// Fetch array of uids
$result = $query->execute()->fetchCol();

// Check if account->uid in array of order uids
// If so, uid has ordered product.
if(in_array($account->uid, $result)){
  $ordered = TRUE;
}


How do you store webform submits to a different database?

General the most secure way is to push a webform submission into a different 'external' database is to create a webservice to populate the external database. Then you can use the 'Remote post' handler to push the submission data via the webservice into the external database.

@see https://www.drupal.org/docs/8/modules/webform/webform-videos#handlers

To disable the saving of submissions…

Goto /admin/structure/webform/manage/WEBFORM_ID/settings
Check 'Disable saving of submissions'


Nested select with Drupals DataBase interface

Ok, figured it out but do not like it:

$query = Database::getConnection('default', 'for_migration')
   ->select('memberdata.pupils', 'p')
   ->fields('p', array('id', 'firstname', 'lastname', 'birthday', 'gender'))
   ->condition('status', 'u', '!=')
   ->range(0, 10);
$query->addExpression("(SELECT COUNT(*) FROM newsletter WHERE email = p.email)", 'newsletter_flag');

There should be a smoother way for the newsletter_flag problem.


I found what was causing the problem with not being able to display form elements as described above. The issue was this line in my templates file:

function mytheme_preprocess_user_register(&$variables) {

   $variables['intro_text'] = t('some text.');
   $variables['rendered'] = drupal_render($variables['form']);
}

It looks as though you can only call drupal_render once. Any subsequent calls to drupal_render are ignored as Drupal as already marked the code as rendered. There should be a way to force a re-render if necessary or be able to get the already rendered results. If someone knows how to do this please reply to this post.

The solution was to remove this line from the templates.php file and everything worked.


Display link after complete countdown time

Alternatively you can achieve that using the jQuery Countdown module

Example for development usage:

In this example, we display an alert box saying "You are done!" after counting down from 10...

<?php
  echo '
10 seconds!
';
  jquery_countdown_add(".countdown", array("until" => 10, "onExpiry" => "finished"));
  drupal_add_js("function finished() { alert('You are done!'); }", 'inline');
?>


This hook might be the solution it excludes different contents from migrating:

function hook_migrate_prepare_row(Row $row, MigrateSourceInterface $source, MigrationInterface $migration) {
  // Ignore content types from being migrated.
  if ($migration->id() == 'd6_node_type') {
    $ignore_content_types = array('content_type1', 'content_type2');
    if (in_array($row->getSource()['type'], $ignore_content_types)) {
      return FALSE;
    }
  }

  // Ignoring content of 4 content types.
  $ignore_content_types_content = array('d6_node__content_type1', 'd6_node__content_type2');
  if (in_array($migration->id(), $ignore_content_types_content)) {
    return FALSE;
  }
}


Make variables outside of node available to pathauto

I was in a similar boat with a site I was working on recently.  Unfortunately, Drupal 7 does not fully support tokens on field entities; see http://drupal.org/node/691078.  This is why the "location node" type exists in the location module -- it is easier to define tokens for your locations.  However, I did not like the UX for location nodes; I greatly preferred the result that can easily be obtained with cck locations.

Since it was not possible to easily support tokens on cck locations, I instead wrote my own custom token code in my custom module for my site. I did spend quite a few hours trying to do the former first, before giving it up as much too large of an effort.

I'm not sure if you are using the location module, or if you are just defining your own entities that happen to contain locations.  The fact that you have your location entities chained together implies that you're using your own entity types.  Here's the result I came up with for the location module; you should be able to adapt it for standard entities without much trouble.  The code below could probably use some minor improvements; 'und' should be LANGUAGE_NONE, the special-checking for a specific content type is probably unnecessary, etc.; it shouldn't be too hard for you to adapt in some code that resolves your chained entity references to build the tokens you need.

Once you've written your code, it's easy to select your new tokens in pathauto to define your URL structure.

function MYMODULE_token_info() {
  // Because of http://drupal.org/node/691078, we just hack in our own
  // field-based tokens here for now (cough).
  // These tokens are only available for nodes of type MY_CONTENT_TYPE_WITH_LOCATION_FIELD
  $node['field_location_street'] = array(
    'name' => t("Location Street"),
    'description' => t('The street address that a location is located at.'),
  );
  $node['field_location_city'] = array(
    'name' => t("Location City"),
    'description' => t('The city that a location is in.'),
  );
  $node['field_location_province'] = array(
    'name' => t("Location Province"),
    'description' => t('The abbreviation for the province (State) that a location is in.'),
  );
  $node['field_location_province_name'] = array(
    'name' => t("Location Province Name"),
    'description' => t('The full name of the province (State) that a location is in.'),
  );
  $node['field_location_country'] = array(
    'name' => t("Location Country"),
    'description' => t('The country that a location is in.'),
  );
  $node['field_location_country_name'] = array(
    'name' => t("Location Country Name"),
    'description' => t('The full name of the country that a location is in.'),
  );
  $node['field_location_summary'] = array(
    'name' => t("Location Summary"),
    'description' => t('A parenthesized summary of the location (City, State).'),
  );
  return array(
    'tokens' => array('node' => $node),
  );
}

function MYMODULE_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  if ($type == 'node' && !empty($data['node'])) {
    $node = $data['node'];
    $location_field = array();
    if (($node->type == 'MY_CONTENT_TYPE_WITH_LOCATION_FIELD') && (isset($node->field_location['und'][0]))) {
      $location_field = $node->field_location['und'][0];
    }
    if (($node->type == 'MY_CONTENT_TYPE_WITH_NODE_REF_TO_TYPE_WITH_LOCATION_FIELD') && (isset($node->field_event_site['und'][0]))) {
      $location_nid = $node->field_event_site['und'][0]['nid'];
      $location_node = node_load($location_nid);
      if (isset($location_node->field_location['und'][0])) {
        $location_field = $location_node->field_location['und'][0];
      }
    }
    if (!empty($location_field)) {
      $location_field['summary'] = "(" . $location_field['city'] . ", " . $location_field['province'] . ")";
      foreach ($tokens as $name => $original) {
        if (substr($name,0,15) == 'field_location_') {
          // $name is always 'field_location_xxx', so key is 'xxx'.
          $key = substr($name, 15);
          if (isset($location_field[$key])) {
            $replacements[$original] = $location_field[$key];
          }
          else {
            $replacements[$original] = '';
          }
        }
      }
    }
  }
  return $replacements;
}


How to add placeholders in customized module?

what do you mean by placeholders? a default value that prefills the textfield or some watermark text that disappears when you focus the textfield?
for a default value you can use the #default_value key in the text field definition.

for a watermark i recommend the Placeholder module. the module enables you to use a #placeholder key in your field definition.

cheers
j


How do I invoke token substitution with Pet?

I've solved in this way:

// SOSTITUZIONE TOKEN DRUPAL
$l_oPetTemplate = pet_load('test1');
$l_TemParams2['pet'] = $l_oPetTemplate;
$l_aSubstitutions = pet_substitutions($l_oPetTemplate, $l_TemParams2);
$l_aEmailParams['email_subject'] = token_replace($l_oPetTemplate->subject, $l_aSubstitutions, array('clear' => TRUE));
$l_aEmailParams['email_body']=token_replace($l_oPetTemplate->mail_body, $l_aSubstitutions, array('clear' => TRUE));


The body element will have a boatload of classes on it.  This does vary by theme, but typically there will be a class like

body.page-the-url-for-this-page

that you can use in your CSS.

Do a view source on various pages and take a look.  Or, use the Inspect Element feature of Firefox's Firebug or Google Chrome, or the Firefox Web Developer extension.

If the class isn't there, you can do something like

function thetheme_preprocess_html (&$variables)
{
  $variables['classes_array'][] = "page-" . str_replace("/", "-", request_uri());
}

You may also want to investigate the Context module, which can aid in section-specific features for a site.


How to modify the Search box input value?

The only line you'd need to set the value of the input is

$form['search_block_form']['#default_value'] = $form_default;

The last line is a basic JS placeholder implementation, but in this day and age the HTML5 placeholder attribute would be preferable:

function MYTHEME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
  $form['search_block_form']['#attributes']['placeholder'] = t('Placeholder text');
}


the WYSIWYG editor doesn't show up, drupal 7

It sounds as if you've selected "Plain text" instead of "Filtered text" as your default text processing option.  To change this, navigate to Administration » Structure » Content types, select the content you experience problems with and click manage fields and edit  on the body field (and other text fields you want to use the wysywyg editor). Make sure that the preset text format for that text field is set to to one of the formats configured for wysywyg (e.g. Filtered HTML).

To make sure that Filtered HTML is selectable, you need to make sure that the setting for "Text processing" is set to Filtered text (not Plain text):

Press Save settings after changing this.

Make sure that when you create content, a text format that is set up to use use WYSYWYG (e.g. Filtered HTML) is selected.  The screen dump below shows how the pull-down menu immediately below the text field for content should look like:

Other thinks to try when debugging a CKEditor setup:

Here are some more tips on debugging a CKEditor setup.  They probably don't apply to you, but may help others that arrive at this question while searching for a cure for CKEditor blues:

Clear the cache:

Remember to clear the cache after you've changed any setting that has something to do with wysiwyg.  Not clearing the cache is probably the most common source for CKEditor not showing up as you would expect.
Check out that roles are configured correctly:

Navigate to your text formats: Administration » Configuration » Content authoring  » Text formats and ensure the roles are configured correctly.

Add the roles you want to use wysiwyg to Filtered HTML and Full HTML.

Check out that profiles are set up right:

Navigate to your ckeditor profiles: Home » Administration » Configuration » Content authoring » CKeditor

Go to the profiles, and verify that the text formats for the profile are set, and the editor appearance is set properly.

Under Basic Setup, check the text formats that apply
Under Editor Appearance, set default state to enabled, and show the toggle.

PS: For a  secure use of WYSYWYG, I recommend using a custom text format filtered with the WYSIWYG Filter.  How you do this is described in this tutorial. However, first get it working, then start tweaking to make it secure.


How to count the number of calls to a rest service?

Do your REST service needs authentication?

If yes, you just log each access attempt by users:
One attempt per one record per user or one record per user and updating the count column always.

If there is no authentication, you will have harder time to achieve this.
It would be also good to know HOW they are making this rest calls (eg: clicking on a button which resolves into a rest call?).

You could still try to check session and find out which user made the requeset.


How to prevent ad blockers from restricting sections of my website (non google ads)

Thanks to No Sssweat's simple suggestion, it is fixed (as far as I can tell).

I changed my CSS class for the block from "banner-advert" to "sitewide-promo".

I'm assuming either banner or advert caused an issue, so I replaced both.


Where to place JS code to be used by Admin?

You have to put that either in an administrative theme or in a custom module.

It's a good idea generally to have a child theme based on the administrative theme you are already using.
This means that you can override most of the things (e.g. styles, labels, etc.) in the admin while still being able to update the parent theme.

Here's how you would do it if you are using Seven for example:

Create a new folder named seven_custom
Inside create a new file named seven_custom.info and copy all the regions from seven.info file
Copy the screenshot.png and logo.png from Seven
Create a new file named custom.js for example
Add that file under scripts[] in seven_custom.info, like so:

scripts[] = custom.js

Edit your JS file to extend Drupal behaviors and use Drupal.t() for making strings translatable:

(function ($) {
  Drupal.behaviors.UltimaTheme = {
    attach: function (context, settings) {
      $('input#edit-field-mine-und').change(function() {
        if($(this).is(':checked')) {
          alert(Drupal.t('Checked'));
        }
        else {
          alert(Drupal.t('Not Checked'));
        }
      });
    };
  };
})(jQuery);

I wrote this without testing, but should work fine. Let me know if it doesn't.


Alter how exactly? You can cast the markup object to a string, then you can change the string or completely replace it.

Also check out the default integration that the contact_storage module has with swiftmailer to allow sending mails as HTML. That might get you much further than trying to change this string.


I think (not checked) that you need to add "target" => "_blank"  ((note underscore)) to the #attributes array. However, that attribute must appear on an  element that encloses the , not the  itself, and I'm not sure if adding it to the structure in your question would do that... have a go.

If it doesn't work, simplest option is to override the twig template in question and then extend attributes with "attributes.setAttribute('target', '_blank')" in the appropriate place.

Determine the right file name to override the twig template with by using twig debug (look in the sites/default/local.services.yml for the setting to change).
, and then view-source of the page (noting there are now lots and lots of html comments), find the existing image html and look before it to see the table of possible templates. There is lots more about this in the official Drupal documentation on twig.


I used the Chaos tool suite module, and it does that!


Can't acces field collection with $content

field_view_field() would probably do the trick:

$rendered = drupal_render(field_view_field('node', $node, 'field_image_teaser'));

There are other options you can pass to the function (display mode for example), so it might be worth checking out the docs to see exactly how you want to use it.


return $form['elements']['status'] is correct.

you need to create your form elements in

public function buildForm(array $form, FormStateInterface $form_state) {

$fields = $form_state->getValues();
if (!isset($fields['status']){
   $form['elements']['status']['#prefix'] = '
';
   $form['elements']['status']['#suffix'] = '
';
   $form['elements']['status']['#disabled'] = myfn_disable_attendance($form_state);
}


Should be able to do it with drush_hook_COMMAND_validate().

Example: https://github.com/Lullabot/drupal-boilerplate/blob/master/drush/commands/policy.drush.inc


How can I programmatically get a list nodes that a user can update?

There should be a view filter like that, but you'll need to use a relationship (Access log: User should do it) then add the filter called User: Permission.


clive would suggest to create a new Formatter for image type fields that would allow in the render display to select a image style for the image link.

At least i could do "In the field formatter settings you can tell the image to render in one style, but link through to the full image" and clean the code to:

(function ($, Drupal) {

  Drupal.behaviors.fancyBoxInit = {
    attach: function (context, settings) {
      $('[data-fancybox="gallery"]', context).once('fancyBoxInit').fancybox({
        buttons: [
          'close'
        ]
      });
    }
  }
})(jQuery, Drupal);

with in image-formatter--media--image--field-media-image.html.twig

   {% if url %}
      {{ image }}
    {% else %}
      {{ image }}
    {% endif %}


If you are sure that your execution do not produce programming errors, the problem may come from the fact that Drupal only executes queue items when running Cron. Taking into account that Drupal Cron is limited by time and PHP memory, your queue items may not be fully processed in a single Cron run.

You can refer to this issue I created some time ago about a very similar problem.

In short, I solved it by processing queue items every X minutes.


If the persistent connections is not enabled you can enable it by adding this to settings.php:

ini_set('mysql.allow_persistent', TRUE);

And you just do like this to turn it off:

ini_set('mysql.allow_persistent', TRUE);

To check is persistent connections is enabled go to /admin/reports/status/php, and search for allow_persistent.


Migrate: Duplicate entries in url_alias after update migrations

Looks like a bug in the core path module: https://www.drupal.org/node/2350135


How to manually delete a node from the database knowing its id

You should use node_delete:

<?php
$nid='22'; // $node id , which you want to delete;
node_delete($nid);
?>

This function from the API does the necessary cleaning up when a node is deleted.

You can stick this in a custom module, or enable the PHP filter and just have it a node where you allow PHP code.

If you use the PHP Filter method, remember to disable it when done.  You don't want it permanently enabled on a production site.

You may also want to repair your database, just to make sure.  The screenshot below shows how to use phpMyAdmin to repair the {sessions} table.  You can also use to repair the {node} table


First, you need 'options' => array('clarification required', 'clarification isn\'t required') for select because you need options. Then you need to make sure your module name is custom (unless you don't want to expose your module name). Also, you pass your function name to $form['#validate'][] but it ends with _submit (it should be _validate).

There are what I found at the first glance. I didn't check the code.


Yes you can add fields: mail, phone & room to each of your tax terms, but the problem would be that all your employees would have the same mail, phone & room, because the fields belong to the tax term and not the employee. Unless you create a unique tax term for each of your employees this would work, but why do this when page<->contactBlock will do the same?

So either you stick with page<->taxonomy term<->contactblock

or go with page<->contactBlock using the Entity Reference module in D7 (for D8 Drupal Core already has this module's features). This option will save you save Database space since you don't create tax terms.


How to programmatically update node title?

To do this, you have to use hook_node_presave().

It's called before saving the node to the database. (both new nodes and edits).
Note that you must make sure that you are saving sanitized and formatted data.


Max File Upload Size set to big, but Ajax Error with old file size

Just for documentation I'd like to add my findings here. I had this issue in Drupal 8, but I guess the Drupal version can be neglected to answer this question.

Suhosin

As @Clive already mentioned it in the comments to the question it's definitely worth a look under /admin/reports/status/php if the Suhosin PHP extension is enabled.

In https://www.drupal.org/node/725056 people suggest to disable this extension completely, but it's maybe better as @Clive suggested to simply override one of its parameters by editing your php.ini. Or by setting this in settings.php – if that is possible at all – via ini_set('suhosin.post.max_value_length', '-1'); or something like that. Maybe it's a different parameter you have to override.

Or Apache

If there's no Suhosin extension enabled, you may find this forum post valuable: https://www.drupal.org/forum/support/post-installation/2015-04-07/ajax-error-when-uploading-large-files where it's suggested to disable or reconfigure Apache's mod_security security mod.

Or JS

Last but not least you could simply try to circumvent Ajax completely by unbinding the event handler for the submit button, or by removing it completely.

Drupal 7

// Disable ajax upload for file field
drupal_add_js("jQuery(function() { jQuery('#edit-field-image :submit').unbind(); });", 'inline');

Source: How do I disable ajax on file fields?

Drupal 8

(function ($, Drupal) {
  Drupal.behaviors.autokill = {
    attach: function (context, settings) {
      // $('.form-managed-file > input.form-submit').remove();
      $submit_button = $('.form-managed-file > input.form-submit');
      $submit_button.unbind();
      $submit_button.removeClass('js-hide');
    }
  };
})(jQuery, Drupal);


How do I render a node returned by the Drupal search module?

You need to prepare a view for the node object:

$view_mode = 'teaser'; // Or whatever
$view = node_view($result['node'], $view_mode);
print render($view);


How do I use PHP in "Rewrite results" for a field in a view?

No, it cannot be done. You can write HTML code in the rewrite box. Please take a look at this if you need to write php code in Views: Views Custom Field
Although I would suggest you create a template to add any custom php code you require.


Connecting 3 content types together entity reference/field collection - adding references in reverse?

It looks like you need Corresponding Entity References:

  It syncs the entity reference between two entity types which have an entity reference to each other, so double editing entities is no longer needed. If one entity has a reference, the other entity also receives a reference to the saved entity if it is referenced in that entity.


Since you can't have the role sensitivity reliably in the links themselves, I'd tackle this differently by using an intermediary routing function.

So if you have a link you want to point to mypath/role_1, mypath/role_2 etc, you might point it to role_route/somekey defined in mymodule.routing.yml like so:

mymodule.role_route:
 path: 'role_route/{key}'
 defaults:
  _controller: '\Drupal\mymodule\Controller\RoleRouteController::route'
 requirements:
   _permission: 'access role paths'

The route function of the controller might be something like:

function route($key) {
  $current_user = \Drupal::currentUser();
  $roles = $current_user->getRoles();
  // logic to process roles and key to get wanted route
  ...
  $role_route_name = ... ;
  return new RedirectResponse( Url::fromRoute($role_route_name);
}


I only want to modify one tpl.php for a theme, do I need to copy the base theme?

The minimalist amount you need for a subtheme info file are the 2 required keys, name & core, plus the declared base theme key, base theme.

If you a create info file with those keys, copy over the tpl.php (e.g. page.tpl.php) from the base theme, modify it, flush caches (to rebuild the theme registry), and use the Enable and set default from the theme administration page, you should have a working subtheme.

See the d.o. docs on creating a subtheme for more info.


remove Anonymous user from "Entity Reference" users list

One way would be to create a View with an "entity reference" display to show all users with an id greater than zero, then use the Views "Entity selection mode" for your entity reference field:

You can choose the View you just created and the anonymous user will no longer show.

There's also the Entity Reference View Widget module which provides an advanced version of this functionality, though it's still in alpha.


The correct answer is you need to look at how to turn on twig debugging
Please read and understand:
https://www.drupal.org/docs/theming-drupal/twig-in-drupal/debugging-twig-templates
once you have fully read the above and have set it up you will be able to find the correct template and copy the default form  the core to your theme and edit away.


I think the problem lies in your contextual filter.  Presumably the teacher's profile page does not contain the taxonomy term ID in the URL, it usually doesn't unless you've done something tricky to put it there.

So: the view is looking at yoursite/user/[uid] and it thinks that the [uid] is the taxonomy term id (because you told it so), so doesn't find any matches and returns a nil result.

I'm not sure how to fix that, but hopefully this will help you troubleshoot.


Nesting a View in a View... or something like that

Check out the Views Field View module.  I have not used it, but it is supposed to embed a view in another one.  Please post back if it works.


Is there a way to know the node being viewed?

Wow - I just got a reply back from Acquia support that answers the issue. menu_get_object() seems to be one of those magically functions I never knew about. Neat.

global $user;
$node = menu_get_object();

if ($node && $user) {

  print '
node uid = ' . $node->uid;
  print '
user uid = ' . $user->uid;

  if ($node->uid == $user->uid) {
    print t('
You are the author of the current node.');
  }

}


I assume you mean this module? https://www.drupal.org/project/youtube

If so this module provides a field for your content type of choice where you need to display the video. The most basic content type to start with is "Basic Page".

Once you add this field, when you "add content" for this youtube field you can specify it's URL. When you view this node/entity the video player should show up. This module does have the ability to render the Youtube player, but there's a chance you may have to configure your content type view mode.

This Youtube video has more details on the setup for the Youtube Field module - Youtube Field Setup Video


Is it safe for me to use _taxonomy_title_get_title() implemented by a third-party module?

Drupal adds a underscore to its function to mean they are for internal use only, and modules/themes should not depend upon them. For example, in Drupal 8, the theme() function was renamed _theme() as reported in theme() renamed to _theme() and should not be called directly, which also states:

  It has been renamed to _theme() and is for internal use only.

Then, it was removed.

Third-party modules follows the same naming convention: If the function name starts with an underscore, they don't want they use that function. This doesn't mean the function is necessarily going to be removed, but the maintainers could remove it at any time, even passing from version 7.x-1.5 to version 7.x-1.6.

So, if by safe you mean sure that the code I am writing will not need any change, then I would say no.
You could eventually write your own code that uses just safe functions made available from that module, using _taxonomy_title_get_title() as starting point; otherwise, you need to check your code is still working when updating that module. Depending on your specific use, you could also use tokens; the module defines [term:title] which is set using the function you are calling.

/**
 * Implements hook_tokens().
 */
function taxonomy_title_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  $sanitize = !empty($options['sanitize']);

  if ($type == 'term' && !empty($data['term'])) {
    $term = $data['term'];

    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'title':
          $title = _taxonomy_title_get_title($term->tid);
          if ($title) {
            $replacements[$original] = ($sanitize) ? check_plain($title) : $title;
          }
          else {
            $replacements[$original] = $term->name;
          }
          break;
      }
    }
  }

  return $replacements;
}

See also Call to undefined function _taxonomy_title_get_title(); it is for the version 6.x of the module, but users are essentially saying that, passing from version 6x-1.3 to 6.x-1.4/6.x-1.5, they get an error about the function _taxonomy_title_get_title() being not defined. (In fact, it was renamed _taxonomy_title_get().) Since the development snapshot doesn't call _taxonomy_title_get_title(), I get they are talking of other code.


I would prefer mail a new link to user rather than altering the current link.

Use Tokens API to create user wise links.

function MYMODULE_token_info() {
  $info['tokens']['user']['passresetlink'] = array(
    'name' => t('Password Reset link 2'),
    'description' => t("Password Reset link 2"),
  );
  return $info;
}

and

function services_chat_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $replacements = array();
  if ($type == 'user' && !empty($data['user'])) {
    $user = $data['user'];
    foreach ($tokens as $name => $original) {
      switch ($name) {
        case 'passresetlink':
          //$user = user_load($node->uid);
          //$newlink = make your link here.
          $replacements[$original] = $newlink;
        break;
      }
    }
  }

  return $replacements;
}


How to add two fields on one add another items?

CCK version 6.x-3.0-alpha3 contains a module called Multigroup. It allows you to group multiple fields together and repeat that group of fields multiple times with a single add-another button. This is an alpha version though, so if you decide to use it, test well to make sure it doesn't break something else.


Delayed error messages for webform blocks in template

I've created a new region and inserted the webform block there.


Default entity ID for _entity_view in routing.yml

The default ID can be set in the defaults section, here is an example:

my_module.view_dashboard:
  path: '/admin/dashboard/{my_entity_id}'
  defaults:
    _entity_view: 'my_custom_entity.full'
    my_entity_id: 123
  requirements:
    _role: 'authenticated'
    my_entity_id: ^[0-9]+
  options:
    _admin_route: true
    parameters:
      my_entity_id:
        type: 'entity:my_custom_entity'

my_module.view_stats:
  path: '/admin/stats/{my_entity_id}'
  defaults:
    _entity_view: 'my_custom_entity.full'
    my_entity_id: 456
  requirements:
    _role: 'authenticated'
    my_entity_id: ^[0-9]+
  options:
    _admin_route: true
    parameters:
      my_entity_id:
        type: 'entity:my_custom_entity'

This solution creates nice URLs without any controller.


When I change a node title and hit save, I get 'page not found'

When you change the title of a node when URL auto-alias is turned on, you will need to fix your links to that node or do the options below. You are getting the page not found error, because it's trying to go back to the view version of the node that now has a different URL. You have the following options:

Install redirect. Then set up a redirect to the old URL. If you install this first, it will automatically track the changes of the URL moving forward.

Alternatively, you can go to the node and uncheck the auto-alias option and hand-assign the URL back to what it was before you changed the title. I recommend the redirect module though.


How to compare form value in an ajax call

I found an answer for me after trying various cases. The below is the call back function which I wrote.

function check_date($form,$form_state){
 $current_date = $form_state['values']['from_date'];
 $custom_value = sp_call_and_extract_needed_data();
 $error_message = t('your error message');
 $current_path = current_path();
 if (strpos($current_path, 'ajax') !== false) { //if call from ajax
   $commands[] = ajax_command_after('#breadcrumbs',  $error_message);
   return array('#type' => 'ajax', '#commands' => $commands);
 } else {
   form_set_error('from_date', $error_message);
 }
}


How do I set an empty link title in a menu item?

No need to resort to "dirty CSS tricks", you can just use clean CSS:

a.class {
  display: inline-block; // Or block if it makes more sense for your layout.
  text-indent: -9999em;
}

This is the correct way to handle it, as you can include proper text as your link (e.g. "Home"), so you're not alienating users with screen readers, etc.


Cant make profile2 fields visible to other users

Profile2 module separates core drupal user profile by adding a separate profile entity to it.The permission "view user profile" you are adding is related to drupal core user management not with profile 2 module.

Here is a screenshot for working permission set for a profile created using profile2 mdoule. The profile name is common

The roles in the screen shot are anonymous, authenticated administrator cutom_role.

As a tutorial this video can help.


With base you can tell views which table to start from

base is a sort of meta data for the views. It describes what would be the primary key of the table, what should be the views title in creating views and some help for the users to use this custom views.

field define the primary key of the custom table you want to show in views.
title is the title that will appear in your show dropdown on add view page.

EDIT: field is not a required field but its good to tell your view what is the primary key of your custom table. In case of composite key you can define both your columns in array(key1,key2)


How to add html head link tag when a specific block is loaded

See NodeViewController::view():

  $build['#attached']['html_head_link'][] = array(
    array(
      'rel' => $rel,
      'href' => $node->url($rel),
    ),
    TRUE,
  );

You can add html_head_link #attached elements anywhere, including in your block, and it will bubble up and be added to any page that shows your block.


Submitting a form rebuilds (expensive) page upon submit

You can also try using drupal_static

  Provides central static variable storage.

  All functions requiring a static variable to persist or cache data
  within a single page request are encouraged to use this function
  unless it is absolutely certain that the static variable will not need
  to be reset during the page request. By centralizing static variable
  storage through this function, other functions can rely on a
  consistent API for resetting any other function's static variables.

function test_menu() {
  $items = array();
  $items['test'] = array(
    'title' => 'Test',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('test_simple_form'),
    'access callback' => TRUE,
  );
  return $items;
}

function expensive_data() {
  $data = &drupal_static(__FUNCTION__);
  if (!isset($data)) {
    $data = very_expensive_data_operation();
  }
  return $data;
}

function test_simple_form(&$form_state) {
  $data = expensive_data();
  $form['create'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  return $form;
}

function test_simple_form_submit(&$form, &$form_state) {
  // do something
}

You might notice that the static variable technique only stores data for the duration of a single page load. For even better performance try this

function expensive_data() {
  $data = &drupal_static(__FUNCTION__);
  if (!isset($data)) {
    if ($cache = cache_get('my_module_data')) {
      $my_data = $cache->data;
    }
    else {
      $data = very_expensive_data_operation();
      cache_set('my_module_data', $my_data, 'cache');
    }

  }
  return $data;
}

If you want to refresh your cache from time to time you can try

cache_set('my_module_data', $my_data, 'cache', time() + 360);

OR you can manually rebuild your cache using

cache_clear_all('my_module', 'cache', TRUE);


Entity Forms are, IMO, a long shot.

1. Webform module

You can use Webform module, and add an Option list (HTML select list) field to the webform, and autopopulate it with a URL parameter. Webform module supports populating the field value automatically from any $_GET, $_COOKIE, or $_SERVER value.

For the select list values, you can use a View to build the list of Product nodes.

2.  Entity Forms

Since you already have an Entity Form, you can do it with the traditional field approach.
Similar to the webform's select lists, you can create a View to list all Product nodes. Entity Reference module supports Option (radio, select, checkboxes) field type, with the options fetched from a View. You can use Entity Reference Prepopulate module to populate the Product node from a URL parameter.

3.  Custom module

Either way above, you will have to use some modules. If you are OK to create a custom module, you can do it with a little coding as well. Be prepared to go through a little bit learning and conventions first. This is a nice guide to get you started.

You can do this easily with an EntityFieldQuery to fetch the eligible nodes list, and then setting the #default_value in hook_form_alter hook.


Is there a module which allows users to edit text together?

Maybe you want to consider using the Paragraphs module for this. Here are some quotes about it (from its project page):

  Paragraphs is the new way of content creation!
  It allows you — Site Builders — to make things cleaner so that you can give more editing power to your end-users.

  Instead of putting all their content in one WYSIWYG body field including images and videos, end-users can now choose on-the-fly between pre-defined Paragraph Types independent from one another. Paragraph Types can be anything you want from a simple text block or image to a complex and configurable slideshow.

  Paragraphs module comes with a new "paragraphs" field type that works like Entity Reference's. Simply add a new paragraphs field on any Content Type you want and choose which Paragraph Types should be available to end-users. They can then add as many Paragraph items as you allowed them to and reorder them at will.

Some other questions on Drupal.SE where the Paragraphs module has also been suggested as a possible answer (which may help for more inspiration about what kind of things you can do with this podule):

Modular Drupal content-type (variable sections).
Simulating TYPO3-Template-Engine.
Alternative to Field Collection.
What is the best method to allow a user to attach dynamic, custom content sections to a node?


Is it possible to get access to files uploaded via FTP in the media module in Drupal 7

Is it possible to get access and select FTP uploaded files via media module?

No.

When you upload the files yourself (via FTP or some other means that is not part of Drupal), they will not be recognised or known by the Media module.

There are a helper module called Filefield Sources that let you add files downloaded with FTP to Drupal media management modules.  A variation called IMCE Filefield currently integrates with the IMCE module, but there is AFAIK nothing similar for the Media module.

It has suggested to integrate Filefield Sources with the Media module. However, there does not seem to be anybody working on it, (just a lot of people who want it).

If you really want this, you probably need to add this to the Filefield Sources yourself.


drupal  shows empty content because of memcache

Have you installed and configured drupal with the module for memcache - http://drupal.org/project/memcache ?

There is also a handbook page that will be able to help you http://drupal.org/node/1131458


how can I identify sidebar blocks in my theme

Check (page.html.twig D8) or (page.tpl.php D7) and check (themename.theme D8) and (template.tpl.php D7)

Worst case scenario, backup first, then start deleting template files one by one and flushing the cache and checking, until you see the one that affects it.


Load node by value of a field and update value for another field

Thanks to the comment by @No Sssweat I realized that I simply needed to specify a content type:

$nodes = \Drupal::entityTypeManager()
      ->getStorage('node')
      ->loadByProperties(['field_one' => $fieldValue, 'type' => 'CONTENT_TYPE']);


Dont want horizontal scroll bar for views

You can use css like this:

overflow-y: scroll;
overflow-x: hidden;


Alter view plugin form in custom module files

Finally i've created an customized views_json_source module adapted to my requirement. Anyway, it would be interesting if somebody can ask the question.


How insert values from client page to database by use custom module

Here is way to do this. use line item type and create your filed.  Hook_commerce_cart_product_add() call in custom module.

  function mymodule_commerce_cart_product_add($order, $product, $quantity, $line_item) {

         $commerce_line_item = commerce_line_item_load($line_item->line_item_id);

         $field_main = $product->field_main['und']['0']['value'];

         $line_item->field_update[LANGUAGE_NONE][0]['value'] = $field_main;

         commerce_line_item_save($line_item);
     }

When user click on button "ADD PRODUCT TO CART", cart value add/update your commerce line item field.


How to implement a custom field available for Views?

Try views.api.php

  Describe hooks provided by the Views module.

& Views hooks

  Hooks that can be implemented by other modules in order to implement
  the Views API.


How can I have Exposed filter of Flag type in views?

You can follow these steps:

You can create taxonomy terms for your flag types.
Add  term reference (taxonomy reference) field in your content type pointing to flag taxonomy.
In your view, add filter of taxonomy terms then and check exposed filter checkbox.

You can use Better Exposed Filters module for better UI.


You can display both directions in Parent-Child Entity references with Views. You don't need to edit the reference to note direction in any special way.

The Entity reference field is already showing Children information on Parent nodes (your Project A is showing Project B and Project C).

List Parent links on Child nodes using Views

To show Parent links on nodes that are referenced from that Parent (backwards relationship) create a block and display it on the Child nodes:

Create Views of type Content Project. You'll probably have the Title field already there, leave it for now just for testing.
Add a Contextual filter ID from Content Category and configure it:
When the filter value is NOT available:
Provide default value
Content Id from URL
When the filter value IS available or a default is provided
Specify validation criteria
Validator Content
Project

Now if you enter the node ID (either Project will do: A, B or C) into the Preview argument field, it will only show that node Title in the Views results. This is just to test that our contextual filter is working correctly, when we place it on Project pages.
Add a new Relationship Content using field_project_reference (Relate each Content with a field_project_reference set to the content.) This is the backwards Relationship! Be careful not to include the forwards one that is called "Content referenced from field_project_reference"!

Require this relationship because it makes sense, we want only the results if the node we're on actually has a Parent, but it won't matter much if you don't tick this.
Edit the existing Title field and set it to use the Relationship from the previous step. The field using that Relationship will show the title of the Parent node, and not the one you're currently viewing, like it did up until now.

Edit the label to say "Other Projects referencing this Project" or similar.

Under No results behavior choose
Hide if empty

This will ensure that if the node you're currently viewing doesn't have any other nodes referencing it, nothing will be displayed. Otherwise, you'd get the Label and No results text (if you have it configured which you always should), or just the Label "Other Projects referencing this Project" with nothing listed there. With "Hide if empty" the block will not display anything which is more inline with displaying Fields on node pages.
Now place this Block on Project nodes in Content region if you want it show close to the orignal Entity reference field, set the Block settings Content ID: Node from URL and restrict to show it on Project types only.

You can use these Views to display other information from references nodes, not only Titles.

In Drupal 7 the module Relation provided two-way references, but it seems in Drupal 8 you can recreate that without that module. If you need fields on your Relation/Entity reference or other features read the comments at the bottom: Relation for Drupal 8 Development.


How do I restrict the type of characters that can be used at registrations?

Based on what you said in your comment, you should just use Pathauto. Pathauto allows you to remove special characters from user/node/taxonomy URLs; if someone's username is 'hey$3#@", you could make their user profile URL http://yourdomain.com/user/hey3.


Enforce rule on Sticky to the top of lists

Do you have a node for the overview page? If so:
Instead of using the sticky to top button add a relationship field to the job overview node and set that to allow 1 value, and show the selected job in the highlight field.


Populate Taxonomy Term reference field in node

First, find the taxonomy term id by the term name as given below.

function getTidByName($name = NULL, $vocab_name = NULL) {
  $properties = [];
  if (!empty($name)) {
    $properties['name'] = $name;
  }
  if (!empty($vocab_name)) {
    $properties['vid'] = getVidByName($vocab_name);
  }
  $terms = \Drupal::entityTypeManager()
    ->getStorage('taxonomy_term')
    ->loadByProperties($properties);
  $term = reset($terms);
  return !empty($term) ? $term->id() : 0;
}

Above function will return the term id and then pass this term id to your field like

// Assigning the entity reference value.
if ($tid > 0) {
  $entity->set('field_example', ['target_id' => $tid]);
}


The file has to be called node--home.tpl.php.
There always has to be 2 '-' between type and name.


How to prevent Rules scheduled within a month may have an offset that is off by 1 or 2 days?

Understanding the issue

The explanation for what you're experiencing can be found in the description of the (open) issue about "Dates are poorly handled". Here is part of what it includes:

/**
 * Defines possible duration multiplier.
 */
function rules_ui_element_duration_multipliers() {
  return array(
    1 => t('seconds'),
    60 => t('minutes'),
    3600 => t('hours'),
    // Just use approximate numbers for days (might last 23h on DST change),
    // months and years.
    86400 => t('days'),
    86400 * 30 => t('months'),
    86400 * 30 * 12 => t('years'),
  );
}

From the above code, it's obvious that there may be a discrepancy of some days if scheduling a rule X months from now (every month is assumed to have exactly 30 days, which is not the case of course). Similar problem when using years, and also a (minor) problem of 1 hour when using DST.

Making it work for MONTHLY executions

So far the bad news ... the good news is that there is a work around for this. If you use the Rules Once per Day module, you can take advantage of these additional facilities of this module (as mentioned on its project page):

  The module also provides a "Day of the week is a" Rules condition, to further restrict actions to being run on specific day(s) of the week, on working days only, or at weekends only.

  From version 7.x-1.1 there is now a "Day of the month" condition, too.

With that, you should be able to adapt any rule to perform its Rules Actions only once a week, or once a month.

Making it work for YEARLY executions

But, there is even more, for those cases where you want a rule to only execute once a year, you can use a Rule as explained in this issue and which looks like so:

Create a rule triggered by the "Once per day" event
Add a "Current day of the month" condition:

Comparison "equals"
Day of the month value "1"

Add a "Text comparison" condition:

Data selector "site:name" (dummy text, not used)
PHP evaluation "return date('m');" ( ! )
Matching text "^01$" (for January)
Comparison operation value "Regular expression"

The above logic will ensure that your Rules Action(s) are executed on exactly the 1st of January of every year (adapt the "1" and/or "January" to fit whatever other day of a year).

( ! ): I admit, this solution (only required for "YEARLY" though) requires the PHP filter to be enabled, which I try to avoid at any cost (I've not found an alternative for this yet ...).

PS: I'm assuming this question is about D7.


Drupal 7 and google maps, distribution or modules

Both the Open Layers project and the Gmap module support google maps. Both can work with a number of geolocation types. See the modules for more details.

I am using both (in different sites) and either one can support what you are trying to accomplish. I would recommend Open Layers as more versatile, and Gmap as easier to use.


You can use 'weight' for every block.

$blocks['contact_info'] = array(
  'info' => t('Contact Info Block'),//admin ui block name
  'weight' => 0,
);

$blocks['contact_form'] = array(
  'info' => t('Contact Form Block'),
  'weight' => 1,
);

I hope this will work for you :)


How do I search all contents including code from admin?

For a quick solution, you can edit the View that powers the Content page (or create a new View, edit a different View, etc), and add the body field as an exposed filter. Combined with a LIKE operator that should give you reasonably good results (though it will possibly depend on what input format you're using).

If you want something more like what you described, i.e. something that searches multiple fields at once, you could install the Search API module, create a results View, and add a combined filter that will search across all the desired fields. This approach takes a bit more effort, but might give more accurate results than the first one, especially if you use (for example) Solr as the backend.


Composite block from multiple other blocks + layout

Use blockgroup. Add block_class if needed.

When creating the block groups, make sure that the machine name does not clash with existing theme region machine names! (from any theme, ideally)

After you created a block group, it will show up in two ways in the blocks UI:

As a new theme region (if you avoided the name clash)
As a block that can be placed.

Block class allows to add classes (e.g. bootstrap grid classes) to each block and block group.

This is not 100% what you would get with a layout, but it is getting close, and will be sufficient in many cases.


How can I change the Apache Solr search URL?

This should work if you place it in settings.php:

function custom_url_rewrite_outbound(&$path, &$options, $original_path) {
  // Filter to get only the apache solr links with filters so it doesn't launch it for every link of our website
  if ($path == 'search/apachesolr_search/' && strpos($options['query'], 'filters') !== FALSE) {
    $new_path = $path.'?'.urldecode($options['query']);
    // See if we have a url_alias for our new path
    $sql = 'SELECT dst FROM {url_alias} WHERE src="%s"';
    $row = db_result(db_query($sql, $new_path));
    // If there is a dst url_alia, we change the path to it and erase the query
    if ($row) {
      $path = $row;
      $options['query'] = '';
    }
  }
}

function custom_url_rewrite_inbound(&$result, $path, $path_language) {
  // See if we have a url_alias for our new path
  $sql = 'SELECT src FROM {url_alias} WHERE dst="%s"';
  $row = db_result(db_query($sql, $path));
  if ($row) {
    // We found a source path
    $parts = preg_split('/[\?\&]/', $row);
    if (count($parts) > 1) {
      $result = array_shift($parts);
      // That's important because on my website, it doesn't work with the / at the end of result
      if ($result[strlen($result) - 1] == '/') {
        $result = substr($result, 0, strlen($result) - 1);
      }
      // Create the $_GET with the filter
      foreach ($parts as $part) {
        list($key, $value) = explode('=', $part);
        $_GET[$key] = $value;
        // Add this because the pager use the $_REQUEST variable to be set
        $_REQUEST[$key] = $value;
      }
    }
  }
}

And then when you create a menu entry, you put the link to apache solr : search/apachesolr_search/?filters=tid:13

And create a url alias for search/apachesolr_search/?filters=tid:13 like products/tv.html

Found via: http://drupal.org/node/783836#comment-4136475


It must have been some sort of caching issue, because the link above just worked.


Any administration page such as /node/add will be displayed in the selected theme, as long as the user has the permission 'View the administration theme' off (and of course has the relevant permission on, such as to create nodes for the specific type).

You wouldn't really need to create a custom form for that, the standard node create form may be sufficient. Of course you could, you would have to read the documentation such as this.

As far as the first requirement about validation from administrators, the modules Workflow and/or Rules would be useful.


Problem installing Knowledge base module

The install yml is not in the wrong place.  This is a new module with 1 install currently in beta state so you might face a few problems with it if not all bugs are not ironed out but perhaps this is not the case.

The error message is not that helpful I must admit. If you want to see what dependencies you are missing you go into the .info.yml file and can also be seen online here and here is the relevant section

...
dependencies:
  - drupal:field
  - drupal:file
  - drupal:text
  - drupal:node
  - drupal:group
  - drupal:gnode
  - drupal:views
  - drupal:views_jump_menu
  - drupal:eva

for field, file, text, node, views are part of core (nothing to do)

but you have to download
https://www.drupal.org/project/group (for group and gnode)
https://www.drupal.org/project/views_jump_menu
https://www.drupal.org/project/eva

before you are able to install this module

I suggest that you start looking into installing things using composer that takes care of the dependencies for you so if you did

composer require drupal/kb

all the dependencies would also be installed for you

More info about composer based drupal installations can be found here and here and perhaps other places but those are good starting points


From below code example you can get the page title as your requirement

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

Hope this helps. :)


How to add the User:Picture field on the account registration form?

You can use Register with Picture module.

  This module exposes the 'upload picture' element to the registration
  form. It also gives you the ability to set a picture as required in
  the module settings.

  Drupal 7 Instructions

  Install and enable the module
  Navigate to: Configuration -> Account Settings. (admin/config/people/accounts)
  Check Enable user pictures if it isn't checked already.
  Confirm Enable pictures on registration is checked.
  Use the Registration Picture Field Weight field to adjust the display order of the picture field on the registration form. It can be
  a negative or positive number.


How to create custom bundle of "User" entity using GUI?

I had the same requirement recently and was able to achieve this using the Profile2 module.  Basically you set up profiles and add custom fields to that particular profile.  Then you create a user using that profile.  Works great but if you are pulling a view of these you must reference the profile in a relationship.

Profile2
https://drupal.org/project/profile2


Real world experience in scaling and tuning performance

Markdorison's answer is basically the accepted method of attacking this problem. I'll take that a little further.

When you have Pressflow for D6 or Drupal for D7, Memcached and Varnish all working nicely together you'll need to custom code your VCL file. There are free ones available  that make starting points but you always need to play with them.

To get Varnish to work optimally make sure you start it with -s malloc xG rather than the default of -s file /path/to/file.
Also with Varnish have Varnish cache static items for as long as you can.

If you have more than one web server remove the ETag from the header sent to Varnish in VCL. I also remove Expires and simply rely on Age and max-age in the headers so get browsers back to the site.

Version 1.5 (as of 3rd March 2011) is still the fastest version of Memcached module from Drupal.org. I typically deploy it using a single bin per server to lower tcp traffic for connections to multiple bins at large scale)

Configure the caching in "Performance" to external and set a max age which will send the correct headers to a caching proxy such as Varnish.

If you can't get certain pages to cache properly in Varnish check out blog posts on the web that detail how to inspect the requests. Here is an example post I wrote a while back: What is stopping Varnish and Drupal Pressflow from caching anonymous users page views

You should pick InnoDB (or one of it's other names from other providers like XtraDB) for MySQL and move all tables into it. Then check out this blog post for basic tuning advice http://www.mysqlperformanceblog.com/2007/11/01/innodb-performance-optimization-basics/

Having a large buffer pool is fundamentally important. When load testing the site turn on the slow query log. You probably want to at first capture queries taking longer than 50msec then tune the queries and repetitively reduce the slow log capture time down until you have most queries running using indexes, and executing fairly quickly.

Other basics involve having APC in for PHP. If you go for fast CGI rather than mod_php do spend some time trying to make the APC cache shared across the php instances by configuring a good wrapper script. Also make sure that the APC cache is in a memory mapped file to squeeze every last bit out of PHP.


How do I find out which what fields are available?

Might depend a little on what you're trying to do with those fields (get info/set info/adjust info), but here are a couple of things you could try:

CustomHandler.php

For submission data:

/**
 * {@inheritdoc}
 */
public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {

  // Get the submitted webform data.
  $data = $webform_submission->getData();

  // Get specific submission value.
  $myFieldValue = $data['field_name']
}

For webform field values (e.g. type = radios):

/**
 * {@inheritdoc}
 */
public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {

  // Get the webform fields (which will contain properties/attributes/values/etc.).
  $elements = $webform_submission->getWebform()->getElementsDecoded();

  // Get field values.
  $fieldType = $elements['field_name']['#type'];
  $fieldTitle = $elements['field_name']['#title'];
  $fieldFirstOption = $elements['field_name']['#options'];['option_one'] // If you need the selected value that will be in ->getData(), or in ['#return_value'] key.

  // Get webform owner (not anonymous).
  $webformOwner = $webform_submission->getWebform()->getOwner();

  // Get owner values.
  $displayName = $webformOwner->getDisplayName();
  $userName = $webformOwner->getUsername();
  $userEmail = $webformOwner->getEmail();

  // And to set data values:
  $data = $webform_submission->getData();
  $data['myNewValue'] = $myNewValue;
  $webform_submission->setData($data);

  // If you need to find some other available methods, try:
  kint($webform_submission->getWebform());
}

Fields on the webform, e.g. feedback_type, your_email, first_name will be available inside the method ->getElementsDecoded().


Custom Module Remote Fails Checksum with Drush

Answer

This isn't a good answer, but it works:

There is an undocumented drush flag --no-md5 and if you pass that to drush up it will skip the md5 check and the update will succeed.


Combining Date Start and Date End in Drupal 8 Views Block

You can create a custom field formatter plugin for the daterange field type and you can use it at other places on the website too.


Programmatically get input format in field template

I would suggest you to create separate template based on field's text format.
Here is the way:

Create a TEMPLATE_preprocess_field function in template.php file of your theme.
Copy and paste a file named "field.tpl.php" and rename it to "field--[your-field-name]--[its-text-format].tpl.php.

The function is :

function MYTHEME_preprocess_field($variables) {
  switch ($variables['element']['#field_name']) {

case 'body':
  $element = $variables['element'];
  $entity_type = $element['#entity_type'];
  $field_name = $element['#field_name'];
  $language = $element['#language'];
  $entity = $element['#object'];
  $values = field_get_items($entity_type, $entity, $field_name, $language);
  $item = array_shift($values);
  $format = $item['format'];
  $variables['theme_hook_suggestions'][] = 'field__' . $field_name . '__' . $format;
  break;
      }
    }


How to change the order of banners using the weight module?

Check out these modules :
weight

This module adds a weight option to enabled node types. Nodes with
lower weight will float to the top of lists, while heavier items will
sink.

Field_weight

Customise the weight/order in which fields on nodes can be displayed
on a per node basis and not just globally per type. Individual fields
can also be hidden from display.
For any node types that are enabled, a 'Field display weights' tab
will appear on nodes (for users with adequate permissions). From this
page administrators can customise the order in which fields are
displayed on each node by using a draggable table (or manually select
weights).

Nodequeue

The Nodequeue module allows users to collect nodes in an arbitrarily
ordered list. The order in the list can be used for a any purpose,
such as:

A block listing teasers for the five top news stories on a site
A user’s favorite music albums
A group of favorite from which one is randomly displayed

Nodequeue provides a simple drag-and-drop interface
to manually order any queue. Additionally, it allows nodes to be added
and removed from queues without needing edit permissions to the node.
Nodes can be added to queues either from a queue management tab or by
links on the node teaser.


What does menu blocks "Block title as link" option do?

For me it doesn't show the menu name, but the link to the parent menu item of the block. IE with a menu hierarchy like this:

<Main Menu>
-- a
---- b
------ c
------ d
------ e
-- f
-- g

If the block looks like this:

Title
c
d
e

Then having the block title as link makes the title a link to menu item b.


How to allow user picture during registration?

You should be able to use the Register with Picture module.

I've never experience any problem with this module.

You install it and configure it, and it does what it is supposed to do.

  This module exposes the 'upload picture' element to the registration form. It also gives you the ability to set a picture as required in the module settings.

You will be given a check box at admin/config/people/accounts named "Enable user pictures on registration" and weight selection. Make sure you also check "Enable user pictures".

This is how it should look like when a new user tries to register:


Is this SQL query even possible in Drupal 7?

Drupal has it's own abstraction layer to work with database , this method helps Drupal to work with different kind of databases like PgSQL or even oracle (just a database driver will handle everything).

You can get familiar with this api in : Drupal Database API

A more exclusive reference could be : Drupal Dynamic Queries


What do you do in a Views field theming function to change the output?

I seem to have stumbled into something that works:

In the Views control panel for my Calendar view, I went down into Format > Settings > Customize Fields, and clicked the "Use a custom title" checkbox.  After I did this, the system started paying attention to views-view-field--fullcalendar--field-target-date.tpl.php, and used whatever I printed as the title of the events in the calendar.

So far, all is well, although I'm not sure whether this is an inherent part of the Views system per se, or if it has something to do with the module's use of the fullcalendar jQuery plugin.  Other solutions/answers/explanations are of course welcome.


How to show payment form on node form preview in Drupal 7?

Try out Pay-per-node module.

  It can be used as standalone module or as an e-commerce plug-in. In
  the second case paypernode can be integrated with Ubercart, providing
  a new "product feature" which will allow, upon product purchase, to
  create a number of nodes.


Machine readable coordinates to Geofield

This question is similar to the follosing, I recommend using the Feeds module: How do I import latitude/longitude into geofield?


Pre-process node type for each node and print within region.html.twig template

You need to use preprocess region:

function iom_preprocess_region(&$variables) {
    $node = $variables["node"];
    $variables['content_type'] = $node->getType();
}

Clear/flush cache after adding it.


Look into the HTTP Parallel Request & Threading Library. The Imageinfo Cache module uses it to generate imagecache presets when a file is uploaded on a node form, and does a final check on node save; all in the background. The other module to look into using is Background Process, it does similar thing as HTTPRL and the 2 modules are actually looking to merge together (http://drupal.org/node/1357652).

An example of how to flush caches in the background is in the httprl readme


How to render media shortcodes e.g [[fid:1234]]

I found the following load_file() and field_view_file() functions which worked a treat for me. I bundled them with a regex search and replace.

Rough abstract taken from my code not tested but the theory remains the same.

preg_match_all('/\[\[{"fid": ?"([0-9]+)".*?\]\]/', $tax_body, $matches);
foreach ($matches[1] as $index = > $fid) {
  $file = file_load($fid); //load the file
  $content = file_view_file($file); // turn it into a render arrray
  $replacement= drupal_render($content); // render it into html string
  str_replace($matches[0][$index], $replacement, $tax_body);
}

Perform a regex for [[{"fid":(???) ..] where the ??? is the file id that is captured in the $matches[1].

Loop through all found instances, lookup the file markup, and then do a search and replace on the entire string replacing the full shortcodes (matches[0]) with the replacement markup.


How to delete a content in a view with view rules?

Depending on your needs you could potentially use Views Bulk Operations (also known as VBO).


Should I use Spaces or Domain Access to share & separate content between subdomains?

I believe I have settled on an entirely different preferred solution - multisite.

For my particular situation, my priorities are derived from having to hand over the multiple site setup to another developer (with unknown resource/ability). I believe that with this in mind my question contained a couple of false assumptions, namely

that a single site would be simpler to hand over to another developer
that therefore maintenance costs would be lower than retaining multiple sites

The site will probably not have to share much content, and even fewer users, between sites so the main crossover is providing a shared search index. I have already solved this by separating the search functionality via aggregation (in an admittedly circuitous fashion). There are more powerful and efficient multiple site options involving Apache Solr or similar, but having separated search from the sites, these options are still open, and need only be implemented in one place.

A single site with multiple domains must necessarily make use of Domain Access, Spaces, Organic Groups or some combination of these. It may, therefore, be a single site, but it is not a simple site. Even if the documentation I provide with the site is perfect, the inheriting developer may encounter complications or complexities when maintaining or extending this more sophisticated site. Domain Access, though the most popular strategy, worried me particularly because of its interference with the core

I also found this article particularly useful in resolving my indecision. One aspect I had not considered with regard to a multiple domain site was the potential for path conflicts. I can certainly imagine a situation where both site1 and site2 have an /about path, and I cannot imagine an easy, maintainable way of getting round this within a multiple domain site without allowing drupal to create an ugly /about-0 path for site2. I find this distinctly unappealing, and it could cause some issues for existing paths.

I have always been quite reticent about using drupal's inbuilt multisite functionality to share a codebase between different sites (with different databases). For the purposes of updating etc it has often seemed simpler to me just to have separate codebases and manage shared code through version control, (because I can break a single site). In this handover situation, however, I think maybe a single codebase better communicates the absolute similarity of aspects of the different sites. As long as configuration is, as far as possible, captured in Features, there should be little confusion about the degree to which components and behaviours are shared between sites. The multisite codebase can easily be separated out into different sites later if required.

As a side-note, one advantage I had not previously considered for the multisite setup was the reduced amount of memory required to cache compiled PHP code (detailed here).


Improve extremely slow 'drupal_process_form'

Based on the backtrace, you won't know why your site is slow.

You should run a proper PHP profiler and analyse the results which can identify the slowest components.

It doesn't have to be Drupal it-self, but could be lack of caching or misconfiguration.

Some suggestions:

disable modules which you don't need (e.g. Devel, core Database Logging module, etc.),
upgrade your PHP to the latest or higher branch,
recompile your PHP for 64-bit or higher architecture depending on your CPU,
use the faster storage device for your db files or whole LAMP environment (e.g. SSD or memory-based filesystem),
use PHP debugger or profiler to find out any performance bottleneck (e.g. XDebug Profiler, DTrace or NuSphere PhpED PHP Profiler),
run some time-consuming drush command under gprof profiling tool, so you can find some performance bottleneck as well.

If disabling slow modules or profiling won't help, see: How do you improve Drupal performance?


Request header field X-CSRF-Token is not allowed by Access-Control-Allow-Headers in preflight response for Drupal 7 REST API

Have a look at cors module
You'll be able to add necessary Access-Control-Allow-Headers

Otherwise, you can do this by changing your apache (or nginx or whatever) conf.

In drupal 8, you define this in services.yml, as explain here.


How to find content that uses a File (File Entity)?

Create a view of type files:

Add a relationship to 'Content', make sure you set it as required:

Add any fields you wish to see of the file or the node.


$ drush @foo ssh 'ls -al *' works great, for any @foo alias that is remote.


What's the best way to include PHP in nodes?

Normally I do heavy php lifting on nodes in hook_preprocess_node(&$vars) and parse / include content in the $vars.

hook_nodeapi() is of course another way to go about it and your additional content will be available in many different $operations, I don't use hook_nodeapi() unless I'm altering data that gets saved, deleted etc within nodes - for display layer stuff hook_preprocess_node() always treats me well.

If you could expand on what sort of preprocessing and content you are including in nodes I'm sure we could go into more details into the best suited solution :)

Update: Given the variety of the tasks you aim to use (APIs, Additional DB Calls, or User Input Parsing etc), I'd definately recommend you use hook_nodeapi so you have the fine grained control over the context. preprocess is view layer only and I feel as though you will likely want to hook the nodeapi(&$node, $op = 'load') so as to make your data entries high level enough to have the information widely accessible (like $node->your_custom_api_field in a node.tpl.php)

I highly recommend that you try to stay with Drupal's conventions as much as possible. Using database functions etc. Checkout the http://drupal.org/project/data module and possibly http://drupal.org/project/schema which both help working with your own tables (and the data module even helps expose that table to views so you can stay with Drupal core more!)

p.s.

My advice is to create a custom module for each data module you have so it can have it use it's own hook_nodeapi and any other hook's that may be required :)


Views: Select nodes having a specific field empty

Have you tried using better exposed filters?


How can i print multiple query output in GLOBAL:PHP view field?

There are many errors in your code :)

First, don't use $data variable, as it's already used in your view ; check the available variables section under your php inputs. Normally, it's advised to use $static.

Second, did you check elsewhere that

$shop_url=db_query("select page_url from mytable1 where user_id=$row->uid");

returns something ? Because I would have thought that only

$shop_url=db_query("select page_url from mytable1 where user_id=:uid", array(':uid' => $row->uid));

would work.


Drupal 7, Rules, Convert text to date and set a date field

field_get_items() returns an array of items – try strtotime('m-d-Y', $mydate[0]['value']);. Also, it looks like you have an extra ( on your field_get_items call:

field_get_items((

I would recommend installing the devel module, then you can add this code anywhere you'd like and get the results printed in your messages area for quick debugging and to see what data is available to you and how it's nested:

$mydate = field_get_items($entity_type, $entity, 'field_textdate');
dpm($mydate);


Autocomplete widget - save id of suggested and accepted value

Use the Entity and Entity Reference modules to create the link between the two items, using this method means your selections will be available to other modules such as Views, Rules, etc.


Alter behavior of Next Page > button on a multipage webform page

webform_client_form_submit handler should be enough to use. Depends what the 'behavior' exactly is.


In Drupal 7 you can do something like the following:

Set user_password_reset_timeout variable (i.e. in settings.php
i.e. in settings.php:

$conf['user_password_reset_timeout'] = '600000';

Then it will use this time after password generation link, when this much time elapsed the link will be invalidated.

You can follow the thread here


Conditions for using mail.css with drupal_mail()

The problem in my case was that the email being sent wasn't using the drupal_mail function but php send mail.

I run msmtp on my server to route mail and so rather than passing through drupal, the email was being sent directly through my server with none of the styling.


Overwriting database with backup from older Drupal version?

Yes - in most cases, this should be a fairly straightforward operation. You should be able to migrate your updated modules from dev over to the live site and just run update to get everything running again. If there are going to be issues with this (for ex. a module that requires a little more configuration to get working), you can isolate these issues before-hand on your dev server (and it sounds like you've already done this successfully).

Most of the top contrib modules (ex. the ones you cite above) will be very careful at upgrading their structure without impacting any new data (or orders).


Access values from multiple field forms as elements of one form

You need to use the #parents variable as documented in the field_attach_form page.
See field_attach_form