Move fields into fieldset with field_collection module doesn't work

I found the solution. It seems values from fields inside the field_collections are not managed as other Drupal form values.

This is the code to achieve the result:

function mymodule_form_testtype_node_form_alter(&$form, &$form_state, $form_id) {
    $form['field_test_collection']['und'][0]['surround_fieldset'] = array(
        '#type' => 'fieldset',
        '#title' => t('Sorround fieldset'),
    );
    $form['field_test_collection']['und'][0]['surround_fieldset']['field_collection_first'] = $form['field_test_collection']['und'][0]['field_collection_first'];
    unset($form['field_test_collection']['und'][0]['field_collection_first']);
    $form['field_test_collection']['und'][0]['surround_fieldset']['field_collection_second'] = $form['field_test_collection']['und'][0]['field_collection_second'];
    unset($form['field_test_collection']['und'][0]['field_collection_second']);
    $form['#submit'][] = 'mymodule_node_form_submit';
}

function mymodule_node_form_submit($form, &form_state) {
    $form_state['field']['field_test_collection']['und']['entity'][0]->field_collection_first['und'][0]['value']=$form_state['values']['field_test_collection']['und'][0]['surround_fieldset']['field_collection_first']['und'][0]['value'];
    $form_state['field']['field_test_collection']['und']['entity'][0]->field_collection_second['und'][0]['value']=$form_state['values']['field_test_collection']['und'][0]['surround_fieldset']['field_collection_second']['und'][0]['value'];
}


You probably need to pass a reference of jQuery and Drupal in your js file like this:

(function ($, Drupal, drupalSettings) {

  ...

})(jQuery, Drupal, drupalSettings);

Btw. your js has {{{ but only }}. And you don't need document ready when you use drupal behaviors.


Configuration variable inside a hook take always the default value in a PHPUnit test

I found an answer that solve this problem, but I think that maybe there are other answer to this.

After some ideas from @tim.plunkett on slack:

  as i see it: with render caching, changing the config value will not
  alter the form

and

  the tl;dr is that any conditionals in render-related code need cache
  contexts

I made the test work with this code:

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Turn off autocomplete on key forms.
 */
function no_autocomplete_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  // Adding cache tags.
  $form['#cache']['tags'] = ['config:no_autocomplete.settings'];

  // Add to the user_login.
  if (\Drupal::service('config.factory')->get('no_autocomplete.settings')->get('no_autocomplete_login_form')) {
    $form['pass']['#attributes']['autocomplete'] = 'off';
  }
}

This is the simplest way that I was found because in this case the config object only have one variable and each time that the config is changed is because this variable has changed, so in this case I think that the use of the cache tags is fine.

But I'm still trying to made works the code with a custom cache contexts. But I don't have luck for the moment.


Search page is not shown properly with D7 custom theme

I finally solve the problem. The problem was my implementation of the template page "page.tpl.php" because inside this I never call :

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

As a consequence the results of the search were never shown, so I can't saw changes made in "search-results.tpl.php" ...


Preprocess taxonomy for a custom template file

If you're trying to use this in your page template files, then you should put your template.php code inside the yourtheme_preprocess_page(&$vars) function.  That's the one that will get called before your page template file, and it can "communicate" its results to the template file by putting them in the $vars variable which was passed to it by reference.

So here's an idea of how you can improve your code:

In template.php:

function mytheme_preprocess_page(&$vars) {
  $term = taxonomy_get_term($taxonomy_id);
  $vars['term_name'] = $terms->name;     // Store anything you want to use later in $vars
}

In page.tpl:

<?php print $term_name; ?>

Let me know if that helps you get closer!

============================ EDIT =============

The variables set in the hook_preprocess_page() function are only available in your page.tpl files.  If you're trying to get to these variables in your view templates, you'll have to instead use a views pre-processing function, such as mytheme_preprocess_views_view(&$vars)


Delay ajax call on textfield to allow for typing

One option is to use a custom jQuery event, eg. something like finishedinput. Set $form['my_input']['#ajax']['event'] = 'finishedinput' and provide some JS to trigger your custom event after an appropriate delay (similar to the JS in the fiddle).


Why can't Drupal write to the database after migrate/restore?

It was a schoolboy error on my part. I didn't have mod_rewrite enabled on my local environment, so clean URLs weren't working.


Creating Pay and Configure Products on Drupal Commerce

This module set only supports customizing the product prior to checkout. Achieving customization after checkout will require custom module development.


How do I merge changes from a development copy of the site to the live site without losing new content?

For content types, views, and structure changes on the dev site look at using Features to export the database to code.

For content migration there are many options, but not a single solid solution. One example is the Deployment suite.


You can run
drush up zen, it will update the zen theme, but not the subtheme
Please do a backup before running this command


Where should I place hook_block_view_alter?

In drupal 8 the declaration of hook_block_view_alter changed from hook_block_view_alter(&$data, $block) (Drupal7) to  hook_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) (Drupal 8).
For more info check hook_block_view_alter Documentation page.

hook_block_view_alter be better in custom module not theme, see guide to building basic Drupal 8 module, and flush all caches.


How do I block individual content items from search engines?

Use Metatag module for this purpose. Go to configuration page of metatag module and you can prevent google to index your node type.

Hope it will help.


How to make author name hyperlinked to it's profile

To the first question: users (anonymous or authenticated) need to have the "View user profiles" permission.

To the second: the user you set will be the original owner. The fact that admin created it is not stored in the node anymore.


Drupal Commerce does not allow any payment if payment pane is not in review order page

I guess 'payment' means 'choose payment method'


Integrating Commerce Feeds and Physical Field. (Drupal Commerce)

If you can't find Physical Field integration with Commerce Feed module for mapping your fields such as height, width or length, please have a look on a discussion started by bmx269 at http://drupal.org/node/1293820. Apply the patch & you will be able to find the field to map with your CSV file header.

Good luck...


How to create a directory during a module install?

Are you sure the directory where you are creating directory is writable?

file_prepare_directory checks that the directory exists and is writable.
You can try drupal_mkdir statement to create directory in hook_install


How to do social links with icons as a link field in a block?

I had a similar task, for me was better creating a Custom Block Type, named 'Social networks' with one field of type 'Link'.

In this field you can configure how many links you can handle (remember once you create one block of this type, you'll cannot change this value).

Once this Custom Block Type was created you can configure 'Manage form display' and 'Manage display' if you need.

Now you'll be able to create a Custom Block of type 'Social Networks' that provide a couple of links that you can set/edit, rearrange and use proper template per block, and place where you want.

This was the solution found to not use any piece of code.


Fields with Secure value (allows use of all tokens) won't appear in your markup (that's why they are secured). They are 'created' on server side and are not available on Client Side. So nobody can't change their value (f.x. via XSS)

Hope it helps.


I think the best solution is used custom field formatter for date type:

/**
 * Implements hook_field_formatter_info().
 */
function mymodule_field_formatter_info() {
  return array(
      'mymodule_custom_datestamp' => array(
          'label' => t('Custom datestamp formatter'),
          'field types' => array('datestamp'),
      ),
      'mymodule_custom_date' => array(
          'label' => t('Custom date formatter'),
          'field types' => array('date', 'datetime'),
      ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function mymodule_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {
    case 'mymodule_custom_datestamp':
      foreach ($items as $delta => $item) {
        $tmp = (integer)$item['value'];
        $minutes = (integer)date('i', $tmp);
        if(empty($minutes)){ //you'll update only values with :00
          $element[$delta] = array('#markup' => date('l, F d, Y - h a', $tmp));
        }else{
          $element[$delta] = array('#markup' => date('l, F d, Y - h:i a', $tmp));
        }
      }
      break;
    case 'mymodule_custom_date':
          .....
          break;
  }

  return $element;
}

You can use it anywhere and It uses the least resources.


Failed to import Bootstrap Paragraph sub module configuration

To use that module, you should upload it to the site, usually in the /modules/custom/ folder since it is not an official Drupal.org module, and then enable it.  The configuration should get installed when you enable it.  You should not have to do that manually.

After the module is enabled, you need to edit the Paragraph reference fields that you want to make this bundle available in.

Hope that helps.


Creating a view with multiple latest content types

You can create two views, one for each content type, the configuration is the same, Filter Criteria should be Content Type (select in one articles and in the other news) you should sort by Authored on in DESC order, in the pager select Display a specified number of items (3) and More link (Yes).

Then you can add the two blocks to the page and add the styles with css.


How can I update or insert a row with NULL fields using query builder?

db_update() does allow NULL to be used for field values. To confirm this, check out the core table, block_custom, which allows both block_custom.body and block_custom.format to be NULL.

First, insert some dummy data either through the block administration screen or via SQL:

INSERT INTO block_custom (body, info, format)
  VALUES ('Lorem Ipsum', 'Test block', 'plain_text');

Now run the following code:

db_update('block_custom')
  ->fields(array('body' => NULL))
  ->condition('info', 'Test block')
  ->execute();

If you look at the table after executing, block_custom.body will be set to NULL.

db_insert() works too:

$fields = array(
  'body' => NULL,
  'info' => 'Test block 2',
  'format' => 'plain_text',
);

$result = db_insert('block_custom')
  ->fields($fields)
  ->execute();

So there's something else wrong with your statement. Two things to check:

Ensure $record really has NULL values in the db_update() query. var_dump() the array just before the db_update() and ensure nothing's modified the values.
Check the condition statement. If set to a condition that doesn't match any of the rows in the table, the update won't occur and $result will contain a falsy value. Since it's perfectly value to have an UPDATE query that matches no rows, it won't throw an exception or return an error.


Is it possible to run command of the same functionality as drush pm-download from hook_install or hook_update_n?

If the web server user has permissions to write to the modules folder (which is in itself a security risk), then yes, you can do that. Writing it wouldn't be trivial, of course, but you can get a lot of the necessary code from Drush.

If the web server user doesn't have permissions to write to the modules folder, then no, it's not possible.

  If not, what other alternative solutions do I have to automatically download and install modules and dependencies from a custom site deployer module?

If your web-server is properly secured, then your only option is to invoke the script (whatever form that may take) as a user with sufficient privileges.


Would that checkout pane still be captured by hook_alter_form()?  If so you could add #required to the field there. Let me have a quick try and I'll get back to you.

EDIT: OK, this worked for me:

function tools_utilities_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'uc_cart_checkout_form') {
    // Make delivery date required
   $form['panes']['ddate']['ddate']['#required'] = true;
 }
}

Create your own module (mine is called tools_utilities in this example) and implement the above and you should be good to go :)


Typically the option to disable these are located under your theme settings (/admin/appearance/settings/THEMENAME). If your theme doesn't provide the option to disable these, you can always resort to http://drupal.org/project/disable_breadcrumbs


Error when creating taxonomy term programmatically

i found the solution.

the problem was with uppercase/lowercase vid value.

If your vocabulary starts with an uppercase letter ex: 'Animal', thr vid value will starts with a lowercase letter ex: 'animal' otherwise you will have an error

This was my problem, hope it will you help.


Order of drush commands for automated deployment?

Drush 10.3.0 now provides a deploy command to standardize how Drupal deployment works. This command performs the following:

drush updatedb --no-cache-clear
drush cache:rebuild
drush config:import
drush cache:rebuild
drush deploy:hook

Database updates always come before configuration import! Support for automatic entity updates has been removed from Drupal core (change record) and entup has been removed from Drush core. Whenever an entity type or field storage definition needs to be created, changed or deleted, it has to be done via hook_update_N().

Here is the updated deployment routine I'm happiest with.
drush state:set system.maintenance_mode 1
drush cache:rebuild
git pull
composer install --no-dev
drush cache:rebuild
drush deploy
drush state:set system.maintenance_mode 0
drush cache:rebuild

This also means you have to run two releases if you want to uninstall and remove a contrib module. First release to deploy the updated config that disables the module. Second release to deploy the updated composer.json and lock file after you removed it with Composer.
To make real consecutive releases possible you might want to pass the current release's commit SHA1 to the deployment script and then replace git pull with a more exact routine (where $1 is the SHA1):
# If not empty 1st argument passed to the script, do:
if [ -n "$1" ]; then
  git reset --hard "$1"
else
  git pull
fi

Otherwise the consecutiveness can not be guaranteed when you push two new releases at once or within a short period. As then the first release's triggered git pull will simply pull the latest changes (from the second release), where instead it should pull only the changes included in the first release. See the full sample repo leymannx/drupal-circleci-behat.
Credit for this git snippet goes to CircleCI. This is how they are doing it in their containers.


ShareThis facebook posts previews are perfect, but posts empty images

http://natureupnorth.org/sites/default/files/styles/encounter_big_image/public?itok=5aqi4xn6

That og:image gives me a 403 error.  Is this set to require a logged in user?


Drupal 6: Having a menu where more than one Item is active

Drupal has built in the assumption that only only one item in a single menu can be active.

You hack the core menu system or create your own, but both would not be recommended.

The best workaround I can think of, is to expend the menu and use css and JavaSript to show/hide the menus and mark them as active. This could be doable but might be quite hard if you have a complex menu structure.


Remove the 'read more' and 'Add new comment' links on the home page

In your theme's template.php file, add this snippet:

function THEMENAME_preprocess_node(&$variables) {
  if ($variables['is_front']) {
    unset($variables['content']['links']);
  }
}

Remember to clear the cache afterward. And replace THEMENAME with your actual theme.


Can you get the itok value programmatically?

It should be possible to get the token via a custom ajax callback that returns:

$token_query = array(IMAGE_DERIVATIVE_TOKEN => image_style_path_token($style_name, $original_uri));

From a custom menu router path or services callback.


If you are doing it by custom code, you have to move the field to 'account' container, example code looks like

function my_module_name_form_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    // Change weight in respect of user name field.
    $form['field_test']['#weight'] = $form['account']['name']['weight'] + 1;
    // Use machine name of field as form field, replace 'field_test' with your machine name.
    $form['account']['field_test'] = $form['field_test'];
    unset($form['field_test']);
  }
}


Can I make a Drupal Book page parent with no content?

Yes, create a new content type, call it headings, remove the body from it and let it have children.

see http://yoursite.com/#overlay=admin/structure/types/add

Create the heading content type and remove the body, add or remove anything you want or don't want while your there.

Then see:
http://yoursite.com/#overlay=admin/content/book/settings

Add the new content type to the books modules allowed content types and your done.


Your steps are right. I tested it on my local environment, and it works.

For example, for the content type "companynews", add the function to the template.php:

function garland_theme($existing, $type, $theme, $path) {
  return array(
    'companynews_node_form' => array(
      'arguments' => array('form' => NULL),
      'template' => 'node-companynews-edit'
    )
  );
}

Create the node-companynews-edit.tpl.php file and put the test code.

<?php
  echo 'it works!";
?>

Clear the cache, and access http://example.com/node/add/companynews: it shows "it works."

PS: You can also use hook_form_alter() to alter the form, and then use CSS to style it.


Omega theme node template renders outside any regions

I had the same issue. It turned out I had the "main content" block visibility settings set to "Only the listed pages," but I had no pages listed in the box below.

So, (of course) it did not render.


Migrating site from localhost to production some images does not show

First, make sure your images are actually uploaded to the server and accessible (go to http://SITEURL/sites/PATH/TO/IMAGE/DIR/image/274f1bf2bd18e7f0d33d6244e658426e.jpg to check), then make sure the file and directory permissions are correct. Check the admin/config/media/file-system page, and click "save" – if it's not setup correctly it should display an error message and you'll most likely have to change directory permissions.

Don't worry about the tokens or anything after .jpg (ie: ?itok=AUwo0SYX) –– those are merely for cache-clearing, and can be safely ignored, it has no impact on accessing the images on the server.


Get out of maintenance mode using database query (without using drush or admin area)

It's never the best idea to manipulate the database directly (for the usual reasons), but if you're out of other options, it's not that unsafe:

UPDATE key_value
SET value = '<value>'
WHERE collection = 'state'
AND name = 'system.maintenance_mode'

Where <value> is replaced with a serialised PHP string representing the integer value 1 for enabled, or 0 for disabled, e.g.

$value = serialize(1);

You'll probably want to invoke a cache rebuild after manually updating the variable, it's probably cached somewhere.


Some files are deleted from the files table after CRON execution

file_save_upload():

  The source file is validated as a proper upload and handled as such.
  The file will be added to the files table as a temporary file.
  Temporary files are periodically cleaned. To make the file permanent
  file call file_set_status() to change its status.

You need to use file_set_status() to change the status of the file.

  $save = file_save_upload('image', array(), $dir);
  if($save->fid) {
    file_set_status($save,FILE_STATUS_PERMANENT);
    ...


How do I programmatically change the body text format on the page content type to full HTML?

You can do it with hook_element_info_alter, here is a snippet.

<?php
/**
 * Implements hook_element_info_alter().
 *
 * Sets the text format processor to a custom callback function.
 * This code is taken from the Better Formats module.
 */
function MODULENAME_element_info_alter(&$type) {
  if (isset($type['text_format']['#process'])) {
    foreach ($type['text_format']['#process'] as &$callback) {
      if ($callback === 'filter_process_format') {
        $callback = 'MODULENAME_filter_process_format';
      }
    }
  }
}

/**
 * Callback for MODULENAME_element_info_alter().
 */
function MODULENAME_filter_process_format($element) {
  $element = filter_process_format($element);
  // Change the default text format of the 'field_company_spotlight' field to
  // 'Media HTML'.
  if ($element['#bundle'] == 'company' && $element['#field_name'] == 'field_company_spotlight') {
    $element['format']['format']['#default_value'] = 'media_html';
  }
  return $element;
}
?>

As THIS post suggests you could try

$form['field_name'][LANGUAGE_NONE][0]['#format'] = 'full_html';
$form['field_name'][LANGUAGE_NONE][0]['#format'] = 'filtered_html';

in your hook_form_alter or in hook_FORM_ID_alter

Also there is Better Formats module

  Better formats is a module to add more flexibility to Drupal's core
  input format system.


"Rate Module" How to put the number inside the button?

This is done by using some CSS.

look at the HTML structure there. 'LI' tag is used there. Just use the anchor style to LI tag.

background: #EEE;
border: 1px solid #CCC;
margin-right: 3px;

Use this style to li and remove anchor border. Also change the hover style of anchor tag.

Use firebug to find the structure.


There are 2 modules out there that can do one part of what you're wanting, but not both.

Field Permissions lets you display fields based on role.
Field Formatter Conditions lets you display fields based on the content value of another field.

If your content design is flexible these might help.

However, if you're looking for field display based on both a role and another field's value you might be better off adding a template_preprocess_node() function to template.php to check for rendering logic. For example:

function MYTHEME_preprocess_node(&$variables) {
  global $user;

  $job = isset($variables['node']->field_job[LANGUAGE_NONE][0]['value']) ? $variables['node']->field_job[LANGUAGE_NONE][0]['value'] : '';
  if($job == 'policeman' && !in_array('Officer', $user->roles)) {
    hide($variables['content']['field_phone']);
  }
  //@TODO: Add other role/value checks
}


To detect folders created and files added to an S3 bucket, you need to Flush s3 media file metadata cache.

To do it,
Configuration > Media > S3 File System > Actions > File Metadata Cache > Refresh File Metadata Cache

The file metadata cache keeps track of every file that S3 File System writes to (and deletes from) the S3 bucket, so that queries for data about those files (checks for existence, filetype, etc.) don't have to hit S3. This speeds up many operations, most noticeably anything related to images and their derivatives.

This button queries S3 for the metadata of all the files in your site's bucket (unless you use the Root Folder option), and saves it to the database. This may take a while for buckets with many thousands of files.
It should only be necessary to use this button if you've just installed S3 File System and you need to cache all the pre-existing files in your bucket, or if you need to restore your metadata cache from scratch for some other reason.


If you are using drupal 7, there should already be a node object available when you are looking at a full node page. Looking at http://api.drupal.org/api/drupal/includes--theme.inc/function/template_preprocess_page/7 - the default implementation embeds it into the $variables array:

  if ($node = menu_get_object()) {
    $variables['node'] = $node;
  }

If your theme is overriding this, you can simply add it back in.

An example might be:

function YOURTHEME_preprocess_page(&$variables) {
  if ($node = menu_get_object()) {
    $variables['node'] = $node;
  }
}


How to define the site to be used in BrowserTestBase on a multisite?

None of your existing sites are used during a fonctionnal test, drupal creates a fresh install defined by your static attribute $modules and the setUp() method.

So, you should get the default.settings.php file back (and create a /sites/simpletest folder)


The Examples for Developers collection of sample modules includes a sample implementation of vertical tabs in forms.


Custom jQuery code loaded but not working

Managing javascript in drupal

As per the above link you should put your Javascript or Jquery inside the following :

(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
   // add your code here
      });
    }
  };

})(jQuery);


How to link to last comment on a node page?

I don't think there's a simpler way than that, but you can combine two of those steps into one so you at least only need to make a single database call:

function node_last_comment_link($node, $link_text) {
  // Get the num active comments and most recent comment id
  $data = db_query('SELECT MAX(cid) AS cid, COUNT(cid) AS cnt FROM {comment} WHERE nid = :nid AND status = 1', array(':nid' => $node->nid))->fetchObject();

  // No comments, no link
  if ($data->cnt == 0) {
    return FALSE;
  }

  // Get the num comments per page
  $var_name = 'comment_default_per_page_' . $node->type;
  $sensible_default = 50;
  $num_per_page = variable_get($var_name, $sensible_default);
  $page_num = floor($data->cnt / $num_per_page);

  //Build and return a URL
  $query = array();

  // No point adding ?page=0
  if ($page_num > 0) {
    $query['page'] = $page_num;
  }

  $fragment = 'comment-' . $data->cid;
  return l($link_text, 'node/' . $node->nid, array('query' => $query, 'fragment' => $fragment));
}

I've given that a quick test and it seems to work but it might need a bit of massaging, especially if you have threading turned on :)


How do you remove the default Drupal 7 administration menu?

Weird, it just took time. I came back a few hours later and it was gone. Perhaps there are cache clearing issues in Drupal 7.


What is the equivalent of user_set_authmaps()?

As reported in {authmap} deprecation, the authmap database table has been removed from Drupal 8; at the same time, the functions using that database table (such as user_set_authmaps()) has been removed.

The suggested alternatives are:

Write your own solution for managing user external authentication and storing remote identities
Use the External Authentication module


How to access $vars['some'] variables in html.tpl.php template

The general rule for any THEMEHOOK.tpl.php file (where THEMEHOOK is something like 'html', 'page', 'node' etc.) is:

The default variables are set in template_preprocess_THEMEHOOK() (eg.
template_preprocess_html)
Any module can add variables using MODULENAME_preprocess_THEMEHOOK() (eg. toolbar_preprocess_html)
The active theme can add variables using THEMENAME_preprocess_THEMEHOOK() (eg. bartik_preprocess_html)

The $variables array (sometimes called $vars) is passed on from function to function in the above order, so each function can expand on or overwrite the variables added before.


Unable to get javascript to make first letter of every word LARGER on my site to load properly

If Alireza's answer doesn't work, try this one.

js/first-letter.js

(function ($) {
 $( document ).ready(function() {
  $('.field-name-title').html(function(i,el) {
    return el.replace(/\b([A-Z])/g, "$1");
     });
  });
}(jQuery));


Organic Groups Vocabulary - Dynamically Load Terms

I recently encountered the same issue and the way I got around it was to use a hook_form_alter to use the appropriate taxonomy from the pre-populated selection of og_group_ref via a db_select on the taxonomy_term_data table.

I used entity_reference_prepopulate to set up the link to create group content for the group.  Seems hacky to me and would like to know if others were able to get it to work like the OP had wanted it.  Here is an excerpt of my hook_form_alter.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // ... get gid from context
  // ... i used request_uri() to get the uri and parsed out the gid
  // there may be less hacky ways of doing this.
  $query = 'SELECT tdata.tid, tdata.name FROM (SELECT vid from {og_vocab_relation} where gid=:groupid) og left join {taxonomy_term_data} tdata on (og.vid=tdata.vid)';
  $query_params = array(':groupid' => $gid);
  $taxi_terms = db_query($query, $query_params);
  $options = array();
  $options['_none'] = '- None -';
  foreach($taxi_terms as $taxi_term) {
    $options[$taxi_term->tid] = $taxi_term->name;
  }
  $form['og_vocabulary'] =  array(
    '#title' => 'Projects',
    '#type' => 'select',
    '#multiple' => TRUE,
    '#options' => $options
  );
}


how to show a link only on my own profile node?

The code you have posted above will check if you are on the user/[uid] page for the user that is logged in. So it will take effect for the user's own user page. If you wanted to post the link on all pages except the user's own page you should instead do

if (arg(0) == 'user' && is_numeric(arg(1)) && $user->uid != arg(1)) {


Filter criteria according to the get variable user/*

Here are the steps to achieve your requirement

Go to view and add contextual filter User: uid

Then select 'Provide default value' and select Type : 'Raw value from URL' and Path component: 2 (as URL is user/* .we select second component to get User ID)

That's it. I've tested this and working perfect.

Hope it helps.


How do I print a twig variable inside a JavaScript in a twig file

I'll spare to tell that it's a bad practice to add custom script blocks to templates, and just point out the error(s):

(1) To set the variable content, you have to wrap set into a {% %} block, not {{ }}.

(2) You most probably want the value as JavaScript string, so don't forget to wrap it in " ".

This sums up to

{% set twigVariable = '123456' %}

<script>
  function myFunc() {
    var myJsVar = "{{ twigVariable }}";
  }
</script>

Which should be working just fine.


Checkout page not found when order created through Drupal Commerce API for not authenticated (anonymous) user

You need to add the order to the session, see commerce_checkout_access().

Something like this should work:

$_SESSION['commerce_cart_orders'][] = $order->order_id;

between saving the order and redirecting.


Put <br/> in view source mode of your field as your line separators.


Open a specific View node with a link in an image

From what I gather there are two possible approaches to this:

Either add a field for Link and then "Rewrite Results" to the content by referencing the node_id. Or do the rewrite on the image itself to the appropriate node_id. You might have to massage the urls for the other View or find a pattern to make this work.
Add a relationship to the gallery view to the Node that contains the UA fields. Add this relationship to the image field and then work it that way.

Hope this helps!


How can I display a confirmation message after someone subscribes via simplenews?

Consider using the Rules module to implement this. And enable the Simplenews rules module (a sub-module of Simplenews).

Then create a rule like so:

Event: "A user has been subscribed".
Action: "Show a message on the site" (located within "System").


AJAX autocomplete based on other field value

I know it's a bit amateur but the question has already been answered I just didn't find it.

It's here:

form auto complete how to restrict results by previous drop down

and here:

Using ajax to filter drupal autocomplete form

BTW: I would delete the question but since I didn't find the answered questions myself I thought that this one might be more discoverable.

//I can't accept my own answer now, sory for that.


What module are you using to upload/show images? CCK + ImageField?

Anyways, to troubleshot your problem you need to figure the reason why no images are shown. This can be due to several reasons:

Wrong file Permission. When uploading via FTP or CPanel sometimes sometimes file permission gets messed. Try setting permission to 777 recursively to your image folder and see if images appear.
different absolute path. Some modules use an absolute path to figure in which folder they should upload images to. one easy way to find out is to create/upload a new image via CKK and using firebug (for instance) compare the URI of old images to the URI of the new image.

Keep us posted


Views 3 | How to programatically unset or add new value to a view's footer / header display?

The snap code below has been tested only on D7. In case this code does not work on D6, check out the comments on this post here.

function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'VIEW_NAME' && $display_id == 'DISPLAY_ID') {

    // To find out the DISPLAY_NAME, FIELD_NAME and FIELD_VALUE use the devel module function
    // below to print them out.
    // Replacing 'footer' by 'header' works the same way.
    dpm($view->display_handler->options['footer']['DISPLAY_NAME']['FIELD_NAME']);

    $view->set_item_option($display_id, 'footer', 'DISPLAY_NAME', 'FIELD_NAME', 'FIELD_VALUE');

    // In this case scenario you needed to unset the footer display.
    // For the embedded view display you do like this:
    $view->set_item_option($display_id, 'footer', 'DISPLAY_NAME', 'view_to_insert', '');
    // For the normal text area display you do like this:
    $view->set_item_option($display_id, 'footer', 'DISPLAY_NAME', 'content', '');
  }
}

Due to comments, to determine what views name and display came to this function, make next (of course, "devel" module should be enabled)

    function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
      dsm($view->name);
      dsm($display_id);
      if ($view->name == 'VIEW_NAME' && $display_id == 'DISPLAY_ID') {
...
      }
    }

And update views page.


Fatal Error: PDOException: SQLSTATE[42000] [1049] Unknown database

This isn't a problem with tables, it's a problem with the name of the database.

Drupal is successfully connecting to your database server, but it isn't finding a database with the name mydevelopmentDB (which must be the name of the database specified in settings.php).

To isolate the problem:

Open up PHPMyAdmin for the server in question and run this query:

SELECT * FROM mydevelopmentDB.users

If you get a similar error then you know that you've definitely got the wrong database name.
Make sure that the name of the database on the server matches the case of the database name in settings.php. Depending on your MySQL settings the server may or may not be enforcing case sensitivity on database/table names.


To disable cache for development(tiwg + Drupal cache) :

first copy and rename the sites/example.settings.local.php to be sites/default/settings.local.php

then open settings.php file in sites/default and uncomment these lines:

# if (file_exists(__DIR__ . '/settings.local.php')) {
#   include __DIR__ . '/settings.local.php';
# }

Now open settings.local.php and change the below lines to "TRUE".

$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;

and uncomment all these to Disable the render cache and Disable Dynamic Page Cache

# $settings['cache']['bins']['render'] = 'cache.backend.null';
# $settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

for twig cache open "development.services.yml" and update the below parameters.

  twig.config:
    debug : true
    auto_reload: true
    cache: false


What happened to the links to import or export a View?

That Views import/export facility is no longer available in Drupal version 8 (within "admin/structure/views") ...

A possible way to do similar Views imports/exports in Drupal version 8 is to use the new configuration management facilities, which can typically be used to migrate configuration items, such as Views, between related dev, staging and production sites.

So it appears to me that as of right now (8.0.5) there is no "easy" way (as it used to be in Drupal version 7) to do such imports/exports between 2 sites that are not "related". Except probably/maybe with some special manual editing to make the site Ids match somehow.

Though according to Berdir's comment below (excl. some typos), "that's not true. You can use single import/export of any configuration file between any site, as long as you take care of the dependencies as well. The related site/UUID checks only apply to a whole config sync.". And followed by the /admin/config/development/configuration/single/import suggestion (merci Berdir).

Maybe an opportunity for a new D8 contributed module to bring this import/export facility back ... and/or one of the "reasons to be" for the Features module in D8 (as suggested in another comment by Danny Englander) (merci Danny).

PS: For some more info about /admin/config/development/configuration/single/import mentioned above, refer to the Community documentation about "Managing configuration in Drupal 8". Part of what is included on that page is like so (bold markup added here):

  It is possible to export a single configuration file and paste it into another environment. The single import option lets you specify the type of the configuration file and import it from your copy-pasted value.

Though nowhere on that page I could find an indication if using "environments" for which site Ids are different (for "single" imports) is allowed or not.

If you want to get an idea of how it is like to use these import/export features, then have a look at the slideshow "The Magic of Drupal 8’s Configuration Management on a Managed Workflow" (especially slides like on page 44 to 48).


Any way to add CSS for a single page/node?

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

In the template.php you will want something like:

function MYTHEME_preprocess_node($vars) {
  if (drupal_get_path_alias("node/{$vars['#node']->nid}") == 'foo') {
    drupal_add_css(drupal_get_path('theme', 'MYTHEME') . "/css/foo.css");
  }
}

Replace foo with values related to your own code.


Best way to unpublish a node, given the nid, while bypassing any node update hooks?

If you have an array of nids you could just run this piece of code

example will unpublish the nodes with nid 1,2,3:

$nids = array(1, 2 ,3);

foreach($nids as $nid) {
    db_query("UPDATE {node} SET `status` = '0' WHERE `nid` =:nid ;"
,array(':nid'=> $nid));
}

entity_get_controller('node')->resetCache($nids);


Use the same image 2 times in image styles

I have solved the task currently without a custom image style. Only custom code:

/**
   * Applies an image effects blur, scale and crop.
   *
   * The result is am image with 2 layers:
   *   - background: a cropped picture with a blur effect.
   *   - foreground: overlay with the same image and scale effect.
   *
   * @param int $width
   *   Result image width.
   * @param int $height
   *   Result image height.
   * @param int $radius
   *   Result image blur radius.
   */
  public function blurScaleAndCrop($width, $height, $radius) {
    $image = $this->getImageFactory()->get($this->path);
    if (!$image->isValid()) {
      throw new \InvalidArgumentException("Image {$this->path} is not valid");
    }

    // Create the background image.
    $image->scaleAndCrop($width, $height);
    /** @var \Drupal\system\Plugin\ImageToolkit\GDToolkit $toolkit */
    $toolkit = $image->getToolkit();
    $resource = $toolkit->getResource();
    // Apply blur.
    if ($radius) {
      for ($i = 0; $i < $radius; $i++) {
        imagefilter($resource, IMG_FILTER_GAUSSIAN_BLUR);
      }
    }
    $image->apply('gaussian-blur', ['radius' => $radius]);

    // Create the foreground image.
    $foreground = $this->getImageFactory()->get($this->path);
    if (!$foreground->isValid()) {
      throw new \InvalidArgumentException("Image {$this->path} is not valid");
    }
    $foreground->scale($width, $height);

    // Merge the 2 image layers.
    $dst_im = $image->getToolkit()->getResource();
    $src_im = $foreground->getToolkit()->getResource();
    $f_width = $foreground->getWidth();
    $f_height = $foreground->getHeight();
    $x = ($width - $f_width) / 2;
    $y = ($height - $f_height) / 2;
    imagecopy($dst_im, $src_im, $x, $y, 0, 0, $f_width, $f_height);
    $image->save();
  }


How to programmatically render a view pager?

The object returned from $views->pager() is an object implementing ViewsPluginInterface and extending PagerPluginBase. If you look at the parameters PagerPluginBase::render() accepts, you will see they are:

  $input: Any extra GET parameters that should be retained, such as exposed input.

If you look at Full::render(), you have an idea of how that parameter is used.

  $tags = array(
    0 => $this->options['tags']['first'],
    1 => $this->options['tags']['previous'],
    3 => $this->options['tags']['next'],
    4 => $this->options['tags']['last'],
  );
  return array(
    '#theme' => $this->themeFunctions(),
    '#tags' => $tags,
    '#element' => $this->options['id'],
    '#parameters' => $input,
    '#quantity' => $this->options['quantity'],
    '#route_name' => !empty($this->view->live_preview) ? '<current>' : '<none>',
  );

In any case, you don't pass to the method of that object the object itself.


How to create a view of duplicate entities based on title, showing the most recently created ones

I solved this using the modules

Flags
Rules
Views Rules
Rules links

with the following method:

Added a flag 'in bucket' connected to the entity
Created A views Rules display listing all entities
Created a rules link, which includes a rule with an action 'Views
loop' that performs an action on each entity in the views Rules
display. The action performed is a rules component that again uses a
views loop checking if a duplicate title is present. So for every
views list item, all views list items are compared.
If a duplciate title is found, the entity is flagged with the 'in
bucket' flag. The Rules link has as a last action the redirection to
the view that shows all entities in the bucket.
To make this more reliable, add as first action of the rules link, a
loop to remove all entities from the bucket (remove all flags).

In this way, with one click all entities are checked on duplicate titles, and the found duplciates are shown.

However, this is not the most efficient and performant way for large lists. For example when having 2000 entities, rules will need to process 2K x 2K = 4M times the comparison.
I had to limit my list to 350 items in order to have processing time of 5 minutes.
I tried to implement batch processing of the views loops, but did not succeed yet.

A more efficient way would probably be to use the view as mentioned in the question, and use that list of titles as a filter for another view which should show the most recent entities having one of this titles.
I haven't figured out how to do this yet.


Your media token snippet is from the Drupal 7 Media library and WYSIWYG integration.

I don't know if that integration exists yet in Drupal 8. It would apart of, listed as a project of the Media Entity project for drupal 8.

EDIT

You want to see the Entity Embed module for Drupal 8 which supports WYSIWYG editors. I don't know if they offer a migration of old media content into this new module though.

These modules were found by these blog resources and DrupalCamp sessions which have a Youtube video showing these modules in action:

https://drupalsquad.com/drupal-8-media-handling
https://amsterdam2014.drupal.org/session/drupal-8-media  Media Ecosystem in Drupal8 drupalcamp youtube video can be found at https://www.youtube.com/watch?v=Hd-jPrEcAn8


"Access denied" whenever trying to edit IMCE User-1 profile

Earlier I changed the Drupal admin from the mysql database. I simply done undo on this operation.
Have a look in your database.


How to create a list of OG groups with no activity using Views?

/**
 * Implements hook_views_pre_render().
 */
function my_module_views_pre_render(&$view) {
  foreach ($view->result as $key => $row) {
    $node = node_load($row->nid);
    if ($node->changed > (time() - (30 * 24 * 60 * 60))) { // 30 days back in time();
    unset($view->result[$key]);
    }
  }
}


Will Drupal 6 be left in a secure state after it becomes unsupported?

Once Drupal 8 comes out, Drupal 6 will be marked "end of life": the Drupal security team will stop working on it and official security releases won't come out for it. If any new vulnerabilities come out, you'll have to patch it yourself. So it's really in your benefit to upgrade at that point.

But upgrade paths for Drupal are from the previous version to the current version: that is, an upgrade path is provided from the last release of Drupal 6 to Drupal 7, and an upgrade path will be provided from Drupal 7 to Drupal 8.

There won't be an upgrade path for Drupal 6 to Drupal 8: if you don't want to rebuild your site from scratch when Drupal 8 comes out, you'll need to first upgrade your Drupal 6 site to Drupal 7, then upgrade to Drupal 8.

So, it really comes down to economics and long term planning. Drupal 6 will be supported until Drupal 8, but when Drupal 8 comes out in a couple of years, will you have an opportunity to rewrite the site? If not, you should plan to upgrade to Drupal 7 at some point in the future.


Accessing Webforms Parameters in hook_form_alter

I can't see a way to access the originalData property you mention. It's a protected property and there's no getter defined. See the callback_object's class in the webform module at src/WebformSubmissionForm.php.
I'd take a slightly different approach here. Since you are building custom values based on the paragraph id, it seems appropriate for the paragraph id to be included with the submission data. To do this, add a new hidden element to your webform for the paragraph id, e.g. with machine name paragraph_context.
Then, to provide a default value for your hidden field, update your twig like:
{{ {
  '#type': 'webform',
  '#webform': 'contact',
  '#default_data': {
    'paragraph_context': paragraph.id,
  },
} }}

(Note: I don't see any mention of the values or parameters options you're using in the How to embed a Webform documentation on d.o.)
Lastly, access your paragraph_context value via the #default_value key for your hidden element in your hook_form_alter(). For example:
mymodule_hook_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'my_form_id' && !empty($form['elements']['paragraph_context'])) {
    $paragraph_context = $form['elements']['paragraph_context']['#default_value'];
  }
}


Where to initialize module specific variables

hook_init() is always invoked for not cached pages, even for AJAX request. You can verify the page request is made because an AJAX request, though.

There are two conditions that should be common on any AJAX request:

The menu path is system/ajax
The delivery callback is ajax_deliver()

While the first condition is only true when the form element doesn't set #ajax['path'],  the second condition should always be true.

Code similar to the following one should detect when a menu callback is called because an AJAX request.

if ($router_item = menu_get_item()) {
  if (isset($route_item['delivery_callback']) && $route_item['delivery_callback'] == 'ajax_deliver') {
    // It is an AJAX call.
  }
}

In Drupal 6, the menu callback for AJAX/AHAH requests changes, and each menu has its own callback. You can notice the path for those menu callbacks follows a specific pattern: It usually ends with /js, but that is not necessarily true. This means a menu callback could be associated with a path ending with /js, but that menu callback is not for a AJAX/AHAH request.


Views slideshow won't show "slideshow" display format (commerce kickstart)

Fixed this myself.

I am working with commerce kickstart and instead of adding it to the regular modules, added it to the kickstart ones (contrib). Also added the jquery.cycle library there (in libraries though) and then cleared the cache just to be sure.


How to set file upload directory by parent node content type and node id

File (Field) Paths module should help you.


How can I remove the default generated  tags in view's result?

The easiest thing to do is copy the template files from "sites/all/modules/views/theme/" into you theme (I normally make a "views/" subdirectory).

If you want to make this change for all themes, edit "views-view-unformatted.tpl.php".

If you want to just change that view, edit the view then click on the Theme: Information link.  It will show the template suggestions for the view.  Copy
If you want to make this change for all themes, copy "views-view-unformatted.tpl.php" to the proper name, and edit that file.

In both cases, make sure you clear the Drupal caches to make sure the system finds the new files.


Trouble displaying different info for same role/node type

If you don't already have one, create a View of Users to filter on.

In the Displays section of that view, add a new Display of type "Entity Reference" (where you would add one of Block, Page, etc.).

Now, you'll see in this new View Display the Format is called "Entity Reference List". Go to the settings for this formatter and add a field to search by (in this case, you'll want to use 'User: Name', most likely). Add a Filter Criteria here to only include Users of a specific Role (Tenants).

Now, go to Admin > Configuration > People > Account settings > Manage fields

Add an EntityReference field called "Tenants".

On the Field Settings page, change the Target type to User. Then change the Mode to "Views: filter by an EntityReference View". You'll see your list of "Tenants" here.

Still with me?

You'll want to make this field widget a Checkbox, probably, so that multiple values can be selected.

Okay, save on that screen and then on Field Edit page, change the number of accepted values to Unlimited. (it defaults to one).

Now, logged in as a Landlord, go to that Landlord's profile and select the Tenants off the checklist now visible on their profile.

You probably created a 'Page' by default with your Tenants (User) View, so now go to that page's View Display settings.

Add a Contextual Filter of User: UID. Set this to a 'Provide a Default Value' with type of "User ID of logged in User".

Now you can Utilize Fields on this Page View--Display content of "Field Tenants" and it will show whoever is selected in that field for the currently logged in user. You can tweak the settings here--if you want to show more information you can display them as "Rendered Entities" and then use any of the View modes for that user you've set up, you'll need to mess with "Multiple Field Settings as well to get it how you want, probably.


Filter to only nodes with an image in an imagefield in Views 3

'Is not empty' is an option for the operator of filters.  Did you try that?

So you can add a filter to your view, and just select that as your operator.  Here's a screenshot to help:


Checkboxes: how do I set the default values or show the user defined values using Form API?

From Drupal.org:

$form['element_id'] = array(
  '#type' => 'checkboxes',
  '#options' => array(1 => "One", 2 => "Two", 3 => "Three"),
  '#default_value' => array(1, 3),
);

Default value is set as an array representing keys of selected options.

Looking at the code in your question, problem is with spelling. you are setting '#deafult_value' when you want to set '#default_value'.


Regarding flag actions and rules integration

I realise this is a long time ago but for anyone else who arrives here: you can't redirect when doing AJAX flagging, because the redirect applies to the AJAX call not the current page.

It's theoretically possible, with D7, to return a page redirect using AJAX commands but I'm not sure off the top of my head how you would achieve that in this case, or whether you'd need some modification to the Flag module code to allow it to occur.


How do I programatically add fields to the Media module's field tables?

There is a sandbox module I helped with, Media Wrapper, which solves this problem by managing media via a field collection. This has the advantage of making it possible to associate any fields you like with a media file, including captions. And the metadata is all per-use rather than per-file.

As it is a sandbox module, it's not as polished as we would like but it does a reasonable job of solving this problem.

To use it, once installed you create a field collection with your media field and meta data and then configure it via field settings of the field collection to say how each field is to be used (for alt text, title, caption etc).


Drush can only find additional commands in themes and modules if it knows where your Drupal site is.  There are several ways you can do this; cd to the directory that contains your settings.php file, or pass --root and --uri on the commandline to point at the Drupal Root and site uri (e.g. mysite.com), or define a site alias and pass @alias on the command line.  See the Drush README file on the github project page for more information.


What's the side-effect of changing the file directory setting of a file field which already has contents?

Those files will still be shown normally unless you remove their directory manually, because the file path is stored in the database with each file information. So even when you change the folder for new files, the old ones will still know the path where they were uploaded.


Is it possible to create a "Meta-Forum" view when using organic groups?

It is very easy to build such of "forum" using Views. If you are using Organic Group Access, the view will be automatically filtered and only the content accessible to the user will be displayed.

Note that the OG Forum module has been abandoned due to security issues and should not be used. Depending on your requirements, it might be easier to simply use standard Views for the group forums (after all, a forum is nothing more then a View of taxonomy terms attached to a View of nodes).


DB connection works from the CLI, but fails from within Drupal

Figured it out!

The client computer was running SELinux and was blocking outgoing connections over http. This pair of CLI command fixed it.

setsebool httpd_can_network_connect 1
setsebool -P httpd_can_network_connect 1


How to cancel added product to cart if previous order has same commerce-product creator id

tl;dr - Rules is really the place to handle this. You need to hook into the add to cart form's validate/submit handlers and take care of it in there.

The best way to handle this is to look into the answer provided here: How do I prevent a product from being added to the cart?

This answer was originally written to do that very thing: to prevent a product from being added to an order if some criteria were met (and the context was a marketplace multi-cart as well).


Jump to a heading in a view from outside the view on the same page

You should be able to do this using standard HTML anchors, just rewrite the output of the Headings to include a simple anchor tag and in your top panel (aka table of contents) make the links go to their corresponding anchor tags.


Is it possible to display user's first login (activation) date in a view?

There is no field that stores this information in the database.

The only thing you have by default are user account creation date, last login date and last access time.

Once a user has logged in for a second time those values are no use to you.

There are also not user revisions by default so you can't see when the first time a user changes their username/password/etc. you can only see the data the most recent change was made.

The only way is to use something like login history or user revisions, however that only helps you from now on, not for existing users.

Off the top of my head I can't think of any way you can get reliable data for this for existing users.

[EDIT]
Actually, the drupal watchdog log stores user login events.

When a user logs in this watchdog call happens:

watchdog('user', 'Session opened for %name.', array('%name' => $user->name));

So if you check your drupal logs for "Session opened for" you can find all user logins.
This will only help you if you have a record of all your watchdog logs since the beginning of your site (probably not likely).
If you only use the dblog module that logs to the drupal watchdog table it is likely you don't have all logs because old ones will usually be purged to keep the database table size under control.
If you use the syslog module to that logs to your web server's file system it is possible that you could have backups of all logs for the whole life of your site, however that also isn't guaranteed.
It's probable that old logs are also purged in this case too.


Your problem is that you have named the chechboxes the same thing which is why you only get one value.

You could replace ['company'] with [$nid] or use '#tree' => TRUE on the field set to make the values turn into a nested array.


The node type will always have an underscore as the separator (not a dash) between words so the test would be:

if ($node->type == 'insert_pub') {
  // ...
}

But it seems from your question you want to test the URL alias of the node, not the type. To do that you need to use drupal_get_path_alias() to get the node's alias, and see if it matches:

$current_node_alias = drupal_get_path_alias("node/$node->nid");
if ($current_node_alias == 'insert-pub') {
  drupal_add_js('...
}

Make sure you've cleared Drupal's caches so the new preprocess hook can be picked up by the system. That's the only reason I can think of to explain the calls to debug() not working, as they should.


What are the recommended directory permissions?

That drupal page like so many is very long and confusing. But it contains this post by Jason, who hit the nail on the head:

  Posted by Jason Sale on November 1, 2010 at 12:40pm

  Thanks for writing this and everything, but all that I and 99% of people reading this page really want is a list of numbers next to a list of folders.

  /default on 755
  /default/files including all subfolders and files on 744 (or 755)
  /default/themes including all subfolders and files on 755
  /default/modules including all subfolders and files on 755
  /default/settings.php and /default/default.settings.php on 444


How to remove non breaking space from body/value in migration process?

By taking a look into the StrReplace class I see that you are missing the source key, which should be the name of the field/column/whatever you are importing from.
If it does not work, try to also remove the "regex" key and if it still does not, try to use a simpler search, to ensure that the problem does not lie with your data.


You can achieve this with Unique Field module. Set the scope to Content Type and you should be good to go.


I found the way :-)

$settings = entity_get_form_display('node', 'article', 'default')
  ->getComponent('field_image')['settings'];


How can I embed an Editor just like those in StackExchange Q&A in Drupal 7?

Yes, there are quite a few.  One of the most popular editor modules is WYSIWYG which allows you to choose which JavaScript library you want to use, or there are more specific modules such as the CKEditor module


You can use SVG Image Field module with Drupal 8 and the new core Media module.

Enable Media module and the experimental Media Library module both of which are found in Drupal >=8.7 core.
Download and enable SVG Image Field and apply to it the patch from Issue #3053011.
Go to /admin/structure/media  and click the "Add Media Type" button.
For the Media Type Name specify 'SVG'.
For the Media source select SVG from the dropdown.
In the field mappings map Name to Name (the only option in the dropdown).
Click save. Then proceed to configure the Form Display and the Display for the Default and Media Library view mode at /admin/structure/media/manage/svg/form-display and /admin/structure/media/manage/svg/display respectively. You'll most likely want to just enable the "SVG" field, and disable the rest of the fields. The default display you can choose to use an inline SVG option.
Add a Media reference (Entity reference) field to your node types and configure it to allow the SVG bundle type.  Optionally, enable other bundle types as well, like Image if you want to allow both images and SVGs in the same slot).
Go create a node,  and click the "Add media" link.
Notice that the Media Library loads with a vertical tab for each kind of media type bundle you enabled in step 7 on your node configuration screen.

If you're still on the fence about how to choose the right SVG media module from Drupal 8 contrib, you may find my comparison of the 3 modules helpful to guide your decision making:

https://drupal.stackexchange.com/a/280837/3167


how to save checkboxes values in node programmatically

i found the solution
:

  $aaz= array_filter($form_state['values']['wrapperrr']['id_offre']);
 foreach($aaz as $of)
   {

  //  $node->title = $form_state['values']['wrapperrr']['id_offre'][0]['value'];
   $node->field_offre[LANGUAGE_NONE][]['target_id'] = $of;

   }


It will sound silly but it can help you.
Go to /admin/config/search/clean-urls
you will get example.com/?=admin/config/search/clean-urls in your address bar
remove ?= from address bar so that your url become example.com/admin/config/search/clean-urls
press enter
Now you will get a check box
tick that box and save configration.

May this Helps you.


Nodewords: how do I use hook_metatags_default_values_alter?

Without ever having used that hook, I would suppose that you could do it very similar to the example in the documentation for hook_metatags_default_value_alter():

function hook_metatags_default_values_alter(&$values, $parameters) {
  if ($parameters['phase'] == 'post_load' && $parameters['type'] == NODEWORDS_TYPE_USER) {
    $values['og:latitude'] = 43.701536;
  }
}

For a better understanding it might be worth the effort to dig through the code of _nodewords_tag_value which seems to have the only invocation of the hook. You can see there, that it is invoked twice with a different $phase parameter. I think I would go for post_load, assuming that the defaults are not empty.

For the type parameter, you can see the available constants in the nodewords.module doc under constants. This value depends on where you want to alter the tag.

If the above code doesn't work, use dpm or something similar to inspect the $values that are passed in. That should give you enough information concerning the expected data.


How to load a variable through different nodeapi's $op?

At first sight, it looks like you would be better off implementing hook_form_alter, adding a custom validation handler. A form validation handler will give you access to the submitted values in $form_state as well as the previously stored values.


How do I send an email to the administrator users when a specific link is clicked?


Target Bundle with hook_element_info_alter

Bundles are defined in hook_entity_info(), so the complementary alter hook is hook_entity_info_alter()

Alter the entity info.
Modules may implement this hook to alter the information that defines an entity. All properties that are available in hook_entity_info() can be altered here.

hook_element_info_alter() is for altering form elements (which a bundle is not), so it can't be used in that context.


You can use this example from the node module.

This adds a body field when a content type is created and at the same time configures the display modes (view modes and form modes):

core/modules/node/node.module:

/**
 * Adds the default body field to a node type.
 *
 * @param \Drupal\node\NodeTypeInterface $type
 *   A node type object.
 * @param string $label
 *   (optional) The label for the body instance.
 *
 * @return \Drupal\field\Entity\FieldConfig
 *   A Body field object.
 */
function node_add_body_field(NodeTypeInterface $type, $label = 'Body') {
  // Add or remove the body field, as needed.
  $field_storage = FieldStorageConfig::loadByName('node', 'body');
  $field = FieldConfig::loadByName('node', $type->id(), 'body');
  if (empty($field)) {
    $field = FieldConfig::create([
      'field_storage' => $field_storage,
      'bundle' => $type->id(),
      'label' => $label,
      'settings' => ['display_summary' => TRUE],
    ]);
    $field->save();

    /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
    $display_repository = \Drupal::service('entity_display.repository');

    // Assign widget settings for the default form mode.
    $display_repository->getFormDisplay('node', $type->id())
      ->setComponent('body', [
        'type' => 'text_textarea_with_summary',
      ])
      ->save();

    // Assign display settings for the 'default' and 'teaser' view modes.
    $display_repository->getViewDisplay('node', $type->id())
      ->setComponent('body', [
        'label' => 'hidden',
        'type' => 'text_default',
      ])
      ->save();

    // The teaser view mode is created by the Standard profile and therefore
    // might not exist.
    $view_modes = \Drupal::service('entity_display.repository')->getViewModes('node');
    if (isset($view_modes['teaser'])) {
      $display_repository->getViewDisplay('node', $type->id(), 'teaser')
        ->setComponent('body', [
          'label' => 'hidden',
          'type' => 'text_summary_or_trimmed',
        ])
        ->save();
    }
  }

  return $field;
}

Edit: Code updated from 8.8.x to remove deprecated functions, see change record https://www.drupal.org/node/2835616

The field storage itself is not added or deleted because it is shared between all content types. You have to do this once when you install the module. The easiest way is to put a yml file for the storage in /config/install. Example from the node module:

core/modules/node/config/install/field.storage.node.body.yml:

langcode: en
status: true
dependencies:
  module:
    - node
    - text
id: node.body
field_name: body
entity_type: node
type: text_with_summary
settings: {  }
module: text
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: true
custom_storage: false


People are using this patch on latest media to multi-select media files on fields: https://www.drupal.org/node/951004#comment-9681531

Personally I had some problems to make it work at first, but finally I got it working (Had to disable admin_language module).


Can I clone a view but keep it independent of it's content?

Yes it is possible to duplicate a views as much as you need and edit them independently. It saves a lot of work and time.


How can I fetch the complete main navigation menu via JSON:API?

I did not get it to run with JSON:API, there are several long-standing issues...

However you can get it to run if you additionally install the REST Menu Tree module.

Be aware that this has several direct and indirect dependencies:

It has a direct dependency on Menu Normalizer and according to this issue you need to then activate that endpoint for example with the REST UI module - which in turn will activate the core REST module.

Then in your site activate the endpoint via the Rest UI in /admin/config/services/rest.

Afterwards you might also want to allow everyone to GET this endpoint via /admin/people/permissions#module-rest

And finally you get a JSON array in /entity/menu/main/tree.
Or query a different menu via /entity/menu/{internal_menu_name}/tree.


How to modify the image output for just one content type using Responsive Images?

The responsive image module creates these with a twig template called:
responsive-image.html.twig.

You have two options to change the output.  You can either copy this template from it's location under core/modules/responsive_image/templates to your theme.

Or you can use the hook_preprocess_responsive_image() in a module or your my_theme.theme file.

Basically, you will need to change the values in the source_attributes object. E.g. grab the value of the src attributes, delete it, and add your srcset attribute with the value of the src attribute.


Local server doesn't work, directly web on local server go to www

You probably have a full URL somewhere in your .htaccess file, in the root directory. Search for Rewrite directives.


well based on your comment:

Use the Computed Field module

  Computed Field is a very powerful CCK field module that lets you add a
  custom "computed fields" to your content types. These computed fields
  are populated with values that you define via PHP code. You may draw
  on anything available to Drupal, including other fields, the current
  user, database tables, you name it. (Feeling the power yet? :) ) You
  can also choose whether to store your computed field values in the
  database with other content fields, or have them "calculated" on the
  fly during node views. (Although you should note that Views use
  requires database stored values.) This field is literally the Swiss
  Army knife of CCK fields. So start cooking up your PHP based values!


Webform block: reload page with anchor link

You can achieve that by using the Webform Ajax module

This module adds AJAX support to Webform (3.0 and above).
As a first step it focusses to simply add form AJAX paging and submit. Form submissions get ajaxified including prev/next pages. Especially for multipage forms, this leads to faster loading (less data transfer), better usability and finally smaller server load.


How to get a flag counter for anonymous users?

The Session API module is required (a prereq) to make the Flag module functionality available for anonymous users (even with page caching enabled),

Consider checking out the great article about Enhancing the Anonymous User Experience: Adventures with Flags to get this to work.


Colorbox grouping content linked from same page - how to stop it?

I figured this out, with crucial help from the #Drupal IRC channel.

I was using Colorbox Node along with Colorbox, and I was confusing the documentation from the two of them. Specifically, Colorbox requires links to have the class colorbox-load while Colorbox Node requires that they have the class colorbox-node. The really confusing thing about this is that if you use colorbox-load instead of colorbox-node, it works, sort of. It was loading the entire page including headers, footers, and all markup and styles, into the modal, as if it were an iframe.

So step one was to start using the correct link class.

After changing the link class to colorbox-node, however, all I saw in the modal was the title of the target page, unstyled, on a white background. Poking around in the Colorbox settings was, unsurprisingly, unhelpful. Again, #Drupal pointed me in the right direction: Colorbox Node creates a display of the content type and makes the body hidden by default for some reason.

So step two was going to structure > content > [content type of target node] > manage display and choosing "Colorbox" (next to "Default" and "Teaser") to unhide the body of the target node.

Voilá, you now have the title and body pulled out from your target node and appearing isolated in your Colorbox modal.


Change the value of a field depending on the selection of another

Converting the element to a value type might be easiest:

// In a form alter hook.
$form['field_foo'][LANGUAGE_NONE][0]['value']['#type'] = 'value';
$form['field_foo'][LANGUAGE_NONE][0]['value']['#value'] = 'some static value';


How to exclude nodes with a taxonomy term from XML Sitemap?

You can use hook_xmlsitemap_element_alter() to check if the node has a particular taxonomy term & exclude it.

function MYMODULE_xmlsitemap_element_alter(&$element, $link, $sitemap) {
  // Check if link is a node link
  if ($link['type'] == 'node') {
    $node = node_load($link['id']);

    // Code to check if $node has taxonomy term goes here
    if ($node has taxonomy term) {
      $element['disabled'] = TRUE; // This removes the node link from sitemap
    }
  }
}


What ways to attach a library to a form?

Like explain by Clive, add libraries directly in the form via '#attached' parameter works. The mistake in my case was to don't send my form properly to my template file. See  Send a form to twig template


Drupal 8.0 to 8.1.8 upgradation is not working

The message is a notice not a error so updating of core just went on. So you core is now on the latest version.

You should however solve the error.


How to override a block generated by a module?

Have you copied block.tpl.php to your template directory as well? In Drupal 6 you need to have the base form before a more specific template will be used. For example before region-sidebar.tpl.php takes, you need region.tpl.php; before node-story.tpl.php, you need node.tpl.php. In D6 the block.tpl.php is in modules/system/.

I don't use D7, and it could've changed as David G. says.


How can a view page work with multiple word term name

In views, the multi-word term is a well-known active issue

issue #1027458: Allow to use multiple arguments with spaces
issue #1940206: term name contextual filter separator
issue #1977854: Transform dashes to spaces does not work still a problem

Solution 1:
You can use pathauto module to set up automatic aliases for your taxonomy terms.
Solution 2:
From views:

Choose "Specify validation criteria" in settings of Taxonomy Term Contextual filter.
Then Choose Taxonomy Term in Validator field.
Choose your Vocabulary.
Choose Term name converted to term ID in Filter Value Type Field.
Please see attached screenshots for solution 2:

Solution 3:
In views, you can create path aliases for term IDs by using view_alias module.


Ahhhh, found the problem!

I had to specify manually a redirect to the form:

$form['#redirect'] = ''; // Redirects to the home page

This way the validate and submit hooks are called appropriately and then it redirects to the home page.

Thank you all for all your replies. I appreciate it.

Cheers.


Menu Block (or custom menu display): expand immediate children of active item

Like we figured out in the comments the problem was that the "Expand all children of this tree" option was checked for the menu block. Without checking this the children will only be shown if the user is on a related page, which was the desired result.


How to direct a dynamic url to a Drupal page

i think that you can use the :
function drupal_goto

but not sure if that is for your case.


Call node information when rendering links

Assuming that you need to access to $node to populate the preview:

You will need to load the node object for access to $node. So lets say you extract the href from $variables, you wont be able to load node based on the url, atleast I dont know any function that does it. You will need to extract (php explode etc) node nid and then use node_load($nid) to load the $node object and then you can populate the preview based on a field of $node.

Where to write the code?

You can either override the theme function or use the preprocess, the preprocess for this should be (though not sure) yourtheme_preprocess_links__system_main_menu(&$vars) and theme override will be yourtheme_links__system_main_menu. I hope you understand the difference between theme function override and preprocess. I'd suggest preprocess to add preview in $variables and then overriding theme function to use that value. OR, you can build the preview and add it as an attribute to the link.

Hope that helps.


Dependency inject a class with values from a config object?

Not sure which part exactly is unclear. There are lots of examples in core.services.yaml that inject the config.factory service to read a configuration object, for example this:

diff.formatter:
  class: Drupal\Core\Diff\DiffFormatter
  arguments: ['@config.factory']

The constructor for that then looks like this:

/**
 * Creates a DiffFormatter to render diffs in a table.
 *
 * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
 *   The config factory.
 */
public function __construct(ConfigFactoryInterface $config_factory) {
  $config = $config_factory->get('system.diff');
  $this->leading_context_lines = $config->get('context.lines_leading');
  $this->trailing_context_lines = $config->get('context.lines_trailing');
}

Once you have the config object, you get the configuration you want and pass it along to the SoapClient constructor.


boolean function to determine whether an commerce order id exists?

There isn't a function that returns only a boolean, but commerce_order_load() returns FALSE if no order is found so you can use it in an if statement quite happily:

if (commerce_order_load($order_id)) {
  // Order exists
}

If you want to be bit more militant about it you could use this:

if (commerce_order_load($order_id) !== FALSE) {
  // Order exists
}

But it shouldn't really make a difference.


Have you tried deleting the styles folder? The folder and everything below it should be created automatically by Drupal.


Is there a way to see what parts are not in a feature?

2 options:

Using Drush, the following command will show you all the Features Components which aren't already claimed by a Feature:

drush features-components % --not-exported

You can install the Features Orphans module, which provides a list of unclaimed Features Components using Drupal's web interface.


how do I make rounded borders around everything in a drupal 7 site?

Not every browser has border-radius implemented yet. Use vendor prefixes for those.

.box_round {
     -moz-border-radius: 12px; /* FF1-3.6 */
  -webkit-border-radius: 12px; /* Saf3-4, iOS 1-3.2, Android <1.6 */
          border-radius: 12px; /* Opera 10.5, IE9, Saf5, Chrome, FF4, iOS 4, Android 2.1+ */

  /* useful if you don't want a bg color from leaking outside the border: */
  -moz-background-clip: padding; -webkit-background-clip: padding-box; background-clip: padding-box;
}

Snippet from: http://css3please.com/


What are the effects of the "access commerce administration pages" permission

Does it do nothing alone and only work if other permissions are added?

Currently, yes (although that could theoretically change in the future).
The permission is added to all HTML admin routes for the order entity type (add/edit/etc), and for admin overview pages, which essentially list sub-pages that the user has access to.
If the user doesn't have access to those sub-pages, all provided by separate permissions, they won't see the links, and won't be able to visit them. Similarly, if they don't have the correct entity access permission, they won't be able to perform the respective operation on the entity.


Using Drupal to authenticate user on a remote web site

The tutorial does not indicate that you must enable the user resource in the rest service you set up.  Doing so allows it to work.


I would suggest using Media as your starting point, and improving it if needed. That's the D7 solution aiming to solve similar problems to the File Framework (and other D6 modules).


Validation error, please try again. If this error persists, please contact the site administrator

The form token associated to forms created with the form API is a value that is used to verify the data are submitted from a user who filled a module form, and not forged data.

The drupal_valid_token() function that validates the token is validating it using the user session; this means that, if the user session used when the data are being submitted is different from the session used when the form was created, the validation of the token fails.
This could happen also when a module calls session_destroy().


In Commerce 2, how can we allow users with a role to bypass payment during checkout (bill me later)

You can enable the "Commerce Payment Example" module that comes with commerce2. From there on, go to commerce->settings->payment->payment gateways and add a new payment gateway. Choose the "Manual" plugin and set the proper roles on the bottom and you should be done.


Override view-list and get items properties

This is the default template for a views-view-list.html.twig. Basically you've overwritten this template when you've created views-view-list--content-recent--block-1.html.

{#
/**
 * @file
 * Default theme implementation for a view template to display a list of rows.
 *
 * Available variables:
 * - attributes: HTML attributes for the container.
 * - rows: A list of rows for this list.
 *   - attributes: The row's HTML attributes.
 *   - content: The row's contents.
 * - title: The title of this group of rows. May be empty.
 * - list: @todo.
 *   - type: Starting tag will be either a ul or ol.
 *   - attributes: HTML attributes for the list element.
 *
 * @see template_preprocess_views_view_list()
 *
 * @ingroup themeable
 */
#}
{% if attributes -%}

    {% endif %}
    {% if title %}

{{ title }}

    {% endif %}

    <{{ list.type }}{{ list.attributes }}>

    {% for row in rows %}

{{ row.content }}

    {% endfor %}

</{{ list.type }}>

{% if attributes -%}

{% endif %}

What you could do is try adding something like this inside your "for" loop:

{% set item = row.content['#view'].style_plugin.render_tokens[ loop.index0 ] %}
{{ item['{{ title }}'] }}
{{ item['{{ field_date }}'] }}


Why am I getting an error message in my dashboard for unprotected private files?

The error, which is reported by system_requirements(), means that either that directory doesn't contain any .htaccess file, or that .htaccess file doesn't contain the following lines.
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

Together the lines added from a previous security advisory, they avoid files in that directory can be executed.
# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

Before showing that error message, Drupal tries to create the .htaccess file. (See HtaccessWriter::write().) If it's not able to create it, or write into that file, you should manually create the .htaccess file containing the following lines.
# Deny all requests from Apache 2.4+.
<IfModule mod_authz_core.c>
  Require all denied
</IfModule>

# Deny all requests from Apache 2.0-2.2.
<IfModule !mod_authz_core.c>
  Deny from all
</IfModule>

# Turn off all options we don't need.
Options -Indexes -ExecCGI -Includes -MultiViews

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php7.c>
  php_flag engine off
</IfModule>

The same lines are shown in the error message contained in the Drupal log.


Contextual Filters On Block of News Items

Whenever you need to pass a parameter into a View, one should immediately think "Contextual Filter" - in this case, one should exist for field_channel_section. Note that blocks don't pass their parameters along the URL by default (as with pages), so you will need to set a default value for the filter criterion based on the URL yourself. Thankfully, this can be done by supplying the default value using PHP in the Contextual Filter settings. The particulars depend on what type of field field_channel_section is. If you could clarify, I'd be happy to do the same.


increase users to display in who is new block

You have two options I see:

Recreate this block with Views - changes like that are the very sense of their existence.
Create custom module with hook_form_alter() and add numbers up to some arbitrary max you prefer. Note that it might be a performance hit that way, if block in question loads full user objects. To much and you'll eat your memory.


Assign new customer with specific user role upon checkout registration

Surely If someone creates the order the the order is associated to that user, so in this case you don't need to wory about user being created, what you can do is look in to:

hook_ENTITY_TYPE_update()

this way your going from the order status being upgraded to paid or whatever I dont know what the entity name for the order is but you could grab that loaded it, get the user id and check the roles , if no role add new role to them and save. as a bonus you have more control over what type of products to restrict it to ect.


custom node type that save to a custom table

You're probably best off if you use the Feeds module to import your data into Drupal. Messing with the database configuration yourself just because you "don't like that" a lot of tables would be generated seems like a lot of work for not much potential benefit.

If you're worried about filling up the Drupal database, it is possible to use one database for Drupal's content and configuration, and another for data that you're using Drupal to expose to users. D7 boasts master/slave database configuration support. It is also possible to integrate with databases that Drupal does not support for its main configuration database, e.g. Mongo.


How to add revisions tab to a custom content entity and list revisions?

To support revisions, the annotation used for the entity class needs to:

Declare the revision tables
/**
  *   revision_table = "node_revision",
  *   revision_data_table = "node_field_revision",
  */

Tell Drupal to show the revision UI
/**
  *   show_revision_ui = TRUE,
  */

Tell Drupal which fields in the database match the revision entity fields
/**
  *   entity_keys = {
  *     "id" = "nid",
  *     "revision" = "vid",
  *     "bundle" = "type",
  *     "label" = "title",
  *     "langcode" = "langcode",
  *     "uuid" = "uuid",
  *     "status" = "status",
  *     "published" = "status",
  *     "uid" = "uid",
  *     "owner" = "uid",
  *   },
  *   revision_metadata_keys = {
  *     "revision_user" = "revision_uid",
  *     "revision_created" = "revision_timestamp",
  *     "revision_log_message" = "revision_log"
  *   },
  */

In the links section, tell Drupal which links are for the revisions
/**
  *   links = {
  *     "canonical" = "/node/{node}",
  *     "delete-form" = "/node/{node}/delete",
  *     "delete-multiple-form" = "/admin/content/node/delete",
  *     "edit-form" = "/node/{node}/edit",
  *     "version-history" = "/node/{node}/revisions",
  *     "revision" = "/node/{node}/revisions/{node_revision}/view",
  *     "create" = "/node",
  *   }
  */

(I used the annotation used from the \Drupal\node\Entity\Node class to show which keys needs to be used and as example of values to assign to those keys.)
Then the module implementing the entity must define the routes used for the revision pages. The Node module does it in the node.routing.yml file, but the route_provider class (which implements EntityRouteProviderInterface) could define them too.
entity.node.version_history:
  path: '/node/{node}/revisions'
  defaults:
    _title: 'Revisions'
    _controller: '\Drupal\node\Controller\NodeController::revisionOverview'
  requirements:
    _access_node_revision: 'view'
    node: \d+
  options:
    _node_operation_route: TRUE

entity.node.revision:
  path: '/node/{node}/revisions/{node_revision}/view'
  defaults:
    _controller: '\Drupal\node\Controller\NodeController::revisionShow'
    _title_callback: '\Drupal\node\Controller\NodeController::revisionPageTitle'
  requirements:
    _access_node_revision: 'view'
    node: \d+

node.revision_revert_confirm:
  path: '/node/{node}/revisions/{node_revision}/revert'
  defaults:
    _form: '\Drupal\node\Form\NodeRevisionRevertForm'
    _title: 'Revert to earlier revision'
  requirements:
    _access_node_revision: 'update'
    node: \d+
  options:
    _node_operation_route: TRUE

node.revision_revert_translation_confirm:
  path: '/node/{node}/revisions/{node_revision}/revert/{langcode}'
  defaults:
    _form: '\Drupal\node\Form\NodeRevisionRevertTranslationForm'
    _title: 'Revert to earlier revision of a translation'
  requirements:
    _access_node_revision: 'update'
    node: \d+
  options:
    _node_operation_route: TRUE

node.revision_delete_confirm:
  path: '/node/{node}/revisions/{node_revision}/delete'
  defaults:
    _form: '\Drupal\node\Form\NodeRevisionDeleteForm'
    _title: 'Delete earlier revision'
  requirements:
    _access_node_revision: 'delete'
    node: \d+
  options:
    _node_operation_route: TRUE

The entity class should also extend EditorialContentEntityBase, a base entity class with extended revision and publishing support. Using it, adding the revision and publishing fields is simple as adding $fields = parent::baseFieldDefinitions($entity_type); to the baseFieldDefinitions() method of the entity class.


You need to read this article:
Multi-site - Sharing the same code base
https://www.drupal.org/docs/7/multisite-drupal/multi-site-sharing-the-same-code-base

Create directories for your each site
Copy config files to each directory
Create a database for each site
Make a symbolic link for each site:

$ ln -s . site1
$ ln -s . site2


How include hash (#) in drupal_goto path?

For Drupal 6,

It should be 3rd parameter

drupal_goto($path = '', $query = NULL, $fragment = NULL, $http_response_code = 302)

drupal_goto("products", NULL, $node->nid);

For Drupal 7

drupal_goto($path = '', array $options = array(), $http_response_code = 302)
drupal_goto("products", array('fragment' => $node->nid));


I need to remove manually a display from a view

You can always try, you could also try to delete the display from the 'views_display' table, in any case make sure to do a complete dump of your database so you may restore it if anything goes wrong=)


Thank you to Alyssa Gono for solving this. She did it in a comment, so I can't formally credit her with the correct answer. But I'll lay out here what happened.

I thought at first that couldn't be it. How could a cookie be interfering with the analysis of the login credentials? But I was so frustrated by this problem that I decided to give it a try. I work in Firefox, so first I loaded IE, and logged in there, and it worked! Then I went back to Firefox and looked at my cookies. Rather than deleting them all, I looked for cookies from localhost. There were about 20 of them. I deleted those and bam! I was able to log in!

This was with the credentials "hello" and "there" set in the update above. So next I undid the changes described in that update by resetting the credentials back to the intended ones. Went back to the site, logged out and logged back in with those credentials and Wow! Problem solved.

Now I can finally get to work on developing my sites.

I'm going to submit a bug report at Drupal because it would be helpful if the sw could let the user know that a cookie is blocking the login. If it can't detect that, at least it would be helpful to suggest clearing cookies if one believes the login should be working and isn't.

Can someone explain how it is that a cookie interferes with the analysis of the login credentials?

Thank you again to Alyssa.


Shopping cart is not updated after add to cart when you select an attributes

Here is where I would do like the big stores, and add a separate line item (product) for the warrantee add-on where you you can have two variations of it, one for $100 add-on value, the other for $200 add-on and then in the product display page you can have a customer select which option if any to select, which will then be itemized in the cart by itself with its own description. If you want you can also have a product display page or just a page for the two to them. It would be a product type by itself, with variations as opposed to color terms describing variations of a cell phone.
And it might be easier on cart space.
And Warrantee variations are products that can be related by name.
You end up with less sku products: The cell phone product color variations, and the Warrantee two variations.


Programmatically accessing field values for a file in a custom form

Since the values array is a protected value, you can only access its value with a method (e.g. a magic method).

The File class extends ContentEntityBase, from which it gets the values property and the magic method that allows to access it. Supposing that $file is the variable containing an \Drupal\file\Entity\File object, you just need the following code.

$destination = $file['destination'];

Longer Explanation

The method that allows to access the content of the values array is ContentEntityBase::__get() (a magic method) that allows to access the value of an object as it would be an array. ContentEntityBase::__get() checks also the content of the values array; in fact it contains the following code.

  // Else directly read/write plain values. That way, non-field entity
  // properties can always be accessed directly.
  if (!isset($this->values[$name])) {
    $this->values[$name] = NULL;
  }
  return $this->values[$name];

So, using $file['destination'], that method would return you the value of $file->values['destination'] you cannot directly access.


You should make a view that lists the terms in your node (use contextual filters) and add the image fields you added to that term.

Create a node view that lists the node type that the categorized nodes come from.
Add the fields used to categorize the nodes.
Remove any other fields.
Add a contextual filter for the node id (Content:Nid).
Configure the contextual filter to have a default value and choose the 'id from url' option.
If you add that block to a region, it should show a list of terms associated with a node.
Now add the image field from the term, if you don't see that field you might need to add a relationship to that term field.


Not able to make simple node path show up in "crumbs module"

What is the path you want to link to for "Content type" ? Do you have e.g. a view at this url?

You need to have something at this url, and Crumbs needs to be able to determine a title at this url. Otherwise it won't appear in the breadcrumb.

So, what you can do:

Create a view at path "events" or "news" or whatever.
Let the title of the view be "Events" or "News". There are two ways to do this:

In the Views admin, "Page settings", click "Menu", and set it to something where you can specify a title. OR
Choose your favourite menu, and create a link to the Views page.
It is NOT enough for the view to have a title by itself. It needs to have a title in the menu/routing system. (*)

In Crumbs "Entity parent" settings, set "events" or "news" as the parent path for the respective node type.

There are other ways to create a parent page like "news" or "events". For instance, I like to use a "page" content type with a "blockreference" field to embed a views block.

(*) Maybe I should create a plugin that uses the real page title of the View as the title of the breadcrumb link.


How to make sure that panels classes are added to a CTools pane?

In the following function, the content is provided by t(). t(), when called, returns the text "my sample text". Because that text gets assigned to $block->content, the pane is rendered with "my sample text" as the content.

function MYMODULE_messagelimits_content_type_render($subtype, $conf, $args, $context) {
  if (!empty($conf)) {
    $block = new stdClass();
    $block->title = check_plain("");
    // Show message limits.
    $block->content = t("my sample content")
    return $block;
  }
}

By contrast, this function:

function MYMODULE_messagelimits_content_type_render($subtype, $conf, $args, $context) {
  if (!empty($conf)) {
    $block = new stdClass();
    $block->title = check_plain("");
    // Show message limits
    $block->content = MYMODULE_show_message_limits();
    return $block;
  }
}

Assigns the return value of MYMODULE_show_message_limits() to $block->content, rendering the pane with that function's return value. To understand why that doesn't work as expected, we must ask, what does MYMODULE_show_message_limits() return?

if ($sent_total > 1) {
  print '
';
  print t('You have already started conversations with 2 people this week.') . '
';
}
else if ($sent_total == 1) {
  print '
' . t('You can start a conversation with 1 more new person this week.') . '
';
}
else {
  print '
' . t('You can start conversations with 2 new people this week.') . '
';
}

The function above, lacks a return statement, so in pratice, it returns NULL. Hence the pane output is empty, not even an empty string.

MYMODULE_show_message_limits() does, on the other hand, execute several print calls. Since that happens at a stage when content is still being assembled, remember, this is not a template, the prints are thrown right out onto the page, in the same way it would have if it was executed in any hook invocation for example.

The solution then, is to do:

$output = '';
if ($sent_total > 1) {
  $output .= '
';
  $output .= t('You have already started conversations with 2 people this week.') . '
';
}
else if ($sent_total == 1) {
  $output .= '
' . t('You can start a conversation with 1 more new person this week.') . '
';
}
else {
  $output .= '
' . t('You can start conversations with 2 new people this week.') . '
';
}
return $output;


How to dynamically populate the condition method argument in a Dynamic Query

If anyone ever need that i got an answer there.

http://drupal.org/node/12843

This is useful as well :

https://stackoverflow.com/questions/7476611/how-to-write-a-query-with-a-dynamic-where-clause


I assume you are using imagecache_actions module. I enabled imagecache_canvasactions module too that comes with imagecache_actions module.

Once i enable above mentioned modules, i can able to see offset for X & Y while adding Underlay (Background Effect) . See screenshot below. I set offsets to 50 & 40 see the style in action in second image.