Red Herring Error : Class name must be valid object or string

For those who have been using PHP a while, it should be obvious what is causing the issue, although what wont be obvious is why Drupal didn't make a song and dance about it.

Basically the cause of the WSOD were the two ampersands denoting call time pass by reference. Something that has been deprecated in PHP for a while. The reason why they were there at all was just a copy and paste typo.

return microsites__admin_settings__ajax_button(&$form, &$form_state);

The above should have been:

return microsites__admin_settings__ajax_button($form, $form_state);

With the above change made, everything magically started working again.

Now I might get some people assuming that we just hadn't been keeping track of our errors, but we had as much logging enabled as possible... at no point did either PHP or Drupal complain about the call time pass by reference. Instead what Drupal seemed to do — and only after clearing cache I might add — was fail to include other files once it had hit this illegal / deprecated syntax, which then went on to create malformed entity_info arrays.

I have since tested this on other files, and all it takes is to add a call time pass by reference and it breaks Drupal, at least for all my localhost setups anyway... that is, unless the following has been specified in the php.ini:

allow_call_time_pass_reference = On

If anyone can ascertain as to why the silence (considering all other PHP errors and warnings are shown), why it broke other files loading, and why the problem only affected when running after a cleared cache, I'd be interested to hear.

Maybe upgrading to 7.22 would fix a few of the above... but in future I'll make sure I double check coherence between my entire php.ini(s) I think; rather than spend a few days trying to bash through a brick wall using only a toothpick.

update

Just to answer Clive's question, this was the output in the apache error log after I've just tested the same problem again:

[Thu Apr 11 11:15:29 2013] [notice] Digest: generating secret for digest authentication ...
[Thu Apr 11 11:15:29 2013] [notice] Digest: done
[Thu Apr 11 11:15:29 2013] [notice] Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8r DAV/2 PHP/5.3.6 configured -- resuming normal operations


Will the site load slower when using a sub-theme of a sub-theme?

TL;DR Have as many sub-themes as you want, it's not a problem.

Longer answer All types of inheritance, theming or otherwise, will have a performance penalty, and really all logic that you perform will have that effect; However

With proper caching enabled, only the very first request that uses the sub-sub-theme, is actually going to notice a difference. After that you will have aggregated css/js files from all three (or more) involved themes, and all of this becomes a non-issue until you clear the cache, after which you will again need to aggregate the files once.
With a pretty big generalization, the performance cost is roughly going to be linearly proportional to the number of changes you make. So if you don't make a lot of changes, you won't see a big effect.

Generally speaking, I suggest you approach the problem the other way around. Organize your theme/solve your problem in a way that is efficient for you as a human. Then worry about how to make it efficient for a machine only when necessary.

Since your site isn't written in assembly, your entire site is a huge performance problem, but in the vast majority of cases, a cpu performing literally trillions of calculations in a second makes that a non-issue.


In subtheming Commerce Kickstart, how to load my own background image?

It's necessary to go in /admin/appearance/settings for your custom sub-theme and in vertical menu on the left, click "Toogle Styles", uncheck the box for "Commerce kickstart theme global style" and click "Save configuration". Now click again in "Toogle Styles" and there is a new option: "MY THEME NAME theme global style. (all) - MYTHEMENAME_style.css".

Check this option and again click in "Save configuration".
Now changes in attributes in mysite/sites/all/themes/MYTHEMENAME/css/MYTHEMENAME_style.css does work.


There is currently no explicit command to run in order to grant a role a certain permission. The documentation is very helpful here - http://www.drush.org/help/5

However, you can use drush to execute native SQL in order to solve the issue

e.g.

drush sql-query "INSERT INTO permission VALUES (4,2,'access comments, post comments, post comments without approval, access content',0)"

If this is something you will be doing on a regular basis after a site install, consider creating your own custom install profile (which will contain the required SQL, or features), or creating your own custom module (e.g. created using features). I imagine having to run this script over CLI is not the most maintainable solution ;)


You should use:

<?php print render($user_profile['account']['pass']); ?>

The password field is only split into 2 in a #process function, and you can't access the separate fields before the element is rendered. To do that you would need to provide a #theme property for the element itself, and write a function/template that returns the desired markup.


I have a query tagged QueryAlterableInterface that I need to add an item to the IN clause

Ok here's what happened. Basically, I had to unset the conditions and then just rewrite all of them. Any better solutions I will accept as the answer but this is how I solved it.

$where =& $query->conditions();

if(empty($where[1])) {
  return;
}

unset($where['1']);
$list = my_custom_function_to_get_groups();

$groups = array();

foreach($list as $group) {
  if(!empty($group->nid)) {
    $groups[] = $group->nid;
  }
}

$query->condition('ga.gid', $groups, 'IN');


Why dont you just add the 100% to views-row-1 and width: 50% to views-row?
I believe that you do it like this:

.views-row {
  width: 50%;
  //other css
}

.views-row-1 {
  width: 100%;
}


Nodes display links to shared document(s)

Create a block views of terms to display the links to term files;
add a filter/contextual filter in the view to show only the files of the terms of the current node;
set the block to show up on node pages (except node edit pages).


<?php
//Create node
    $node = new StdClass();
    $node->type = 'game';
    $node->title = t('@date-@time', array('@date' => format_date($om__result->date, 'short'), '@time' => format_date($om__result->time, 'custom', "h:i A")));

    //Date
    $node->field_date = array(
      0 => array(
        'value' => format_date($om__result->date, 'short'),
      ),
    );

    //Location
    $node->field_location = array(
      0 => array(
        'value' => $om__result->location,
      ),
    );

    //Home team
    $node->field_home = array(
      0 => array(
        'value' => $om__result->home,
      ),
    );

    //Visitor
    $node->field_away = array(
      0 => array(
        'value' => $om__result->visitor,
      ),
    );

    //Division
    $node->field_divsion = array(
      0 => array(
        'value' => $om__result->divisoin,
      ),
    );

    //Program
    $node->field_program = array(
      0 => array(
        'value' => $om__result->program,
      ),
    );

    //Time
    $node->field_time = array(
      0 => array(
        'value' => $om__result->time,
      ),
    );

    //Field
    $node->field_number = array(
      0 => array(
        'value' => $om__result->field_nuber,
      ),
    );

    node_submit($node);
    node_save($node);
    drupal_set_message(t('@node has been created', array('@node' => $node->title)));
?>


Problem trying to create a boolean view filter

Add a boolean value to both content types, should be the same boolean you created. no need to create a different boolean field for each content type.

create a view:

filter for the "Operator -  Is one of" and chose your two content types.
filter for you boolean field wich was added to both content types "Operator - Is one of" and select "yes" or 1 depending on your field yes value.
add what ever fields needed.

I have created two content types "content one" and "content two" and added the boolean field "check me" to both.

here is my view:


you can your page with a GET variable appended in the url, something like

www.mysite.com/node/1?videoId=123

then inside your template you use a GET variable like this

$videoId = $_GET['VideoId'];

then you could do this

<object bla bla ... idmedia=" $videoId "></object>.


How to display a node's last saved date?

The arguments you are passing a format_date() are wrong: The second argument is the format used for the date, not another timestamp.

You should code similar to the following one.

  if ($form_id == 'node_page_edit_form') {
    $node = $form_state->getFormObject()->getEntity();
    $form['field_message2'] = array(
      '#type' => 'item',
      '#title' => t('Changed date'),
      '#weight' => -1,
      '#markup' => format_date($node->getChangedTime(), 'medium'),
    );
  }

Even better, you should use the service Drupal provides for formatting dates.

  if ($form_id == 'node_page_edit_form') {
    $node = $form_state->getFormObject()->getEntity();
    $form['field_message2'] = array(
      '#type' => 'item',
      '#title' => new \Drupal\Core\StringTranslation\TranslatableMarkup('Changed date'),
      '#weight' => -1,
      '#markup' => \Drupal::service('date.formatter')->format($node->getChangedTime(), 'medium'),
    );
  }

Instead of 'medium', you can use the default value, or another one you prefer.


hook_node_update hitting a wall with a loop I created

Thanks to #drupal on IRC, I now only run the code once by creating a static cache:

function commitments_node_update($node) {

    if($node->type == 'commitment') {
        if (!empty($node->field_conditions['und'])) {
            static $cache = array();
            if(array_key_exists($node->nid, $cache)) {
                return;
            }
            $cache[$node->nid] = true;
            $condition_name = array();
            $fc_name = array();
            //Create array of all FC conditions
            foreach ($node->field_conditions['und'] as $key => $value) {
                $fc = entity_load('field_collection_item', array($value['value']));
                foreach($fc as $condition) {
                    $fc_name[] = $condition->field_condition_title['und'][0]['value'];
                }
            }

            //Create array of all selected conditions
            foreach ($node->field_commitment_conditions['und'] as $conditions){
                $tid = $conditions['target_id'];
                $term = taxonomy_term_load($tid);
                $condition_name[$tid] = $term->name;
            }

            $fc_diffs = array_diff($fc_name, $condition_name);
            $condition_diffs = array_diff($condition_name, $fc_name);

            //Remove deselected conditions from FC
            foreach ($fc_diffs as $fc_diff) {
                foreach ($node->field_conditions['und'] as $item) {
                    $fc = entity_load_single('field_collection_item', $item['value']);
                        $fc_name_search = $fc->field_condition_title['und'][0]['value'];
                        if ($fc_diff == $fc_name_search) {
                            $fc->delete();
                        }
                }
            }

            //Add new conditions to FC
            foreach ($condition_diffs as $key => $value) {
                $term = taxonomy_term_load($key);
                $condition = $term->field_condition['und'][0]['value'];
                $condition_name = $term->name;

                $condition_fc = entity_create('field_collection_item', array('field_name' => 'field_conditions'));
                $condition_fc->setHostEntity('node', $node);
                $condition_fc->field_condition_title[LANGUAGE_NONE][0]['value'] = $condition_name;
                $condition_fc->field_condition[LANGUAGE_NONE][0]['value'] = $condition;
                $condition_fc->save();
            }
            unset($cache[$node->nid]);
        }
    }
}


Bit old, but for module version 1, you have to use OwlCarousel 1
https://github.com/InchoonPark/meteor-owl-carousel-1/


How to make a view that only shows content a user has not voted on

An effective solution to this problem can be found in http://drupal.org/node/513088.

As suggested by Cthos, one should first set up a "Relationship" in the view setting ("advanced" settings in Drupal 7), then use this relationship as a regular filter (no need for contextual filter here).The proposed procedure is:

Relationships
    Node: Votes
        "Require this relationship": no
        "Value type": No filtering
        "Vote tag": Normal vote
        "Restrict to current user": yes
Filters
    (Votes) Votes: Value
        "Relationship": use the one from above
        "Operator": "Is empty (NULL)"


How can I undo the changes made by setting a private file system path?

When I set the path to the directory that contained my actual site/s, it placed a .htaccess file restricting access. Being as that folder contained many Drupal sites, all sites seemed broken.

Deleting that .htaccess file in the folder I entered resolved the issue.


If still relevant, you can try out Taxonomy Edge.

It has optimizations for taxonomies in general, and also implements views filter/arguments for taxonomies.


No, there's no such command AFAIK.

Logo path is stored in the variable table along with all theme settings as an array. For example, My Theme will store all its settings, including log_path, in the theme_my_theme_settings.

If you know all the settings for the theme you can use the vset drush command to set your theme settings variable with the right value.

This is an example of a theme settings variable value for a subtheme from Zen theme:

array (
  'toggle_logo' => 1,
  'toggle_name' => 0,
  'toggle_slogan' => 0,
  'toggle_node_user_picture' => 0,
  'toggle_comment_user_picture' => 1,
  'toggle_favicon' => 1,
  'toggle_main_menu' => 0,
  'toggle_secondary_menu' => 0,
  'default_logo' => 1,
  'logo_path' => '',
  'logo_upload' => '',
  'default_favicon' => 0,
  'favicon_path' => 'public://favicon_1.ico',
  'favicon_upload' => '',
  'zen_breadcrumb' => 'yes',
  'zen_breadcrumb_separator' => ' › ',
  'zen_breadcrumb_home' => 1,
  'zen_breadcrumb_trailing' => 0,
  'zen_breadcrumb_title' => 1,
  'zen_skip_link_anchor' => 'main-menu',
  'zen_skip_link_text' => 'Jump to navigation',
  'zen_html5_respond_meta' =>
  array (
    'respond' => 'respond',
    'html5' => 'html5',
    'meta' => 'meta',
  ),
  'zen_rebuild_registry' => 0,
  'zen_wireframes' => 0,
  'favicon_mimetype' => 'image/vnd.microsoft.icon',
)

If you want to use vset with an array see this hint:

php -r "print json_encode(array('drupal', 'simpletest', 'leftandright', 'category'));"  | drush vset --format=json project_dependency_excluded_dependencies -


How to tag content by users and filter the content in a view?

Add entity reference field in Meeting Minutes use entity type user and then tag users from there with you  content of Meeting
now in views
use Contextual filters
add Contextual filters select you user reference field like if your field name is

Content: user in meeting

then select

Provide default value

from check boxes a select list will be appear then select from them

User ID from logged in user

and done
Now when page load content should be filtered with current user id
i think this will solve your problem


How do I display fields in my product type in a product display?

Fields from the referenced product entity are automatically available on the product display node.

Set the fields to visible on the product at

admin/commerce/products/types/subscription-product/display

Then, set the fields to display at:

admin/structure/types/manage/product-display/display

Update: As noted by vintorg below when creating your product reference field on the product display node, ensure "Render fields from the referenced products when viewing this entity." is checked.

That should do it.


Test a settings form that displays a queue

A functional test satisfies both requirements.

<?php

namespace Drupal\Tests\google_analytics_counter\Functional;

use Drupal\Component\Utility\SafeMarkup;
use Drupal\Tests\BrowserTestBase;

/**
 * Tests the google analytics counter settings form.
 *
 * @group statistics
 */
class GoogleAnalyticsCounterSettingsTest extends BrowserTestBase {
  const ADMIN_SETTINGS_PATH = 'admin/config/system/google-analytics-counter';

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['google_analytics_counter'];

  /**
   * A test user with administrative privileges.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $adminUser;

  /**
   * Verifies that the google analytics counter settings page works.
   *
   * @see MediaSourceTest for good example code.
   */
  public function testForm() {
    $admin_user = $this->drupalCreateUser(array(
      'administer site configuration',
      'administer google analytics counter',
    ));
    $this->drupalLogin($admin_user);

    // Create item(s) in the queue.
    $queue_name = 'google_analytics_counter_worker';
    $queue = \Drupal::queue($queue_name);

    for ($i = 1; $i <= 5; $i++) {
      $queue->createItem(['type' => 'fetch', 'index' => 'boogie' . $i]);
    }

    $this->drupalGet(self::ADMIN_SETTINGS_PATH);
    $this->assertResponse(200, 'Access granted to settings page.');

    // Assert Fields.
    $settings_fields = $this->getAdminUserSettingsFields();
    foreach ($settings_fields as $field_name) {
      $this->assertField($field_name, SafeMarkup::format('@field_name field exists.', ['@field_name' => $field_name]));
    }

    // Cron Settings.
    $edit = [
      'cron_interval' => 0,
      'chunk_to_fetch' => 5000,
      'api_dayquota' => 10000,
      'cache_length' => 24,
    ];

    // Enable counter on content view.
    $this->drupalPostForm(self::ADMIN_SETTINGS_PATH, $edit, t('Save configuration'));
    $this->assertRaw('The configuration options have been saved.');
  }

  /**
   * Returns a list containing the admin settings fields.
   */
  protected function getAdminUserSettingsFields() {
    return [
      'cron_interval',
      'chunk_to_fetch',
      'api_dayquota',
      'cache_length',
      'queue_time',
      'start_date',
      'advanced_date_checkbox',
      'fixed_start_date',
      'fixed_end_date',
    ];
  }

}


How to display list of files under a particular directory in Drupal?

I found a module called Filebrowser for this.

  Allows site administrators to expose a particular file system folder and all of its subfolders with a fancy FTP-like interface to site visitors. File metainformation (via descript.ion and files.bss) is supported. The module also allows these metafiles to store special content, which can be parsed with a callback. If no callback is specified in the file, only the description will be fetched.

This is the exact module what I was looking for. Using this module I could display all my exported files. Here is the screen-shot.

Additionally we can Delete the files and also download the selected items as an ZIP archive from here itself.

Hope this post helps someone.


How to list taxonomy terms grouped by a field with Views

A-ha!

Tick the "Force using fields" option under the page style. This turns on the fields bit which you can then use to group by.


replace template with other when conditions are met

You can alter the list of template suggestions in your preprocess hook:

function drop_preprocess(&$variables) {
  $variant = drop_get_variant_for_current_user($variables);
  if ($variant) {
    $suggestions = array();
    foreach ($variables['theme_hook_suggestions'] as $suggestion) {
      $suggestions[] = $suggestion
      $suggestions[] = $suggestion . '--' . $variant;
    }
    $variables['theme_hook_suggestions'] = $suggestions;
  }
}

This will add templates variants for all theme hook. So for instance, this allow you to override the node.tpl.php and page.tpl.php templates with node--special.tpl.php and page--special.tpl.php ones (when drop_get_variant_for_current_user() returns 'special'. If the template for a variant does not exists, it will simply be ignored.

Note that the order of suggestions is preserved. If you have three specialized node templates: node.tpl.php, node--special.tpl.php and node-article.tpl.php (the default one, the 'special' variant and the template for article nodes), when rendering an article node, the 'node-article.tpl.php' will be used since 'node_article' will be after both 'node' and 'node__special' in $variables['theme_hook_suggestions'].

Because it will run for all templates used on the page, the use a static cache in get_variant_for_current_user() so the actual variant won't be computed again and again for the same request/template.

Update:

The exact used template with be the last one in $variables['theme_hook_suggestions'] for which a template file exits. For instance if $variables['theme_hook_suggestions'] == array('node', 'node--special', 'node-article', 'node-article--special'), but only the node.tpl.php, node-article.tpl.php and node--special.tpl.php files exist, then node--special.tpl.php will be used.
The drop_get_variant_template() function is the one where you put your variant selection logic (and that has to be written).


list on node page where node selected on different content types

I assume you are lining the nodes via Entity Reference.

In that case use Views to grab the staff node nid and show the related projects via a relationship. Add it to your staff page via a block, EVA, Display Suite, Panels or some other contrib module (there are a quite a few that can embed a View).

The exact module you choose depends on your requirements, such as what modules you already have installed, and what other features you would like from the module.

You can do it yourself in the template if you wish, but you will have to create an SQL query for that or use views_embed_view to embed the same view referred to above directly into the template as a variable via template_preprocess_node. The problem is that the list of staff is available on the project node but not the other way round. You can solve that by having a two-way reference, by using a module such as Corresponding Entity References, but to me that sounds too convoluted.


View filtering all records with no argument, empty text with invalid argument

All of the methods below will display:

Matching results on foo/bar (valid term name with matches)
Value of "No results found" on foo/norf (valid term name with no matches)
Value of "No results found" on foo/baz (invalid term name) (Page display) or 404 Page Not Found (Block display)**See note below.

The following methods will take different actions if a term is not present; e.g. foo/.

Method 1. Display NO results if term is not present

Contextual filter: Content: Has taxonomy term ID

When the filter value is NOT available .. Provide default value
                                  Type .. Raw value from URL
                        Path component .. 2
                        Use path alias .. checked

                 When the filter value
 IS available or a default is provided .. Specify validation criteria
                             Validator .. Taxonomy term
                          Vocabularies .. (select vocabularies)
                     Filter value type .. Term name converted to term ID
     Transform dashes in URL to spaces
            in term name filter values .. checked

   Action to take if filter value does
                          not validate .. Display contents of "No results found"

Method 2. Display ALL results if term is not present (using PHP filter module)

Note: For this method the core module PHP filter must be enabled.

Contextual filter: Content: Has taxonomy term ID

When the filter value is NOT available .. Provide default value
                                  Type ..  Raw value from URL
                        Path component .. 2
                        Use path alias .. checked

                 When the filter value
 IS available or a default is provided .. PHP code
                     PHP validate code .. (see below)

if ($argument) {
  $vocabulary = 'vocabulary_name'; // The machine name of the  vocabulary.
  $terms = taxonomy_get_term_by_name($argument, $vocabulary);
  if (!empty($terms)) {
    $term = array_shift($terms);
    $handler->argument = $term->tid;
    return TRUE;
  }
  else {
    return FALSE;
  }
}
else {
  $handler->argument = 'all';
  return TRUE;
}

   Action to take if filter value does
                          not validate .. Display contents of "No results found"

Method 3. Display ALL results if term is not present (using Views hook)

Contextual filter: Content: Has taxonomy term ID

When the filter value is NOT available .. Provide default value
                                  Type ..  Raw value from URL
                        Path component .. 2
                        Use path alias .. checked

                 When the filter value
 IS available or a default is provided .. Specify validation criteria
                             Validator .. Taxonomy term
                          Vocabularies .. [select]
                     Filter value type .. Term name converted to Term ID
   Action to take if filter value does
                          not validate .. Display contents of "No results found"

Add this function to a custom module and clear the caches:

function MODULENAME_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'view_name') { // You can optionally also check the display ID.
    if (!empty($args)) {
      $argument = $args[0];
      $vocabulary = 'vocabulary_name'; // The machine name of the  vocabulary.
      $terms = taxonomy_get_term_by_name($argument, $vocabulary);
      if (empty($terms)) {
        $args[0] = FALSE;
      }
    }
    else {
      $args[0] = 'all';
    }
  }
}

Method 4. Display ALL results if term is not present (no coding required!)

On your first block display, use the contextual filter in Method 1, then limit the block visibility*** to 'foo/*'. Create a new block display that outputs all results and limit the block visibility to 'foo'.

**There's an important caveat when using URL arguments with a block display: the URL must be a valid path. In other words, foo/bar must be an actual page or you will get a 404.

*** In the Pages fieldset on the block configuration form (Administration > Structure > Blocks), select "Only the listed pages", then enter the suggested values.


get error field is required when #access is false with field permission  in image field

This fieldpermission bug with image and file cck field.

You can get all element in form_alter and if #access set false remove #require of it

    if ($profile_type == 'profile_main') {
    foreach($form[$profile_type] as $index=>$value) {
          if (preg_match('/^field_/', $index)){
                if ($form[$profile_type][$index]['#access'] == FALSE)
                  $form[$profile_type][$index]['und'][0]['#required']=FALSE;
          }
        }
    }


If this is a custom block, then you can use the Cache API, and set the cache max age to 0, eg

$build = [
 // ...
 '#cache' => [
   'max-age' => 0,
 ],
];

If it is an existing block, then you can alter it to add this into the render array.


At the end I benefited from both @No Sssweat and @Neograph734 answers.

First of all I added (field_tag: Content) Content: Title [nie pokazuj] field. Than I entered Content: Title field marked "modify output value" and get replacement token from there.

At the end I inputed the replacement token in contextual filter menu.

As @Neograph734 mentioned my problem was that the contextual filter did not proper list all available tokens.


This is intended behavior, if user does not have "access site in maintenance mode" permission, then user is logged out.

For Drupal 7 take look on user_menu_site_status_alter

For Drupal 8 take look on Drupal\user\EventSubscriber\MaintenanceModeSubscriber


How to store value of variable if it is changed inside of ajax callback function?

The ajax callback is not for form logic. It's only supposed to send back a new version of $form or part of it in a wrapper. Or in more advanced cases a collection of ajax commands.

Use instead buildForm(). You can check which button was clicked with $form_state->getTriggeringElement().

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

    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

    $i = $form_state->get('elem') ? $form_state->get('elem') : 1;
    $trigger = $form_state->getTriggeringElement();
    if (isset($trigger['#ajax']['callback']) && $trigger['#ajax']['callback'] === '::addMore') {
      $i++;
    }
    $form_state->set('elem', $i);

    $form['counter'] = [
      '#markup' => $form_state->get('elem') ?? 1,
    ];

    $form['btn'] = [
      '#type' => 'button',
      '#value' => 'Btn',
      '#ajax' => [
        'callback' => '::addMore',
        'wrapper' => 'ajax_wrapper',
      ]
    ];

    return $form;
  }

  public function addMore(array &$form, FormStateInterface $form_state){
    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state){

  }


Is it safe to use $vars['name_raw'] instead of $vars['name']?

For this particular instance you should be fine because usernames already are filtered to a limited set of characters.

Like you assumed *_raw is unfiltered input. So in almost any other circumstance, it should be sanitized in some way before use.


Where in the database is the password reset form's expiration date set?

The text for the One time password form is located in user_pass_reset form function in core.

While the user's password reset notification mail may be configured from the admin menu (Administer >> Configuration >> People >> Account Settings) there's no similar Admin UI based configuration of the reset form itself.

Though there doesn't seem to be a module to customize the form itself (based on my search), there do appear to be modules that offer alternative password reset methods that you could look at namely Password Reset and Simple Password Reset.

If you could consider taking a coding way, this could be achieved by using a hook_form_alter or hook_form_FORM_ID_alter

As for the expiration date drupal uses a default of 86400 seconds (24 hours). It would be stored in the variable table in the database with the name user_password_reset_timeout (note that when present the value 86400 would be serialized like all values in that table). If you wish to change this value consider doing it using variable_set through code. The equivalent drush command would appear an easier option though. Do make sure to update the email content on expiry time to avoid any confusion.


How do I overwrite the view output for each vocabulary?

Ok, it seems that I have found a solution. A Drupal 8 & 7 module called "Taxonomy Views Integrator" provides ability to set custom view for each vocabulary and/or terms. So far seems to work fine. Link to module - https://www.drupal.org/project/tvi


absolute url of inline images in body using views and services

This is discussed for a long time, but unfortunately there is no solution committed to core until now, see https://www.drupal.org/node/2630076

Basically this tells you, that you need a text filter like this

http://cgit.drupalcode.org/drupal/tree/core/modules/editor/src/Plugin/Filter/EditorFileReference.php

where you change the line

$node->setAttribute('src', file_url_transform_relative(file_create_url($file->getFileUri())));

to

$node->setAttribute('src', file_create_url($file->getFileUri()));

by removing url_transform_relative().


Edit old revision without changing the current revision

I'm afraid that not even _node_save_revision allows that. Revisions were designed to keep old stuff archived and unchanged. Of course sometimes we need to violate that principle for the sake of moderation.

You will have to smartly adapt piece from above function:

$node->uid = $uid; // Make sure revision's author stays unchanged
drupal_write_record('node_revision', $node, $update);

I don't have time to experiment with it, but I'm sure you will find out pretty easily.

Carefully consider if you want to also call

module_invoke_all('node_presave', $node);
module_invoke_all('entity_presave', $node, 'node');

before save, and

module_invoke_all('node_' . $op, $node);
module_invoke_all('entity_' . $op, $node, 'node');

after save. Probably you don't, but it depends - some modules may use revision data for search or other purposes.

Last but not least: I must admit I have no idea how field_attach_update handles field revisions.


Remove Caption and next/previous arrows from Colorbox for Node

The only way I found to do this was to change my theme css file (I use an Omega >theme so used global.css) and add:

  #cboxPrevious, #cboxNext {
        width:0;
     }

  I initially tried display:none but something is overriding it.

display:none works if you use !important


How do I set up default.settings.php to use it for development, testing and production sites?

Don't use the same settings file like you are suggesting with your pseudocode. Instead, use three different settings files in three different folders, each folder corresponding to the domain name of each of your instances.

As a minimum, generally each environment is going to use a separate database host. Other settings that can differ from environment to environment can include the Apache Solr host, memcached settings, temporary folder and files folder, to name a few. You can place all of those there. When you migrate your database from PROD to TEST to DEV, it will automatically pick up the settings you specified.

Imagine that my site is called myfoobarsite.com. This is how my settings structure would look like:

/htdocs
../sites
..../default
....../default.settings.php
..../dev.myfoobarsite.com (DEV)
....../settings.php
..../qa.myfoobarsite.com (TEST)
....../settings.php
..../myfoobarsite.com (PROD)
....../settings.php

I also generally have two local instances of the site, one with the latest database snapshot from PROD and another where I keep all my changes. This is very useful when working with Features, and it allows you to test your features against the production database (locally) before committing. Here's the modified structure:

/htdocs
../sites
..../default
..../dev.myfoobarsite.com (DEV)
..../qa.myfoobarsite.com (TEST)
..../myfoobarsite.com (PROD)
..../mfbs.local (LOCAL ONE)
....../settings.php
..../mfbs2.local (LOCAL TWO)
....../settings.php

As for your local instances remember to make the appropriate entries in the /etc/hosts file and to modify your Apache host settings.

Just in case, I also placed a snippet from the settings.php for guidance:

<?php
$databases['default']['default'] = array(
    'database' => 'myfoobarsite',
    'username' => 'foo',
    'password' => 'bar',
    'host' => '127.0.0.1',
    'port' => '3306',
    'driver' => 'mysql',
    'prefix' => '',
);

/**
 * Apache Solr settings.
 * Use the acquia_identifier/acquia_key when hosting w/ Acquia.
 * Specify only the apachesolr_path key for your local instance
 * or instances that do not use Acquia.
 */
//$conf["acquia_identifier"] = "ABCD-12345";
//$conf["acquia_key"] = "1234f05ab12345dc1234a1234bbc1c12";
$conf["apachesolr_path"] = "http://localhost:8983/solr";

/**
 * Filesystem settings (MAC OS X, LOCAL)
 */
$conf["file_public_path"] = "sites/default/files";
$conf["file_temporary_path"] = "/Users/amateurbarista/tmp";
$conf["file_private_path"] = "/Users/amateurbarista/Sites/tfk/private";

Finally, if you're hosting with Acquia, you'll need to go to http://myfoobarsite.com/admin/config/system/acquia-agent and click on "clear keys" every time you migrate the database. That will cause Drupal to drop the keys that came w/ the imported database and pick up the ones specified in the settings file.


Where is the parent/child relationship between nodes stored in the database?

The simple answer is, there is none.

Nodes in Drupal does not have a hierarchy, it's other things on top of it that allow you to do that, depending on the use case:

Menu links: You can have menu trees and each points to a node, but the nodes themself don't really about that. Some parts might look like it does, e.g. breadcrumb but that is simply based on the path.

Book module: This allows to create a book (basically a hierarchic structure of nodes), but this only makes sense for specific cases, e.g. structured documentation that has chapters and so on.

References: In many cases, nodes are just connected between each other with reference fields, which you could make look like a hierarchy.

Taxonomy: You can have Terms with a hierarchy and reference those from nodes, but again by default that doesn't give you anything hierarchy-like unless you start to combine with with path aliases or so.

=> Content in Drupal is very different from how most other sites handle it and you can't just convert it 1:1.


Emails not being sent from Acquia dev desktop2, win7

Had the same problem and switched from XMail to Papercut recently:

  Papercut is a simplified SMTP server designed to only receive messages (not to send them on) with a GUI on top of it allowing you to see the messages it receives. It doesn't enforce any restrictions on addresses, it just takes the message and allows you see it.

So, turn off the XMail service and start Papercut. When a mail is sent in Drupal, Papercut acts as the (local) SMTP server and allows you to see the message.


How do you create a colorbox popup on the frontpage of D7?


Change the Mandatory field based on selection in webform

That is an interesting thing to have, but i don't think Webform support such a functionality. However they are some other way to achieve the same result.

Using Webform Conditional module. you can have two sets of  hidden questions, and only one set of question could be visible base on user selected choice.

If user click on phone the first set of question will be display to user where the phone is a mandatory and email optional.

If user click on email the second set of question will be display to user where you can have email as mandatory and phone as optional.

You can ready more about alternative ways here .


Pointing the Views handler for Node Body at another field handler

As the database field you are using is external to the node_revisions table, you should probably declare a relationship, in the same way done from Views for the uid field.

// uid field
$data['node_revisions']['uid'] = array(
  'title' => t('User'),
  'help' => t('Relate a node revision to the user who created the revision.'),
  'relationship' => array(
    'handler' => 'views_handler_relationship',
    'base' => 'users',
    'base field' => 'uid',
    'label' => t('user'),
  ),
);


Can't click link added to header of a block

If I understand the question correctly, this can easily be done using Views alone with a nice tabbed menu:

Create your view page as normal, with the default information provided, except for the url - set that to whatever you want, in my example /tabs
change the Display name under Page details to: Base (just to make things easier to read later on)

Add a Page
Change the Display name to the format type of the default page, presumably 'List View'
set up the format, show, fields, filter, sort, etc. how you want the list view to be displayed - be sure to change the 'For' drop down from All displays to 'This page (override)' - or the changes you make will be set for all the pages, but you want different settings for each page
set Path: tabs/list
set Menu: Default menu tab, Title: View as List, Parent: already exists

Add a Page
Change the Display name to the format type of the second page, presumably 'Thumbnail View'
set up the format, show, fields, filter, sort, etc. how you want the thumbnail view to be displayed - be sure to change the 'For' drop down from All displays to 'This page (override)' - or the changes you make will be set for all the pages, but you want different settings for each page
set Path: tabs/thumbnail
set Menu: menu tab, Title: View as Thumbnails, Menu: Navigation

This should create a tabbed menu at the top of your view for easy navigation by users:


The Advanced forum module might be a good starting point, since Drupal has a modular approach you'll have to use a lot of building blocks (drupal contrib modules) to get to the extended functionality that you desire. There might be some custom code needed. In short: there is no out of the box solution for this nor a short answer to help you build this forum but here is a good start:

Has staff moderation. Volunteer moderators can be assigned.
-> Use Workbench
Private messaging between members.
-> Use Privatemsg
Users can earn or be given “badges” and have a nice leaderboard – we would like to use it to create an "expert" vs "new user" atmosphere for Q&A threads, with new contributors asking more seasoned ones (or staff moderators) for advice
-> Badge/score system might be custom, the overviews you can build with Views
[Advanced] A stub of the most popular discussion(s), i.e. linked title (# of replies) can be pulled into a relevant landing page, using categories or similar to define which forums belong to which landing pages. This is important to bring user generated content into landing pages. An extra bonus would be the feature of over-riding the 'most popular' discussion with another staff featured discussion at landing page level.
-> Probably some custom code with also views to pull the lists
Doesn't require subdomain or iframes to integrate - can reside at something like domain.com/forum/thread or domain.com/landingpage/forum/thread
-> Use PathAuto and again views for the landingpages overviews with dynamic urls
Clean and modern UI out of the box or can be themed, responsive for mobile
-> Omega's example theme Ohm might be a good starting point or you could build a child theme from scratch on omega
Can use Drupal user authentication or replace/supplement it with OpenID or Facebook/Twitter logins
-> Try OpenID connect, Facebook connect, not sure if there is something like this for twitter
Includes spam control, though this isn't a deal breaker.
-> Use Mollom or Honeypot
Comment upvoting
-> Use Vote Up/Down


Enable all languages for multilingual site

No - there is no drush command for this and you would want to do this one by one because you're going to need to upload your specific po translation files from Drupal.org (one reason its not practical to make this an option with the base install for n languages)


Rules does not have any action for publish selected content

You can use drupal's hook_form_alter() for firing your PHP code. Check below example:

function contr_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'node_admin_content'){
    $form['admin']['options']['submit']['#submit'][] = 'CUSTOM_SUBMIT_HANDLER';
  }
}

and then you can write your PHP code in CUSTOM_SUBMIT_HANDLER function as below:

function CUSTOM_SUBMIT_HANDLER($form, $form_state){
  if($form_state['values']['operation'] == 'publish'){
    // Do your stuff when PUBLISH here.
  }elseif ($form_state['values']['operation'] == 'unpublish') {
    // Do your stuff when UNPUBLISH here.
  }
}


How to autofill webform with node field data

Using hook_form_alter() or hook_form_FORM_ID_alter(), you can set the default value by php code

For Example

function HOOK_form_FORM_ID_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){
  if($form_id == 'YOUR_FROM_ID'){
    $form['submitted']['FIELDNAME']['#default_value'] = date("Y-m-d h:i a", time());
  }
}


Webform provides a fieldable form entity type. And when you add a date field to it (you didn't specify what date field exactly, core, contrib, custom), this date field may make use of a datepicker library.

Speaking of core it most likely is core's core/jquery.ui.datepicker library. Which is used for #type => 'date' form elements for example.

When you in your custom script want to make use of this datepicker library you need to add it as a dependency. Same as core does:

drupal.date:
  version: VERSION
  js:
    misc/date.js: {}
  dependencies:
    - core/drupal
    - core/modernizr
    - core/jquery.once
    - core/jquery.ui.datepicker

See https://git.drupalcode.org/project/drupal/blob/8.8.x/core/core.libraries.yml#L142-150.

And maybe you also make your JavaScript look more like in the examples in the docs.


How to Port customField PHP from Drupal 6 Views 2 to Drupal 7 Views 3


How do I use the Commerce Coupon module?

The key to creating the coupon rules are two events: "Validate Coupon," and "Redeem a Coupon."

In this case, you need to create a rule with the "Redeem a coupon" event; in it, you need to add the actions "Create coupon line item," and "Set granted coupon amount" (in that order). The "Set granted coupon amount" action requires a number that is the discount to be applied. You need to calculate this in the rule by finding the percentage of the order total.

This video may help.


Views displays helps you manage your views that are similarly the same.

Basic example is articles:

On your home page, you want a simple block that shows 5 articles, no pager.
At the bottom of this block, you want a link "read all articles".
It redirects you to a page with all the articles, 10 per page, with a pager at the end.

Instead of creating 2 views, which is a waste of time, you'll create one view with 2 displays.

For this example, you will create two views displays, one "Block" and one "Page".
First you create your "Page" display (or "Block", as you want), set it to filter only articles content type, show the title and the date of publication.
Then you can create the other view display, and you only need to override the "Pager" settings.

Tomorrow, if you add an image to your articles, and you want them to appears on both the block and the page, you just need to add the image in the fields, and it will appear on both views display.

Beware that each views display has its own purpose, for example "Feed" will all you to create Rss display, "Page" needs it's own URI, etc.


How to show only child terms of a taxonomy on a table

Solved by joining two tables : taxonomy_term_data and taxonomy_term_hierarchy, the second one contains the field : parent ( 0 for parents, tid of the parent if it's a child term)


How to set one path alias as the canonical alias?

Metatg seems to be your answer:

Currently supported meta tags:

Abstract

Author

Canonical URL

Copyright

Description

Dublin Core (sub-module)

Generator

Image source

Keywords

News Keywords

Open Graph Protocol (sub-module)

Original Source

Publisher URL

Robots

Shortlink URL

Title (e.g. Page titles)

Twitter Cards (sub-module)


Check it out Commerce Field Group Panes module. Using this you can able to add field Delivery Date & Time field to check out process.

  This enables an easy way to collect information in the checkout
  process. For example customer comments, feedback about where the
  customer founds the shop or any other fieldable information.


How to improve Drupal speed when developing in localhost

The best tip you can use (this really change my life) is adding a line in your my.cnf file:

innodb_flush_log_at_trx_commit = 0

You can find this file in your wamp folder or if your on linux server: /etc/mysql/my.cnf

Regards


How to hide the right and left regions from a customized login page?

Go to the Blocks admin page, admin/structure/block.

Find the regions you don't want to show. E.G., 'Sidebar A,' 'Sidebar B.'

'Configure' the blocks which appear in those regions. They will all have a 'Pages' tab at the bottom, and this is where you can configure which pages contain or exclude those blocks. You'd check 'All pages except those listed' and then put the path to your custom page.

HTH.


How do you add a custom search box at code level?

I'm pretty brain-dead. I just set up a custom submit handler for a custom form for search to redirect after form submission to the search results page with the right URL, e.g., passing the query and filter in manually.


Giving a default value to a password element in D7 form API?

You can try to add your default value directly with #attributes option just like that :

$form['password'] = array(
  '#type' => 'password',
  '#title' => t('Password'),
  '#description' => t(''),
  '#attributes' => array('value' => $this->config['password']),
);

After I'm not sure if you will be able to get that value on validate and submitcallback, you should check.


Drupal response time incredibly slow, but only from some end-users

These kind of problems are extremely hard to debug, because it can be one of a million things. My bet is that there's some server misconfiguration.

If I was in your position, here's what I'd try to do:

Try to reproduce the problem reliably - If you can reproduce this 100% of the time, then you know you have some method to reliably recreate the problem that you're facing. Try to identify any recent changes that might have caused this -- has it always been like this, or did you do something recently to cause this?
Isolate the problem - You're most likely running on a LAMP stack. I doubt your OS is a problem, but it's most likely related to the Apache, MySQL or PHP side of things. Double check your php.ini settings, then your mySQL settings, and then your Apache settings.
Debug / Profile - There's a bunch of ways to do this. Try the devel module and performance modules. If you're comfortable writing code and developing modules, try using debug statements to figure it out. If you're more advanced, profile your site using xdebug.

Good luck.

EDIT: I missed the part of about you running on EC2 -- still, the issue still stands. See if you can reproduce it reliably, and jump straight to profiling / debug.


Tablefield output in No Results behaviour

Got the answer!!

<?php
$view = views_get_current_view();
$node = node_load( $view->args[0] );
$table_data = field_get_items('node', $node, 'field_modal_parameters_tabel');
$output = field_view_value('node', $node, 'field_modal_parameters_tabel', $table_data[0]);
print $output['#markup'];
?>


Delete directory from private folder programatically?

Note that glob('*') ignores all hidden files by default. This means it does not return files that start with a dot (e.g. .file).  If you want to match those files too, you can use {,.}*  as the pattern with the GLOB_BRACE flag. This will include the special cases . and .. so you need to exclude those by using {,.}[!.,!..]*.

So in summary, try the following:

$files = glob("$folder/" . '{,.}[!.,!..]*',GLOB_MARK|GLOB_BRACE);

As a sidenote: you mention you tried using rm_dir. I assume you mean rmdir?


How to create a simple form to redirect the user to entered URL?

Have a look at the Rules Forms Support module. Some more details about it (from its project page):

Rules Forms Support provides a Rules based method for controlling forms and their elements. The module can be used to alter any form provided by Drupal core or contributed modules. Change element titles, descriptions, weights, and more, or validate form data and set form errors. Rules forms saves time and cost by affording site builders the ability to monitor and alter forms without the need to implement a custom module.
For help getting started with Rules Forms Support, please see the module documentation.
Features

Activate events for form creation, validation, and submission on a form-by-form basis.
Target individual form elements or the entire form in conditions and actions.
Manipulate the attributes of a form element like title, description, weight, and more.
Validate the values of form elements during form validation.
Set form errors when rule-based validation fails.
Redirect users to a different page upon viewing or submitting a form.
Examine the attributes of elements in active forms with the element inspection tool.

Especially the "Redirect users to a different page upon viewing or submitting a form" should help to address your question.


How to add a contact link next to the 'submitted by' user info?

You certainly shouldn't need to hack core for this. There's a few ways to do this, the simplest way is to customise node.tpl.php. For example if you were using the default node.tpl.php you would copy it to your theme folder, rename it "node--yourcontenttype.tpl.php" and then open it up and find the code:

<?php if ($display_submitted): ?>

    <?php print $submitted; ?>

<?php endif; ?>

You can then add the code to generate your contact link, something like this (untested):

<?php if ($display_submitted): ?>

    <?php print $submitted; ?>
    <a class="user-contact" href="/user/<?php print $uid; ?>/contact">Contact

<?php endif; ?>


Can you paste an example here with the code that didn't work for you?

Did you respect the structure below?

  Enter long URL:

    <input type="text" maxlength="100" size="60" value="http://" name="example_input" id="edit-example-input" class="form-control col-md-10 form-text" tabindex="1">


Is there any ideas on webform mutile values on same field?

There is module for doing this: Try the Multivalue Settings module.

  This module adds some useful settings for fields that can contain multiple values. You can specify:

  Number of values allowed
  Number of values required
  Number of empty widgets to display initially (Drupal usually displays all fields for non-unlimited fields. This allows you to only display a few, followed by the 'Add More' button, which will disappear after the maximum number of fields has been filled.)
  Number of empty widgets to display on edit forms after the field contains some values (Drupal usually displays one extra.)


How do I resolve this installation error?

Had the same problem started from D8.4beta1.

Solved by switching to Drush 9 with:

composer require drush/drush:^9


Drupal Commerce Kickstart 2 Adding Attrubutes to SPECIFIC Products

I think you can use Conditional Fields module which can help you in showing and hiding fields based on any other field value.

You can also watch these tutorials in case you need to understand Drupal Commerce in detail.


Solved!

Adding custom access to the Views is very easy:
Just create own views access plugin by extending Drupal\views\Plugin\views\access\AccessPluginBase class.

Then implement custom access logic in access method and new rule should appear in PAGE SETTINGS > Access popup window.


How to add a javascript function after uploading file

You could just bind something to the jQuery ajax success event on the page where your form is displayed.

You can bind ajaxSuccess to any jQuery object, try something like this if you're experimenting:

<script>
  (function ($) {
    $(function () {
      jQueryObject = $({});
      jQueryObject.ajaxSuccess(function(event, XMLHttpRequest, ajaxOptions) {
        /* do something whenever an ajax call is successful */
      });
    });
  })(jQuery);
</script>


I can't check it right now, but I guess the following should work:

For each content type (its meta tags you want to be indexed), go to "Manage display".
Add the "Search" display.
Add the metatag field to that display.

Assuming that the metatag module uses fields. If not, you'd have to create a dummy field (comment, if you need that explanation).


The Custom Formatters module will help you quickly and elegantly. Here is a quote about it (from the module's project page):

  ... allows users to easily create custom CCK/Field Formatters without the need to write a custom module. Custom Formatters can then be exported as CTools Exportables/Features or Drupal API Formatters.


Can I turn cache off for the development deployment?

Install the devel module which adds a cache clear option for administrators.
You'll find a devel block to add to a region for quick cache clearing, or if you install the admin menu and get a quick menu in the top left for clearing various caches in Drupal.

If you like the command line install drush and use the drush cc all command to clear your sites caches. Beware that currently drush cc doesn't clear the Varnish cache if that's applicable to your setup.


What I normally do for all my themes is to add the missing region region-name class to each region by implementing hook_preproccess_HOOK in MYTHEME.theme.

/**
 * Implements template_preprocess_region().
 */
function MYTHEME_preprocess_region(&$variables) {

  // Add missing region CSS classes.
  $variables['attributes']['class'][] = 'region';

  if (isset($variables['region']) && !empty($variables['region'])) {

    $variables['attributes']['class'][] = 'region-' . str_replace('_', '-', $variables['region']);
  }
}


Why does view display incorrectly when logged out?

Nevermind.

After walking away for an hour or so, coming back and then refreshing the page, everything is working. WTF? Does anyone know if this is a Drupal setting somewhere or is it an artifact of the somewhat locked-down instance of Drupal that I have to work with.

Grumble grumble.


Change layout of a view 'page display' based on number of grouping field occurences

I think what you are trying to drupalize/ise this into is something along the lines of:

function YOURTHEME_preprocess_views_view(&$vars) {

  $view=$vars['view'];

  if (empty($view)) {
    watchdog('YOURTHEME', 'Rut roh Rastro....');
    return;
  }

  switch ($view->name) {

     case 'need':

        if ($view->current_display=='page') {

          $tid_arr = $view->field['term_node_tid']->view->field['term_node_tid']->items;
          $terms = array_keys($tid_arr);
          $number_tids = count($terms);

          if ($number_tids == 1) {
            drupal_add_css(path_to_theme() . '/css/my_custom_css.css');
          }

        }

        break;

     // any other views here

  }

}

with my basic comment being that you switch on the View's name in the preprocess function and do all your work in there instead of going out into another function.


Serve Anonymous Pages when users are logged in for some pages

You may implement ESI block caching.

Have a look at ESI module  and varnish basic tutorial. You would be able then to cache whole pages except the blocks with session data.

Additionally, @Kevin comment points a complementary way: using Redis or Memcache will substantially speed the pages when logged, by caching data and objects in server memory to reduce the number of times the data source must be read.


how to display a link on a node view page?

In your implementation of hook_node_view(), add an element to the $node->content array. The element should be a renderable array as expected by drupal_render().


You could make use of

entity_load('field_collection_item', array($item_id))

This how-do-i-load-a-field-collection-from-a-node post provides multiple solutions for your problem!!


Linking entities using EntityFieldQuery?

Well your approaches sound ok ... an alternative might be the Relation module. You can define a relation such as "event-has-engagement" between any number of entity ids. A "relation" is just given a numerical id typically and then the endpoints go into a table.

The Relation module has already extended the EFQ class to encapsulate querying Relations; eg you can easily query for "Find me all Engagements for Event with some entity id". You can additionally attach drupal Fields to endpoints and query those fields in your EFQ-Relation query object.

I imagine you could loop through your existing database and build the necessary Relation(s) to migrate the data into "Relation" relations.

There are also Views integration with Relation .... but I personally stick with EFQ for alot of stuff.

Just my 2 cents ...

EDIT

there is a patch to allow the use of the migrate module to move Reference fields into Relations.


Can we write javascript code in twig template?

Yes, you can write JS code in a twig template. I can't think of any syntax crossovers so you should be able to literally write it as-is.

Indeed this works fine in html.twig.html:

<script>
  (function(val) {
    console.log(val);
  })('test');
</script>

If you're having syntax trouble, you can always escape it with raw, but it should be unnecessary:

{% raw %}
<script>
  (function(val) {
    console.log(val);
  })('test');
</script>
{% endraw %}


How to load conditionally a script depending on whether element exists in DOM?

drupal_add_js() happens server-side, it can't possibly have exposure to what's in the DOM (unless you pass that info back to the server with AJAX, but that would be a very weird thing to do). The correct solution is the javascript one as you've mentioned.

You want that code to run whenever the DOM is ready, so in the Drupal paradigm immediately inside the attach function of your behaviour:

(function ($) {
  Drupal.behaviors.leftMenuSticky = {
      attach: function (context, settings) {
        if ($(".full-height").length > 0 ) {
          var contentHeight = $("#main").innerHeight();
          // ...


go to yousite/sites/default and open the settings.php file and find $base_url and change it to the new value (somewhere around line 270).

NOTE : settings.php is a read-only file, you need to clear the read-only flag first to make the changes. You'll need to restart the server to update the changes.


How do I create an AJAX filter for a view?

Edit the view, and add a filter to the page:

Drupal 6: Third column, section is called Filters
Drupal 7: First column, section is called Filter Criteria

When you configure the filter, you want to expose it:

Drupal 6: Click the Expose button in the top right of the configure area
Drupal 7: Check Expose this filter to visitors, to allow them to change it

Enable AJAX:

Drupal 6: Use AJAX is under Basic settings in the first column
Drupal 7: Use AJAX is under Advanced → Other in the third column

When the view is saved, there will now be a form that'll allow users to filter the view dynamically via AJAX.


How deal with taxonomy term parameter in multilingue site?

You must edit your route to be like this, /myroute/{alias}.

Then you can load the term in your controller like this:

public function index($alias) {
  // Find the term by path alias.
  $path = \Drupal::service('path_alias.manager')->getPathByAlias($alias);
  if (preg_match('/taxonomy\/term\/(\d+)/', $path, $matches)) {
    $term = $this->entityTypeManager->getStorage('taxonomy_term')->load($matches[1]);
  }
  if (isset($term) && $term instanceof TermInterface) {
    $term_id = $term->id();
  }
}

NB: The path_alias.manager service is added in Drupal 8.8.x, if you use an older version you must use the path.alias_manager service instead.


How do I give access to only specific roles to buy at my store?

Solution

After a few nights of sleeping on it I believe I have a solution. I tested it and so far it works. But please let me know if you experience any issues with my solution below.

Step 1

a) Install Roles For Menu module (has a stable releases for this project are covered by the security advisory policy.)

b) Install the Path Access module together with the Chain Menu Access API (which is needed to install the Path Access module)

Step 2

a) Go to your menu links in the user menu admin/structure/menu/manage/user-menu (or wherever your 'my cart' link is located) and set the required roles to show and hide for that menu item.

b) Go to admin/config/people/pathaccess and add the paths that you wish to deny access to per role.

Now the roles who don't have access to any of these paths get an access denied page and those who do have access will just be able to use the store as intended.


Remove Home from menu at module installation

Following the suggestion from @Leigh Mason and copying almost verbatim from the link he posted, I ended up implementing hook_install():

function hook_install() {
  $menu_link_manager = \Drupal::service('plugin.manager.menu.link') ;
  $front_page_link = $menu_link_manager->getDefinition('standard.front_page') ;
  $front_page_link['enabled'] = 0 ;
  $menu_link_manager->updateDefinition($menu_id, $front_page_link) ;
  $cache = \Drupal::cache('menu') ;
  $cache->deleteAll() ;
}

and the link was successfully deleted. I think that the last two lines are not really needed, I will check it at the next build from scratch...


Move Drupal to subdirectory - clean urls

Perhaps setting the $base_url variable in the settings.php will help Drupal generate the correct urls.

/**
     * Base URL (optional).
     *
     * If Drupal is generating incorrect URLs on your site, which could
     * be in HTML headers (links to CSS and JS files) or visible links on pages
     * (such as in menus), uncomment the Base URL statement below (remove the
     * leading hash sign) and fill in the absolute URL to your Drupal installation.
     *
     * You might also want to force users to use a given domain.
     * See the .htaccess file for more information.
     *
     * Examples:
     *   $base_url = 'http://www.example.com';
     *   $base_url = 'http://www.example.com:8888';
     *   $base_url = 'http://www.example.com/drupal';
     *   $base_url = 'https://www.example.com:8888/drupal';
     *
     * It is not allowed to have a trailing slash; Drupal will add it
     * for you.
     */
    # $base_url = 'http://www.example.com';  // NO trailing slash!


Move Acquia dev destop sites to another local enviroment

(Just saw your comment that you are not using Acquia Cloud so I'm editing my answer.)

Copy the current location of your local sites to your new computer.
Download the latest version of Dev Desktop.
Click on the plus sign at the lower left side of the Acquia Dev Desktop window and select Import local drupal site. In the following dialog, select Change... in the top right corner and select the root folder of your site.

FWIW: The default location of dev-desktop sites is:

  ~/Sites/devdesktop/(site root folder)

You may want to keep this convention for convenience/clarity's sake

I seem to remember having to import my sites individually after upgrading my Acquia Dev Desktop. As you can see from the above, it's really easy.


What you got can do what you want, but it requires configuration and without a UI it's quite hard.

You might want to try adding the file browser module, which uses Dropszonejs to create a nice file browser widget. I have tested it out and it seemed to work just fine, but it wasn't quite mature enough for what we wanted to do at the time.


Send email notification when a new comment is posted

Updated Answer

Whilst testing this on a fresh install of Drupal 8 with Rules (Alpha 2) I have come across a bug which is preventing a successful test of this, whilst the data selector below is correct I am presently unable to reproduce a working rule.

The bug report is here: https://www.drupal.org/node/2770291 - To summarise this issue Rules is expecting the TO: parameter to be an array and will throw an error when passing the email address token below which returns a string.

My initial answer holds true for Drupal 7 however for Drupal 8 the situation seems simpler and hinges on a single fact that isn't yet well-documented.

In D7 we're familiar with a syntax resembling: comment:node:author:mail

In D8 the same selector (which works) is: comment.entity_id.entity.uid.entity.mail.value

Hopes this helps, I'm leaving the previous answer below in case it helps someone else.

Previous Answer

*In general with Rules to use the value of a field the rule must first specifically check for the existence of the field (i.e. that the field has a value in the context the rule is running).
If you haven't tried this already you might want to try adding an "Entity has field" condition to the rule to check for the existence of the email address. This should then expose the token for the field.

I've had similar issues executing rules using entity relations (which is more or less what you're doing by referencing the author from the node) checking for the existence of the field (in your case most likely a check that the entity has an author (this should open up access to the user object) then a check against the user object to ensure it has an email address) opened up the available field tokens from the referenced entity.*


You could call Replicate's  replicate_entity_by_id($entity_type, $id) method. And maybe hook it's API for custom behavior, see here.

entity_ui_clone_entity won't create the new entity, but only prepare your entity for creation, and could be used like this:

$my_clone = entity_ui_clone_entity('your_bundle', $my_entity);
entity_save('your_bundle', $my_clone);

Or if you created a method for saving your entity, use it direclty:

my_entity_save($my_clone);


Creating complex tables in views in Drupal 7

The Views UI supports this.

Once you have your View configured, click on the "Settings" link in the Format section. You will then see a table that allow you to choose which column each field should appear in. See screenshot below. In this example, if you wanted the Author uid and Nid fields to appear in the same column, you would just select Author uid from the select list next to Nid (or vice versa).


How do I load a field collection from a node?

Doh! I should have looked in the field collection module:

entity_load('field_collection_item', array($item_id))


How to create a new properties to $node (or $user and so on)

In conjunction with the Entity API module, you can use

hook_entity_property_info

  Allow modules to define metadata about entity properties.

  Modules providing properties for any entities defined in
  hook_entity_info() can implement this hook to provide metadata about
  this properties.

e.g:

/**
 * Implements hook_entity_property_info
 */
function MODULE_entity_property_info() {
  $info = array();
  $properties = &$info['node']['properties'];

  $properties['nid'] = array(
    'label' => t("Content ID"),
    'type' => 'integer',
    'description' => t("The unique content ID."),
  );
  return $info;
}

See also entity_metadata_node_entity_property_info for default node property definitions.


If there is a node for each company, you can insert an alias when the node is saved.  Set up the alias created for each company to start with '/company/{company_name}', then when the alias is inserted, you can add a secondary alias for login:

/**
 * Implements hook__path_insert().
 */
function mymodule_path_insert($path) {
  if (preg_match('/company\/(.*)/', '/company/xyz', $matches) && preg_match('/node\/(\d+)$/', $path['source'])) {
  $company_name = $matches[1];
    \Drupal::service('path.alias_storage')->save("/u/$company_name/login", "$company_name/login" $path['langcode']);
  }
}

This way, the visible path will be /{company_name}/login, but the machine name as far as Drupal is concerned with be /u/{company_name}/login.

You could instead do this on entity_insert and entity_update.


Updating node field value using custom module validation

I worked out that I was using

   $form['actions']['submit']['#submit'][] = 'sitefuncs_custom_submit';

When it should have been

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

Then all my data saved using

$form_state['values']['field_stage_complete_text']['und'][0]['value']['#value'] = 'No'; // set value to No


What security issues are involved with cross-domain logons using OpenID?

As far as I'm aware OpenID is reasonably secure. The downside to OpenID is that it's fairly complicated for non-technical users to understand. Something like this might make that a little easier on your users. There are options to make your site the OpenID provider, but they don't seem ready for production sites yet from a brief skim through the issues.

Another option might be OAuth. This would let your users log in with their accounts from sites like Facebook, Twitter and LinkedIn.

If all 3 sites are Drupal sites, one final solution might be to share the users between the sites, by sharing certain database tables. This would allow you to share other information about your users between the site profiles as well.

This page on Drupal.org describes the details, as well the downsides. Main one being that upgrades to major Drupal updates aren't supported. I honestly wouldn't recommend this unless you know a great deal about how the database side of Drupal works.


Is it possible to show a view's page in the admin overlay?

It may be a bit late and unfortunately I can not assist with your php script but you can try the Overlay Paths module which can achieve something similar to what you are trying to do.

It kind of did what I needed and I say kind of because it does not work that well with Views.


In case anyone else will look for this later, I was able to display the views field value with the following.
{{ view.field.field_calendly_url.original_value }}


How To add Comments to Profile 2 with five star rating on parent node

Mentioned by Marcus,

  You should create an entityreference field from the profile2

Please let me add a picture to explain this sentence in detail,

Using hook_profile2_presave instead of using Rules

Make a node with Fivestar
Add Nid into profile 2

function mymodule_profile2_presave($profile) {
  // is_new is important becase we will add fivestar into mint profile2
  if ($profile->is_new && ($profile->type == 'main')) {
    global $user;
      // Make node for Fivestar and comments
      $node = new stdClass;
      $node->type = 'profile_rate';
      $node->title = 'Rating for the profile';
      node_object_prepare($node);
      $node->language = LANGUAGE_NONE;
      //TODO: Who should be the owner?
      $node->uid = $user->uid;
     // No promote to front
      // Published node
      $node->status = 1;
      $node->promote = 0;
      //  Comments open
      $node->comment = 2;
      // Try to save node
      $node = node_submit($node);
      node_save($node);
      // Save Fivestar NID into profile 2
      $profile->field_article_ref[LANGUAGE_NONE][0] = array('target_id' => $node->nid);
  }
}


What to use for node_prepare in Drupal 7

You don't need to replace it with anything as it happens, you can just remove it.

All that function does is prepare the node body for display. Since the body is a field in Drupal 7, all that processing is done elsewhere, and it's not something you need to invoke manually any more.


how to render a field "view mode" inside a field collection item template file?

I haven't tested this but I suspect your issue arises from the fact that the $node object is not available to that template file. You have a couple of options; write your own theme function, load the node object some other way (this might still not work though because of the way field collection works) or just trim the rendered value.

Something like this should work for you if you are just looking to trim the result to 30 characters:

<?php print trim(substr(render($content['field_myfieldname']), 0, 30)); ?>


How to sort taxonomy facets alphabetically in views?

For those who drop by here check this issue here

  Just make sure to have "Display value" at top and checked, put the
  order as "Ascending" and you are good to go!


Controller is loading twice after search form is submitted

It's unclear how both pieces of code are connected with each other.
If you are handling the form values in form submit you need to pass the resulting parameters to the controller:
public function submitForm(array &$form, FormStateInterface $form_state) {
  // prepare $params
  $form_state->setRedirect('route_to_controller', [], ['query' => $params]);
}

If you are pointing the form action to the controller
$form['#action'] = Url::fromRoute('route_to_controller')->toString();
$form['#method'] = 'get';

then there is no form submit and you have to process the submitted values in the controller.


entityCondition check if a field is not empty

You can do this by

$query->condition('field', '', '<>');

See: https://api.drupal.org/api/drupal/includes%21database%21select.inc/function/SelectQuery%3A%3Acondition/7.x

If this doesn't answer your question you need to. Be more specific.


How do I migrate content to a field added with UI to an existing custom content entity?

In fact, it was easier than I thought. I just had to add the field to the Person migration file:

id: migration_persons_with_sel
migration_tags: null
migration_group: null
label: 'Person migration from CSV'
source:
  plugin: csv
  path: /Users/efalzon/Sites/JdP8M7b/config/migration_Persons.csv
  delimiter: ;
  enclosure: '"'
  header_row_count: 1
  keys:
    - id
process:
  id: id
  lastname: lastname
  firstname: firstname
  cellphone: cellphone
  email: mail
  iscontact: iscontact
  isactive: isactive
  member_id: member_id
  user_id: user_id
  field_sel_initial_credit: credit <----------
  owner_id:
    plugin: default_value
    default_value: 1
destination:
  plugin: 'entity:person'
migration_dependencies:
  required: {  }
  optional: {  }


In Drupal 8 how can I print the page title within a paragraph.html.twig

An alternative strategy to setting cache context is to use a placeholder. This is a more complex approach but you will never have issues with the database cache table filling up - as 4k4 points out this can be a real problem.

All of this code goes in themename.theme.

First we must define a callback function that returns the page title to the placeholder:

function _MyTheme_paragraphs_title_placeholder($page_title) {
  // Must go here, if you attempt to pass in $page_title from preprocess it will
  // be cached!
  $request = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $page_title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());

  $title_array = array(
    '#theme' => 'page_title',
    '#title' => $page_title,
  );

  return $title_array;
}

Next we create the placeholder in preprocess, we will print a variable in the template, so we must populate it with the placeholder:

function MyTheme_preprocess_paragraph(&$variables) {
  // Note: the first item in the #lazy_builder array is our callback.
  $placeholder_title = array(
    '#lazy_builder' => ['_MyTheme_paragraphs_title_placeholder', ['page_title']],
    '#create_placeholder' => TRUE,
  );

  $variables['title'] = $placeholder_title;
}

Finally create copy the paragraphs template and use the title variable:

<div{{ attributes.addClass(classes) }}>
  {{ title }}
  {{ content }}
</div>

This is how I have implemented the breadcrumb title feature in Adaptivetheme (D8 version), to avoid cache context url as I noticed the database entries, I think it's a great method and I'd love more feedback if I have done something wrong - I'm a themer of course, not a hardcore dev :)


Use 'Search Api Attachments' file extractor in my own custom 'Search Api' processor plugin

I was able to use the search api attachments file extractor by extending it.

The FilesExtractor class itself was a processor plugin. So I was able to access all the functionality by using

class BodyFieldAttachments extends
\Drupal\search_api_attachments\Plugin\search_api\processor\FilesExtractor

instead of

class BodyFieldAttachments extends ProcessorPluginBase

Then I could just override the specific functions that need to be overwritten while having access to all the functionality the search api attachment plugin had.


Show block on specific views search result

If you have the PHP filter (not advised but still popular) module enabled you can use the Pages on which this PHP code returns TRUE (experts only) option for block visibility with the following code.

<?php return (isset($_GET['tid']) && $_GET['tid'] == 5971); ?>


You can change the value using a field template.

Add the date field to your view
Look in Advanced -> OTHER -> Theme: Information for a suitable file name for a field template that will only affect the field in this specific view.  They are listed in order from least specific to most specific so the final one in the list for that field is probably the best one to use.  The link on the filename will show you the default contents for such a file.
Create a file in your theme where you keep template files with that filename
Start with the default contents in that file and refresh your cache
Install devel module and use dpm($output) in your new template file to see the structure of the output
Use PHP to edit the appropriate portion of the output, you may need strtotime() and date_add() to achieve this.

Clear your cache often.  If you haven't already got drush installed, do it, it is a very useful tool.


You need to enable the List module, which also gives you the List, List (numeric) and List (text) field types.


Let anonymous view dpm() when using Omega subtheme

Give them Access developer information permission at admin/people/permissions.

Note that this opens a huge security risk so make sure you revoke it when you are done with debugging.


display view mode on node based on field setting or taxonomy term of user profile

Not entirely sure if i understood your question, but I believe the Entity view modes module might help you to define custom view modes for entities, which in your case could be a taxonomy term field in your node type or user profile.

  The Drupal 7 successor to Build modes which will allow administrators to define custom view modes for entities. Custom entities are added to the entity registry via hook_entity_info_alter() so they are available to any code that uses entity_get_info() to provide a list of view modes for an entity. This includes node and user reference fields, Views, etc.


Help with db_delete using both LIKE and IN.. I'm trying to delete many rows whilst having a wildcard

You can't combine LIKE and IN in the way you are attempting.

You will need a run a different query for each UID.

E.g.

$cid_base_pattern = db_like($module) . ':' . db_like($block) . ':' . db_like($theme) . ':%:u.';

foreach ($uids as $uid) {
    db_delete('cache_block')
      ->condition('cid', $cid_base_pattern . $uid, 'LIKE')
      ->execute();
}


New line item every time an item is added (avoid grouping)

You can just toggle the setting on your Add to Cart form display formatter to turn off combining like items in the cart.


How to hide empty fieldset, but leave prefix and suffix in place?

The easiest way would be to wrap the fieldset itself in another element.

$fieldset_wrapper = array(
  '#prefix' => '
',
  '#suffix' => '
',
);

$fieldset_wrapper['fieldset'] = array(
  '#type' => 'fieldset',
  '#access' => FALSE,
);

As you might expect, setting #access to false will prevent an element from being rendered at all.


It is in the default comment module , and editing the core options is not a good practice at all.

You can alter the comment  form in your active theme template.php or hook_form_alter() function in your custom module

<?php
function THEMENAME_form_comment_form_alter(&$form, &$form_state) {
        //dpm($form); //shows original $form array
        //$form['author']['#type'] = 'fieldset';
       // $form['author']['#title'] = 'Your Information';
       // $form['author']['#collapsible'] = FALSE;
      //  $form['your_comment'] = array( '#type' => 'fieldset', '#title' => t('Your Comment'), '#collapsible' => FALSE, '#weight' => 2, );
        //Subject
       // $form['your_comment']['subject'] = $form['subject'];
       // unset($form['subject']);
     //   $form['your_comment']['subject']['#weight'] = -10;
        //Comment
        $form['your_comment']['comment_body']['#prefix'] = "
User picture
" ;
        $form['your_comment']['comment_body'] = $form['comment_body'];

}
?>

You can add user picture using prefix/suffix in the comment form.
Try if it work for you.


Attaching the comment form programmatically

comment_form() is expecting the parameter to be an object rather than an array so you should be doing something like this:

$comment = new stdClass;
$comment->nid = $row->nid;
$form = drupal_get_form('comment_form', $comment);

Note the lack of a 3rd parameter passed to drupal_get_form(), comment_form() only accepts the comment as a parameter, if you want to add a title you'll have to print that separately.

Finally drupal_get_form() returns a render array rather than a string so you need to pass it through the render() function:

print render($form);

The extra errors you're getting are just side-effects of passing an array rather than an object to the comment_form() function


add text before block is being displayed in region content

Assign this css code to one class of your block ( or the #id )

.your-block-class-name:before {
  content: "";
  display: table;
}


how to attach existing images(image field) to node in drupal 7?

can u provide me an example of how to upload image programmatically
  provided I have an image url on the public path in D7

This should do the trick

$node  = node_load($nid);
$image = file_get_contents('public://images/folder_name/image_name.jpg');
$file  = file_save_data($image, 'public://images/folder_name/image_name.jpg', FILE_EXISTS_REPLACE);
$node->field_image[LANGUAGE_NONE][0]['fid'] = $file->fid;
node_save($node);


using profile2 login information as billing information in commerce

You're better to use Commerce Customer Profiles for that information.

Although "billing" is the default, you can add other groups of profile fields as types, e.g "Profile information" etc...

There's a module commerce_customer_profile_type_ui that helps creating new profile types, else you can do it in code via the API.


Can't loop through $form_state->setErrorByName?

I think you simply need to replace:

$form_state->setErrorByName($key, $this->t('cannot be empty.'));

with

$form_state->setErrorByName($key, $this->t('<b>%key</b> cannot be empty.', ['%key' => $key]));

According to the docs, the first parameter will identify the field and the second will be the message to output.

In your code, the $message string is outputed as expected, you need to prefix it with the $key parameter, the same way you do with drupal_set_message.


Display comments from other nodes with a reference

Well, I couldn't get this to work with views, so I wrote a custom module with an sql query. Not very clean, but it does the trick.


Wyswig editor not showing to authors in Full HTML mode for Authors

The issue is resolved as it is js error.
I fixed this issue from this solution(https://drupal.org/comment/6313896#comment-6313896).

As i am using wyswig 7.x-2.1 but the above fix is given for 7.x-2.0 which is applied clearly for my version too.
The below fig. shows that the js error.


8 - How can I detect when an entity is being autocreated?

You need a custom EntityReferenceSelection handler plugin. An example would be how the node module sets the autocreated entity to published:

Drupal\node\Plugin\EntityReferenceSelection\NodeSelection:

  public function createNewEntity($entity_type_id, $bundle, $label, $uid) {
    $node = parent::createNewEntity($entity_type_id, $bundle, $label, $uid);

    // In order to create a referenceable node, it needs to published.
    /** @var \Drupal\node\NodeInterface $node */
    $node->setPublished(TRUE);

    return $node;

You find more information in the plugin annotation class https://cgit.drupalcode.org/drupal/tree/core/lib/Drupal/Core/Entity/Annotation/EntityReferenceSelection.php


Finally worked it out again
Look for navigations.css
Edit it and look for menu-toggle
change it from display: none; to visibility: hidden; !important;
now it gone
I will update question with screenshots so others can see the problem better and know what this solution does


In case of use d6, you can use Flexifield, then after you install you should create a content type that should represent your subfields, and in your main content type you should create a new field, with Flexifield type, and then, define the it's a number of values of the field, and then, in the creation node form of your main content type, you`ll have a field (kind of group), that will have multiple subfields, and depending of the number of fields defined, you should have multiple "groups of subfields".


Entity Metadata Wrapper ->set saving data in incorrect language

Test the following described here:

$ewrapper = entity_metadata_wrapper('node', $entity, [
  'langcode' => 'en',
]);

instead of

$ewrapper->language('en');


How to implement Likert Scale with EntityForm?

[...] you can make form elements that don't have directly corresponding elements in the FAPI. The "grid" component is a good example of this, and in this case, I think it's exactly what you're wanting. You can effectively create a likert scale by creating "options" along the top with these keys:

-2|Strongly disagree
-1|Disagree
0|Neutral
1|Agree
2|Strongly agree

Source: https://www.drupal.org/node/291658


The error is in the following line:

$query = db_select('EMPLOYEES', 't1',array('target' => 'import_employee'));

It is selecting import_employee as target, and default as key, but in your settings.php file you have a default target with a import_employee key. Failing to find the definition for the target you select, Drupal fallbacks to using default as target and (without being instructed differently), to use default also as key.

You can do one of the following:

Edit your settings.php file so that it contains information about the import_employee target and its default key. Keep in mind that the information about the database is given as $database['<target>']['<key>'], not $database['<key>']['<target>'].
Change your code to always call db_set_active() before your query.


Is there a hook I can use to alter the way comments are rendered?

You can use hook_comment_view():

  The comment is being viewed. This hook can be used to add additional data to the comment before theming.

e.g.

function hook_comment_view($comment, $view_mode, $langcode) {
  // how old is the comment
  $comment->time_ago = time() - $comment->changed;
}

Or use a standard theme preprocess hook

function MYTHEME_preprocess_comment(&$vars) {
  // Make changes to $vars that will be available in comment.tpl.php
}

You can also override the standard comment.tpl.php file in your theme to have full control over the markup.


Assuming you're working in Drupal 6:

/**
 * Implementation of hook_comment().
 */
function mymodule_comment(&$a1, $op) {
  switch ($op) {
    case 'validate':
      $subject = $a1['subject'];
      $comment = $a1['comment'];
      // validate here
      break;
  }
}

In Drupal 7 hook_comment() is gone, being replaced by a set of hooks hook_comment_view(), hook_comment_load(), etc. Unfortunately there is no hook_comment_validate() but see this answer for a solution.


Drupal commerce - purchase a product at registration

Figured this out - apparently you have to add the action, "save entity" after you create it, and also force it to save immediately.


How can i make my solr search case sensitive?

Original answer from: https://stackoverflow.com/questions/10205688/how-to-make-field-search-not-case-sensitive-in-solr-using-solrnet

You could use a copyfield that converts the field in question to lowercase.

Similar problem/solution: https://stackoverflow.com/questions/2053214/how-to-create-a-case-insensitive-copy-of-a-string-field-in-solr


How to access image style url from jQuery code?

For a single image style, I tack it on as a data attribute to the image.  Then in my JS, I use that.

This is how I handle retina images, using src switching (edited to just show the relevant portions):

function MYTHEME_image_style($variables) {
  // ...

  if (in_array($variables['style_name'] . '_2x', array_keys(image_styles())) {
    $variables['data-retina'] = image_style_url($variables['style_name'] . '_2x', $path);
  }

  return theme('image', $variables);
}

/**
 * Implements theme_image().
 */
function MYTHEME_image($variables) {
  // ...

  if (isset($variables['data-retina'])) {
    $attributes['data-retina'] = file_create_url($variables['data-retina']);
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}

This in the JS (again, lifted and edited):

$('img').each(function (i, img) {
  var $img = $(img);

  if ($img.data('retina')) {
    $img.data('src', img.src);
    img.src = $img.data('retina');
  }
});

The key is to generate the style URL on the server side, so that the URL includes the itok and that all hooks get fired to allow modules like CDN to work.  You just need to figure out the proper place to do it from.  In your case, I suspect you may need to do it from a theme_field.


Access denied when user tries to edit his Content Profile

Edit the node as an administrator
On the node edit form, under "Authoring Information" set the author to the content profile user
Save content profile node with updated author information.


devel module use anonymous user as author in generate content?

Answer for you question is Yes it do,and you can resolve your problem  with following solutions:

The First solution is

Install the views, views_bulk_operations, and admin_views modules.
Go to the content listing (admin/content).
Filter the results to get the nodes you are interested in.
Check the checkboxes next to the node (there is also an option to select all).
Select "Change author" from the operations dropdown and click the "Execute" button.
Select the user you want to change the author to and click the "Next" button.

Admin views uses views bulk operations to override the default drupal administration views with something a lot more useful.

And also another solution is using bulk author update module


As JSONlog project page states:

  Logs watchdog events JSON-formatted to log files. Provides a Logstash/ElasticSearch-ready log source.

The module only does one thing: turn Drupal watchdog events into JSON-loggable files and writes them to whatever server dir you've configured for it.

Before using this module you will need to:

Setup ElasticSearch & Kibana. This is a separate task from setting up LogStash. It will depend on your service provider (this is off-topic for Drupal Answers).
Setup LogStash. This will vary based on whatever app server you're running Drupal on. You'll have to find instructions applicable to the app server running Drupal.


How can I remove the header n the node/add/[content_type] pages

This may not be a good solution but it works. Put the below code in template.php preprocess_page in your admin theme.

if(arg(0) == 'admin' && arg(1) == 'numbers') {
      $vars['title'] = "";
}

Where number is the node type.


render field collection with already defined custom formatter

So it turns out that the field collection 'field' will be treated like a normal field and rendered properly.  You don't need to load the field with entity_load. (We don't need any of the fields in the collection, we just want the entire collection).  And using field_view_field you can choose your custom formatter:

  //get the nid of the node that contains the field collection from any number of methods
  $node = node_load($nid);
  // the custom formatter was already defined using hook_field_formatter_info() and
  // hook_field_formater_view() (see drupal docs)
  $display = array('type' => 'custom_formatter_name');
  //print or 'return' depending if this is a module or a template file
  print drupal_render(field_view_field('node', $node, 'field_name', $display));

The two hurdles for me were (1) finding out that you can add the custom formatter to field_view_field() and (2) that I needed to print out this info (not return) as I was in a template file, not a function of a module (doh!).


After a while doing the following worked, I do not know why it did not work from the beginning :

return theme('chart', array(
              'chart' => $chart,
              )).theme('chart', array(
              'chart' => $chart,
              ));


I managed to reduce the memory exhaustion with remedying the last edit's errors in the following matter:

I added a not empty check for the "groups" index in the array around the foreach function on the 91-st line of code in DrupalConfigHelper.php

static public function addFieldsFromSchema(&$form, $schema, ConfigInterface $config, $parents = []) {
// Add the specified groups.
// Temp fix for "Undefined index: groups..."
if(isset($schema['groups']) && !empty($schema['groups'])){
  foreach ($schema['groups'] as $group_key => $item) {
    // If the group is just called 'default' then use the key from the plugin as the group key.
    // @TODO: make this less ugly.
    if ($group_key == 'default' && $parents) {
      $group_key = end($parents);
    }
    if (!isset($form[$group_key])) {
      $form[$group_key] = [
        '#type' => 'fieldset',
        '#title' => $item['title'],
        '#tree' => FALSE,
      ];
    }
  }
}

And fixed the "undefined index #description" error on line 116 by checking if the "#description" index exists, and if not create it with empty value to be processed on the initial 116 line.

switch ($item['type']) {
    case 'text':
      $form_item['#type'] = 'textfield';
      if (!empty($item['multiple'])) {
        $form_item['#type'] = 'textarea';
        // Temp fix for "Undefined index #description..."
        if (!isset($form_item['##description'])) {
          $form_item['##description'] = '';
        }
        $form_item['#description'] .= ' ' . t('Add one item per line.');
        $form_item['#element_validate'] = ['BackupMigrate\Drupal\Config\DrupalConfigHelper::validateMultiText'];
        $value  = implode("\n", $value);
      }
      if (!empty($item['multiline'])) {
        $form_item['#type'] = 'textarea';
      }
...

Now backup works nicely.


I have tried to regenerate the issue you have specified 'Welcome email body not changing to reflect account settings' in D7. Although, particular use case has not been specified, I have tried all the three scinarios releted to 'Welcome email' here 'admin/config/people/accounts' :

Welcome (new user created by administrator)
Welcome (awaiting approval)
Welcome (no approval required)

Also, 'Account activation' for 'Welcome (awaiting approval)' use case.

but could not regenerate the issue. At the most it can be that you have made changes in one scinario & tried to check in another.

Hope it helps.