Add all the fields to view automatically in csv export I am using entity registration module for node registration.Now i wants to export the registrants.

I am using view export module to export registrants list. Its working fine

But as the registration fields is different per node i can not add a fix number of field to export.

I am trying to use global php field, its working for single column.

Is there any alternatives?

What other i have tried?

function paticipant_export_views_pre_view(&$view, &$display_id, &$args) {
          if ($view->name == 'paticipants_export') {
            views_db_object::add_item($view->current_display, 'field',
    'field_data_field_first_name_1', 'field_first_name_1',
$options = array(
            $handler->display->display_options['fields']['field_first_name_1']['id'] = 'field_first_name_1',
            $handler->display->display_options['fields']['field_first_name_1']['table'] = 'field_data_field_first_name_1',
            $handler->display->display_options['fields']['field_first_name_1']['field'] = 'field_first_name_1',

            ), $id = NULL);

          }
        }

Thanks for your suggestion.

This might be a really stupid suggestion but why dont you just edit the view and add all the registration fields manually. The view will have empty cells for fields thats not a part of the registration type at a specific row, but thats something you'll get anyways.

Another way to go is to skip views alltogether and export data with a module of your own using the entity api. You aparently are writing a module to override view fields above so you have already started down that road (so to speak)


How to set newest first in the view of content created How to set newest first in view of content created. So far I have created a view for content type and now it's displaying created new content on last page but I want to set in first page. Can anyone help?

Under Sort Criteria section, add field Content: post date and set it's configuration as descending as shown in image below.


Example of writing Latitude Longitude to a Geofield? I need to write a lat/lon value to a Geofield and I can't figure out how to set the field. I would prefer to do this using EntityMetadataWrapper.

And the answer:

    $entity_metadata_wrapper = entity_metadata_wrapper('node', $node_object);

    $data = array(
       'lat' => 44,
       'lon' => -93
    );

    $entity_metadata_wrapper->field_position->set($data);


Duplicate Website with different theme? I would like to create a duplicate of my existing website (includes all content) and apply a different theme.

So for example I would have www.widgets.com with one theme & products.widgets.com with the same content but a totally different theme.

Also, when I add/update/delete content in www.widgets.com I would like it to change in products.widgets.com.

What's the best way to accomplish this? I'm using Drupal 6.

Thanks-in-advance

You could take a look at themekey module.

  ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties.

One other property is "host", which would fit into your demands, although this wouldn't be actually a copy of your site. Instead you would just switch the theme on another domain. (On a side note you should consider avoiding "duplicate content" for better serach results.)


How do I create multiple blocks? I would like to create multiple blocks using the data rendered from the variable table in Drupal 8. I was able to achieve it in Drupal 7, but I can't find a way to do the same in Drupal 8.

The code I use for Drupal 7 is the following.

/**
 * Create a block that will display the calendar feed
 * Implements hook_block_info
 */
function my_module_block_info() {
  $blocks = array();
  $block_urls = variable_get('my_module_content');
  $block_regions = variable_get('my_module_content_block_region');
  $number_of_blocks = count($block_urls);
  if ( $number_of_blocks > 0 ) {
    foreach ( $block_urls as $key => $block_url ) {
      $blocks['eventblock-' . $key] = array(
        'info' => t('my_module_widget_block_' . $key),
        'status' => TRUE,
        'region' => $block_regions[$key],
        'cache' => DRUPAL_NO_CACHE,
      );
    }
  }
  return $blocks;
}

/**
 * Render the my_module block
 * Implements hook_block_view
 */
function my_module_block_view($delta = '') {
  $block = array();
  $block_urls = variable_get('my_module_content' , array());
    foreach ( $block_urls as $key => $block_url ) {
      switch ($delta) {
        case 'eventblock-' . $key:
          $widgetURL= $block_urls[$key];
          $block['content'] = my_module_content_generate($widgetURL); // Some function to generate block content.
          break;
        }
    }

  return $block;
}

In order to create blocks dynamically in Drupal 8, you will have to define a plugin derivative. Plugin Derivatives.

This way you can create multiple instances of the same block. Hope this helps.

Block Derivatives Example

Remember to respect the folder structure when creating your derivative and block class.

Derivative

<?php

namespace Drupal\YOUR_MODULE_NAME\Plugin\Derivative;

use Drupal\Component\Plugin\Derivative\DeriverBase;

class YOUR_DERIVATIVE_NAME extends DeriverBase {

/**
 * {@inheritdoc}
 */
public function getDerivativeDefinitions($base_plugin_definition) {
// @todo might as well include your configuration here and assign a value.
  $block_urls = ['1', '2', '3'];

  foreach ($block_urls as $block_url) {
    $this->derivatives[$block_url] = $base_plugin_definition;
    $this->derivatives[$block_url]['admin_label'] = 'Sample Label ' . $block_url;
  }

  return $this->derivatives;
  }

}

Block

<?php

namespace Drupal\YOUR_MODULE_NAME\Plugin\Block;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Session\AccountInterface;

/**
 * Provides a block.
 *
 * @Block(
 *   id = "YOUR_BLOCK_ID",
 *   admin_label = @Translation("YOUR_BLOCK_ID"),
 *   deriver = "Drupal\YOUR_MODULE_NAME\Plugin\Derivative\YOUR_DERIVATIVE_NAME"
 * )
 */

class YOUR_BLOCK_NAME extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $id = $this->getDerivativeId();

    $build = [
      '#markup' => $this->t('Your Block Content with ID' . $id),
    ];

    return $build;
  }

  /**
   * {@inheritdoc}
   */
  protected function blockAccess(AccountInterface $account) {
    return AccessResult::allowedIfHasPermission($account, 'access  content');
  }

}

Rename YOUR_MODULE_NAME, YOUR_BLOCK_NAME, YOUR_BLOCK_ID, YOUR_DERIVATIVE_NAME accordingly.


Error while altering js file Undefined index: scope in drupal_get_js() (line 4309 I need to change javascript code of jCarousel, and I want to create my own function and change it in hook_js_alter(), but it is not working properly, or I missing something.

function common_js_alter(&$javascript) {
  if ($node = menu_get_object()) {
    if ($node->type == 'home') {
      if (array_key_exists('sites/all/libraries/jquery.jcarousel/lib/jquery.jcarousel.js', $javascript)) {
        $file = drupal_get_path('module', 'common') . '/js/jcarousel.js';
        $javascript['sites/all/libraries/jquery.jcarousel/lib/jquery.jcarousel.js'] = drupal_js_defaults($file);
        dpm($javascript);
      }
    }
  }
}

I need to change sites/all/libraries/jquery.jcarousel/lib/jquery.jcarousel.js to drupal_get_path('module', 'common') . '/js/jcarousel.js'. The path is correct, but as I can see with dpm() no scope is enabled and type.

Just got into this function too to alter "folder/js_file.js" and the issue causing the

  Notice: Undefined index: scope in drupal_get_js() (line 4309 of
  [DRUPAL_DIR]\includes\common.inc).

error is that there are times when the hook is called but "folder/js_file.js" is not yet in the array w/c just adds

[folder/js_file.js] => Array(
  [data] => [your_custom_js],
)

to the array but the scope, type, and other attributes are not there. So we first need to check if the array key exists like so:

if (isset($javascript['folder/js_file.js'])) {
  $file = drupal_get_path('module', 'mymodule') . '/your_custom_js.js';
  $javascript['folder/js_file.js']['data'] = $file;
}

That solves it. :)


Remove "pubdate" attribute from Submitted Time tag in Drupal 7 Currently when a node or comment is submitted it gets a Submitted text saying "Submitted by user on Wed, 04/01/2015 - 18:07"

The mark-up for this is:

Submitted by *user* on <time pubdate="pubdate" datetime="2015-04-01T18:07:34+0000">Wed, 04/01/2015 - 18:07</time>

What I need to do is remove the "pubdate" attribute from the tag because the it is failing on W3C validation.

I have tried to add the following code in my template.php file but had no luck

function ThemeName_preprocess_node(&$variables) {
    $attributes['datetime'] = '<time'.drupal_attributes($attributes) .'>'.$variables['date'] . '</time>';
}

How can I remove the "pubdate" attribute in the Submitted by tag?

So `$variables['submitted'] is the one you want to override in your theme's preprocess_node function. Try this as a starting point:

function ThemeName_preprocess_node(&$variables) {
  $variables['submitted'] = t('Submitted by !username', array('!username' => $variables['name']));
}

Which will replace the $submitted variable with "Submitted by username" (where the username will be linked to the user's profile page).


Nightly truncating all cache_* tables? Good or bad? I'm having some issues on various D7 sites with some cache tables growing stupidly large (e.g cache_metadata or cache_menu) which then makes drush cc all very slow (more than 1 minute).

Do you think that there is any problem if I setup a nightly linux cronjob which will be truncating cache and cache_* tables apart from cache_form? And after that I plan on executing a drush cc all for safety.

p.s I do not plan on investigating and trying to fix the root cause that makes those tables grow large.

Cron job to truncate the tables might cause some metadata locks due to the TRUNCATE command being a DDL statement; depends on how busy your server is. What APDQC does is a table rename swap and then truncate; if you did something similar then you should be ok. APDQC will also use gzip to make the table sizes smaller; something that would be a benefit in your case. Without compression our DB cache tables would take about 50GB, they now take about 12gb.


What causes the error "Call-time pass-by-reference has been deprecated?" My understanding is that objects in PHP 5.3 are all passed by reference so using the &$ notation is not necessary. My problem is using date_views module where I'm getting this error.

Deprecated function: Call-time pass-by-reference has been deprecated in
 _registry_check_code() (line 2701 of C:\wamp\www\cruzr\includes\bootstrap.inc).

The affected lines of the code are:

  // $type is either 'interface' or 'class', so we only need the first letter to
  // keep the cache key unique.
  $cache_key = $type[0] . $name;
  if (isset($lookup_cache[$cache_key])) {
    exit;
    if ($lookup_cache[$cache_key]) {
      require_once DRUPAL_ROOT . '/' . $lookup_cache[$cache_key];
    }
    return (bool) $lookup_cache[$cache_key];
  }

How do I test if a variable is passed by reference? With several classes being loaded how do I approach debugging this problem?

The cause of the "Call-time pass-by-reference has been deprecated in
 _registry_check_code()" is a file that holds a class being loaded that contains a variable that is passed by reference that is not in a function definition.

Drupal 7 requires PHP 5.2 or higher and PHP 5 always passes objects into functions by reference

This was a difficult bug to find because enabling a feature of the Date Views module is what triggered it. However, the problem was in the Workbench Moderation module. What I did was set the breakpoint in the debugger on function drupal_set_message() then worked back through the call stack till I found the offending variable.

Problem was not exactly in the Date module but was nonetheless triggered by the Date module in line 53 of date_views_fields.inc.

// If we don't have a filter handler, we don't need to do anything more.
if (!$handler = views_get_handler($table_name, $field_name, 'filter')) {
  continue;
}

This would iterate through all the view's handlers including workbench_moderatioin_handler_filter_user_can_moderate which passed a variable by reference not in a function definition,     parent::options_form(&$form, &$form_state);. Simply the Workbench moderation module needs to be patched to reflect changes in code in PHP 5.3


views_query_alter Matching all values in IN clause I have a content type with a list(text) field. In which the admin can set multiple values on the field for the content type. Using a view the information is exposed to the end user. The views has a exposed filter to filter the list(text) field. However multiple options can be selected and need to be checked against the values set by the admin. The way Drupal views does this is by joining the table as many times as the amount of values being searched for, resulting in a very slow query.

I am now looking to do this with the query adjustment below inspired by this post:
https://stackoverflow.com/questions/11636061/matching-all-values-in-in-clause

However I have no clue on how to include the HAVING combined with COUNT as suggested in de post from the link above within Drupal.

$field_values - array(1, 4)
$query->where[1]['conditions'][0]['field'] = 'field_data_field_listtext.field_data_field_listtext_value';
$query->where[1]['conditions'][0['value'] = $field_values;
$query->where[1]['conditions'][0['operator'] = 'IN';

Suggestions on solving the SQl query performance in other maners for exposed filters on list(text) are also very wecome.

The following code should allow you to add the SQL code found in the accepted answer to the S.O. post you mentioned to the Views generated SQL code.

function YOUR_MODULE_views_query_alter(&$view, &$query) {
    if ( $view->name == 'YOUR_VIEW_NAME' ) {
        $value_count = 0;

        // Collect the number of selected values in the exposed filter
        foreach($query->where[1]['conditions'] as $key => $condition) {
            if ( $condition['field'] == 'field_data_field_listtext.field_data_field_listtext_value' ) {
                $value_count = sizeof($query->where[1]['conditions'][$key]['value']);
                break;
            }
        }

        // Add the having expression
        if( $value_count > 0 ){
          $query->add_having_expression(
            0,
            "count(distinct :field_name) = :value_count",
            array(
              ':field_name' => 'field_data_field_list_select.field_list_select_value',
              ':value_count' => $value_count
            )
          );
        }
    }
}

Good luck!


Construct POST data and send it to an external page Is there any way to construct post data and send it to an external URL, like how a form will send POST data to action URL?

I am aware of drupal_goto() function, but it is not possible to send POST data using it. I am also aware of drupal_http_request(), but I do not want a response from the URL here. I just want to submit data to the URL from my custom module. How can I achieve this? Any help is appreciated.

This is a PHP question, really. But here's an answer: http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl/

Many many caveats; read the comments.


Immediately delete managed files I have a use case (in D8) where file and corresponding directory needs to be deleted from the file system. The standard mechanism suggested by Drupal is to mark file as temporary and let cron take care of deletion. This means, in my case, that I need to keep track of the file deletion and only then delete the corresponding directory, if it empty. This can be easily avoided by simply using file_delete().

Why is this method not recommended?

The standard cron based deferred deletion causes other side effects with file replacement, etc.

Why is this method not recommended?

The function comments do give a nod to the reason:

  Instead of directly deleting a file, it is strongly recommended to delete file usages instead. That will automatically mark the file as temporary and remove it during cleanup.

But perhaps the "file usage" part of that could have been expanded upon, if you're not aware there's proper reference tracking going on it could be confusing...

Put simply, multiple entities/things can reference a single file. Those references are stored as file usage records, which are consulted when the system wants to know if it's safe to delete a file. If a record exists, for the target file, it can't be deleted without breaking a link, so the system doesn't do it.

Rather than go through that process of checking usage then deleting every time a file is dereferenced, the system batches it up on a cron job for convenience.

If it's not convenient for your use case, and you are comfortable that the file delete is 'safe' with the above in mind, then you can happily ignore the recommendation and use file_delete directly.

If you do, make sure you clear up the file usage records at the same time, or you might end up with inconsistent data some time down the line.


Php function to clear cache for regions I made a custom module, in which I dynamically add regions. The thing is, I want to make just the region part of the cache to refresh after. So drupal_flush_all_caches(); isn't the solution, since this takes too long, as well as it sometimes crashes the site.

Could anyone tell me which function I need to specifically clear the region/blocks cache? I tried all logical functions from the drupal_flush_all_caches(); function. I also couldn't find the right call from cache_clear_all();.

Any help would be appreciated.

You are looking for cache_clear_all. You want to set first argument $cid to NULL, as you want expire all your objects. Now you only need to figure second argument, $bin. For sure you have to clear cache_page bin. If it's not enough, look inside your database for cache_% tables (where % means any string, per SQL standard) to know what bins are available to you.

Last but not least, dynamic regions may be huge performance hit. Think twice if that's what you really need.


How do I tell Drupal not to aggregate my css file I have enabled Drupal's Aggregate and compress CSS files. What should I do in order to exclude certain css files from being aggregated and compressed?
Thanks.

To stop a file being aggregated, you can add a flag to the drupal_add_css() command which loads the file. To do this, hunt where the CSS is added and add array('preprocess' => FALSE) after the style, e.g.

drupal_add_css('/fonts/fonts-min.css', array('preprocess' => FALSE));

Alternatively, external CSS are never compressed, so if you change the CSS to the absolute URL of the file it won't be compressed.

drupal_add_css('http://mysite/css/fonts-min.css');

If you want to change a CSS included from a .info file, it might be best to add it as an external file with _preprocess_html in template.php. This is well explained under 'Adding external stylesheets' on this page.


How do I remove the classes from the pager item-list in Drupal 7? I am in a Drupal 7 theme development where we need to over write the pager theme where the class "item-list" needs to be removed.

My current item-list HTML

« first

‹ previous

1

2

3

next ›

last »

And I need something like this

« first

‹ previous

1

2

3

next ›

last »

To override the markup of the pager, override the theme_pager() theme function.

However in your case you want to override the class in the item list so for that you need to also override theme_item_list().

For information on overriding theme functions see the beginners guide to overriding themeable output, and for more thorough drupal themeing information see themeing drupal 6 and 7


Delete user account after checkout completion Im trying to create a rule that deletes an user account after checkout completion for New users, but it is not working. Can anyone please help me to figure out what is wrong? after checkout completion, check if user is not admin or any other role, then delete the account. After anonymous checkout, an user account is created (blocked, registered).

{ "rules_delete_user_account_after_checkout" : {
  "LABEL" : "Delete User Account after Checkout",
  "PLUGIN" : "reaction rule",
  "WEIGHT" : "3",
  "OWNER" : "rules",
  "REQUIRES" : [ "rules", "php", "uc_cart" ],
  "ON" : { "uc_checkout_complete" : [] },
  "IF" : [
    {
      "NOT data_is" : {
        "data" : [ "order:customer:roles" ],
        "value" : { "value" : { "3" : "3" } }
      }
    }
  ],
  "DO" : [
    { "php_eval" : { "code" : "\/\/ Delete the user.\r\nuser_delete(NULL, [order-uid]);" } }
  ]
}}

Deleting a user after checkout is a bad idea. I assume you know this, but the client is asking/forcing you to do this.

check this link - automatically delete all Ubercart-created users,  this has a solution.


ajax_command_invoke addClass changes lost after form validation I am currently trying to build a form which has a series of select elements, each of which triggers display of a textarea specific to that select element which is initially hidden.

Currently the select element has a callback to a function which is using ajax_command_css (to toggle the view of the textbox) and also ajax_command_invoke to add a class to the textbox so that it is still shown after validation errors are triggered. Currently after a validation event, the classes added using this method are lost so the textboxes remain hidden.

Select and textareas are created like this:

$form['2og_select'] = array(
    '#prefix' => $blurb,
    '#title' => t('2OG'),
    '#type' => 'select',
    '#options' => array(
      t(' '),t('1'),t('2'),t('3'),t('4'),t('5'),
    ),
    '#ajax' => array(
      'callback' => 'show_comments_js',
      'event' => 'change',
      'effect' => 'fade',
      'progress' => array(
        'message' => '',
        'type' => 'throbber',
      ),
    ),
  );
  $form['2og_textarea'] = array(
    '#type' => 'textfield',
    '#maxlength' => 512,
    '#suffix' => ('

'),
    '#attributes' => array(
      'class' => array('comments'),
    ),
  );

Callback function looks like this:

function show_comments_js($form, &$form_state) {

  $commands = array();

  $triggerName = $form_state['triggering_element']['#name'];
  $triggerValue = $form_state['triggering_element']['#value'];

  $name_bits = explode('_',$triggerName);
  if ($triggerValue != '0') {
    $commands[] = ajax_command_css('#edit-' . $name_bits[0]  . '-textarea', array('display' => 'inline'));
    $commands[] = ajax_command_invoke('#edit-' . $name_bits[0]  . '-textarea', addClass, array('show-comments'));
  }
  else {
    $commands[] = ajax_command_css('#edit-' . $name_bits[0]  . '-textarea', array('display' => 'none'));
    $commands[] = ajax_command_invoke('#edit-' . $name_bits[0]  . '-textarea', removeClass, array('show-comments'));
  }

  return array('#type' => 'ajax', '#commands' => $commands);
}

I have also noticed that the id of the form has '--2' appended to it after submitting, could this be related?

Would using an ajax validation tied to the submit button have the same effect?

Yes, the IDs of an element change when it's being reloaded using AJAX. That's supposed to be a feature. :/ You might try using a class to target your textareas instead.


Image Gallery with multiupload i have a Drupal 7 site and want to generate a image gallery.

My requirements:

Multi File Upload
one folder per Gallery
only accessible for authenticated user

I tried plup and multiupload_imagefield_widget for multi file upload. This works fine except for the one folder per gallery requirement. All files are stored in the same folder.

Do you have any advices on how to achiev this goal?

I've got the same problem like Jussi and i tried to set up a system with the himuesgallery module, the upload via ftp works great and you can build a folder system.
I tried to integrate the image folders in Drupals Private Dir and the result is that i can't see any picture anymore ... may i configured somehing wrong, but this seems not to be a solution.
May a module to restrict access to another folder help.
A long time ago i tried the media module and there was some other problems...
See also the Media Issues or the statement of the authors:

Known Issues
Private files: There are several issues in Media and Drupal core when the private file system is used. While these issue are being investigated and fixed, the use of the File lock module is highly recommended.

So my answer is: No, there is currently no working gallery that reachs your aims.


Long-running cron task never fully executed I am developing a Drupal Cron that has a very long-running task.
First I tried with a simple Cron, which, of course, did not work because of "Memory exhausted" PHP fatal error.

Then, I developed a Batch with the Batch API which worked fine as a normal Batch. However, I could not make to run it completely inside the Cron. It receives the same PHP error.

After that, I developed a Cron using the Queue API. However, I could not make Drupal to run all queue jobs in the same cron. The execution stops at some point and I am unable to run more jobs. I know that there is an option to define the worker's function time, but my task is a long-running task. So it is limited by PHP.

I also tried to use Background Process module in order to execute my long-running task but it had the same problem as before: the execution stops at some point.

I am sure that the code can be executed completely. The only working way was through Batch page but I want to run it automatically every day (Cron).

Do you know how can I run a Cron until it finishes?

As I said, I tried with Batches and Queues but it did not work. PHP "memory exhausted" or timeout errors appear or the execution can be cut by Drupal.

Thank you.

After a long battle analyzing how to execute a long-running task as a Drupal Cron, finally I found a generic solution that involves the Queue API and Cron. Maybe this can help other people who is struggling with a similar problem. Here are the steps I followed:

Think about how to execute your long-running task as chunks in terms of Drupal Queue items. You need to represent all tasks as queue items. For example, the first item (or action) may be to initialize the complex work that needs to be done. Then, the following items may execute that work by pieces. Each item (or chunk) has to be processed individually, so no PHP Timeout or PHP Memory Exhausted error appear.
Create a new Cron that will create the queue and its items. Make sure that you also implement the hook_cron_queue_info().
Implement the queue item process function you defined in the above hook. If you need to pass information between each item process, you can use Drupal's variable_get(...) and variable_set(...). If you need a more complex structure, you can define a database with Schema API in the module my_module.install file.
Now create a new function that will read and process one or more items of your queue (if not empty).

For example:

function my_module_process_my_queue() {
  $my_queue = DrupalQueue::get('my_module_queue');
  if ($my_queue->numberOfItems() > 0) {
    $action = $my_queue->claimItem();
    if ($action) {
      my_module_queue_process_item($action->data);
      $my_queue->deleteItem($action);
    }
  }
}

Install a Cron module (such as Elysia Cron) or add a cron job in your server configuration. At least, you need to specify the execution of 2 Cron functions. The first one (from step 2) will run the moment you prefer. In my case, it has to run once a day. The second one will be a simple Cron that will call the function from step 4. That second Cron will run every X minutes. Where X means the maximum time execution that a queue item processing may take. If you do not install a Cron module, you do not need the second Cron function. In my case, I decided to use Linux crontab configuration and Drush.

For example:

*/2 * * * * cd /path/to/your/drupal/installation && export DRUSH_PHP=/path/to/your/bin/php && drush ev "my_module_process_my_queue();"

Finally, execute your crons or wait until they are executed. Once a day, the queue will be filled with new queue items. Those items will be processed during the first Cron execution and every X minutes with the other one. So, after some time, all queue items will be processed and the long-running task will finish.


How can I setup a site with Acquia Dev Desktop 2 beta? I'm using the new version of Acquia's Dev Desktop beta 2 (https://docs.acquia.com/dev-desktop2) and I want to use it to test and develop on Drupal 8, but it seems tied to a specific set of distributions (ex. commons, COD, Acquia Drupal) and doesn't have the option to install a separate installation. How can I use this for another version of Drupal, besides the versions they are offering?

To do this, I used dev desktop to create the site instance (instantiating the database and vhost files within Apache) than overwrote that with the install I wanted. Specifically,

I created my site instance normally, selecting "Acquia Drupal" or any of the installations when it asked me to choose a distribution.

For my site settings, I changed it from the long name to 'drupal8' for simplicity

then I went to my local sites directory through terminal and removed the Drupal 8 installation it created (these commands assume OS X environment)

cd ~/Sites/Dev\ Desktop/
rm -rf ./drupal8

Now I can add whatever I like back into this directory, making sure I create it with the same name:

git clone --branch 8.x http://git.drupal.org/project/drupal.git ./drupal8

Now we should be able to install this normally with a couple changes at the install stage. For the database settings, you can use

username: drupaluser
password: <blank>

as Dev Desktop uses these credentials for all the databases.

Under advanced configuration there were two other settings you need to get this to work:

port: 33067
localhost: 127.0.0.1


In a view of products, add the word "Added" to all products already added to the cart I have a view that lists all my products, I want to display the word "Added" below every product that has already been added to the shopping cart.

How can I accomplish this?

Sorry for the late answer, I meant to answer this, but for some reason got lost and today this Q just randomly popped into my mind.

If you think creatively, you can accomplish this using CSS like this:

1) Create an attachment clone of your cart, by clicking the +Add button and selecting attachment. Remove all fields and add a unique field to it, such as SKU. (Make sure you use For: this attachment override, so you don't affect your actual cart view).

2) Rewrite your SKU field to be like this

3) In in the header section of your products view, add the attachment clone of your cart.

4) In your Products view, wrap each product inside a div class that has the SKU#

...

You could try doing the re-writes through the Views UI, else you can use a template file (hopefully you know how to use template files in Views).


How to secure session cookies I am facing a session cookie hijacking vulnerability please refer the attached

  image. When i put these cookie in another browser which i simply type
  the domain like http://example.com and add the copy cookie using the
  extension then simply i change the url to example.com/dashboard
  then user dashboard automatically open just because of copy cookie
  all have the same label only value is different.

The value of the cookie needs to be kept a secret, otherwise as you point out, someone can 'hijack' the session and perform actions as the original user.

Under normal circumstances an attacker wouldn't be able to get the value of this cookie from your browser, if they can, then they're into your machine, and can probably do what they like. Game over.

That leaves man-in-the-middle attacks as a way to get the value of this cookie, and you avoid those by running the site over HTTPS, so that the value of the cookies is encrypted in transit, and only readable by the client and the server.


Is it possible to use search api indexs together? I'm trying to create a search page for forum topics. Forum topics however are both posts and the comments attached to them, unlike other content the comments and actually posts are just as important to search.

I have an index of all forum posts and one of all forum comments. I'd like to be able to have both searchable from one page. Maybe even if it's possible then I'd like to have one index that handles all of them. But if that is not possible then is it possible to combine two index's in search api into one page search?

I'm not finding anything on this so far, but will keep looking. If I find something before I get an answer I'll post it here.

Yes, you need to used the Search API multi-index searches module.

  This module is an addition to the Search API module which allows users
  to search on several indexes at once.

  When the module is enabled, you'll get a new Views base table where
  you can search all enabled Search API indexes at once. Performance
  might suffer, though, if not all indexes lie on the same Solr server
  (or other backend server that supports this feature).

  Please note that, since multi-index searches aren't supported
  explicitly by the Search API, most other Search API add-on
  functionality (facets, autocomplete, saved searches, search pages,
  etc.) won't work with searches created with this module.

There is also a sanbox project that allows you to combine Search Multi Index and Facets.


How to change the variation title in the add to cart block in Drupal Commerce 1? I'm building a store in D7 and Commerce 1. My product variations have a Size attribute - these are displayed in the Add to Cart block as a list of radio options.

I would like the option labels to include the price of that variation, e.g.

Small - $10
Medium - $15
Large - $20

These labels should be generated automatically from the price.

I figure this could be achieved with a simple function, but I haven't been able to find one. Any suggestions welcomed!

OK. I got it working. Perhaps not quite as simple as I'd hoped, but this function will do the trick ...

function commerce_price_attribute_form_commerce_cart_add_to_cart_form_alter(&$form, $form_state) {
    if (isset($form['attributes'])) {
        $entity = entity_load_single($form_state['context']['entity_type'], $form_state['context']['entity_id']);
        foreach (element_children($form['attributes']) as $field) {
            foreach (field_get_items($form_state['context']['entity_type'], $entity, 'field_product') as $product) {
                $product = commerce_product_load($product['product_id']);
                $status = entity_metadata_wrapper('commerce_product', $product)->status->value();
                if ($status) {
                    $items = field_get_items('commerce_product', $product, $field);
                    if (is_array($items)) {
                        $attribute = reset($items);
                        $attribute = taxonomy_term_load($attribute['tid']);
                        $items = field_get_items('commerce_product', $product, 'commerce_price');
                        $item = reset($items);
                        $price = commerce_currency_format($item['amount'], $item['currency_code'], $product);
                        $form['attributes'][$field]['#options'][$attribute->tid] = $attribute->name . ' - ' . $price;
                    }
                }
            }
        }
    }
}

Note that the $status value checks whether the variation is disabled and skips over it if it is - without that, disabled products were still showing in the list of options.


How to create an unsubscribe link via mail in simplenews? UPDATE

I updated my code to helderco's answer:

$mail = $form['mail']['#value'];
$subscriber = simplenews_subscriber_load_by_mail($mail);
$context = array(
    'category' => $form['newsletter']['#value']->name,
    'simplenews_subscriber' => $subscriber->snid
  );

but

debug(token_replace('[simplenews-subscriber:unsubscribe-url]', $context, array('sanitize' => FALSE)));

prints:

'https://mywebsite.com/newsletter/confirm/remove/'

is this correct?

I am writing a small module to extend the simplenews module, because as it seems, once a user has confirmed to be subscribed, no email is being sent. So I wrote a module which does exactly that.

Within the mail I am sending I would like to provide an unsubscribe link directly (or to a form). How would you do that? Simply adding the token within the mail text does not work.

<?php

function simplenews_apag_form_simplenews_confirm_add_form_alter(&$form, &$form_state, $form_id) {
  $mail = $form['mail']['#value'];
  $form['question']['#markup'] = '<p>'. t('Do you really want to subsribe your e-mail adress (%mail) to get a notification via e-mail as soon as ...', array('%mail' => $mail)) . '</p>';
  $form['#submit'][0] = '_simplenews_apag_simplenews_confirm_add_form_submit';
}

function _simplenews_apag_simplenews_confirm_add_form_submit($form, &$form_state) {
  simplenews_subscribe_user($form_state['values']['mail'], $form_state['values']['newsletter']->tid, FALSE, 'website');

  $path = variable_get('simplenews_confirm_subscribe_page', variable_get('site_frontpage', 'node'));
  drupal_set_message(t('Thank you very much for your interest. You will receive a confirmation mail.'));

  $params = array();
  $address_default = variable_get('site_mail', 'info@example.com');
  $params['from'] = variable_get('simplenews_from_address', $address_default);
  $params['to'] = $form_state['values']['mail'];

  drupal_mail('simplenews_apag', 'subscription_complete', $params['to'], language_default(), $params['from'] );

  $form_state['redirect'] = $path;
}

function simplenews_apag_mail($key, &$message, $params) {
  switch ($key) {
    case 'subscription_complete':

      $message['subject'] = 'Thanks';
      $message['body'][] = 'Bla Bla. Click the link beneath to unsubscribe: ';
      // how to provide unsubscribe function?
      $message['body'][] = '[simplenews:unsubscribe-url]';
      $message['body'][] = 'Regards';

      break;

    case 'unsubscription_complete':
      break;

    default:
      return false;
      break;
  }
}
?>

Any idea is greatly appreciated. I am using drupal 7

You need to use token_replace.

Try this:

<?php
$newsletter = simplenews_newsletter_load($node->nid);
$context = array(
  'category' => simplenews_category_load($newsletter->tid),
  'simplenews_subscriber' => simplenews_subscriber_load_by_mail($mail)
);
print token_replace('[simplenews-subscriber:unsubscribe-url]', $context, array('sanitize' => FALSE))';
?>

You should get a url like so: http://example.org/newsletter/confirm/remove/c453d5e25d2t10

That thing in the end is an hash, built in simplenews_token() (simplenews.tokens.inc).

Update: I updated my answer to show how you can get the correct variables from simplenews. Taken from simplenews_node_view() (in simplenews.module).


Product color from select list in Commerce Kickstart 2 I thought it would be simple, but either I'm stupid or the commerce kickstart 2 doesn't have such functionality.

I've created a t-shirt product variation and I want to give my customers the possibility of choosing their favorite color from a color picker or from a select list. The color doesn’t affect the price.

As I see the only option for doing this in kickstart commerce is by creating each variation per color.
Is there any other way to accomplish this? I just want to create t-shirt and let people choose their color.

Please help me I'm getting very frustrated.

That's exactly what variations are for...

You have a product (a t-shirt) with a variety of different options (colours), hence you need different variations of the product to identify what colour of t-shirt has actually been sold.

Kickstart already has that exact functionality built right in; if you install the demo content and browse to "/tops/guy-short-sleeve-tee" you should see it:


How to redirect "relationships/received" to "user/[requestee:uid]/relationships/received? (D7) When a user sends a friend's invitation to another user (User Relationships) the other user, once he logs in, sees a green message that informs him so-and-so sent him a friends request. There is a link that takes the viewer (requestee) to example.com/relationships/received.

However, I have created a view that displays the received requests in a different format. Of course the page view has a different path and I want the user to be redirected to: user/[uid of the requestee]/relationships/received and the requestee only to be allowed to see the requests he received.

I have created a rule (Rules module) as follows:

Event: A user relationship has been requested
Condition: Relationship has type (friend)
Action: Page redirect (user/[requestee:uid]/relationships/received)

[requestee:uid] is in the allowed replacement patterns but it doesn't work. Clicking on the link still takes the viewer to the original path.

What do I do wrong?
:)

If you want to redirect to the current user profile page, you could try using the redirect module with redirect_token

Use tokens in "To" paths in Redirect module.

Then you can redirect from http://example.com/relationships/received to http://example.com/user/[user:uid]/relationships/received


How to pass same contextual arguments to two view blocks programmatically? I'm trying to pass same arguments to views. Here is my code:

$view = Views::getView('taxonomy_articles');
            if (!empty($age)) {
              $view->setDisplay('block_6');
              $view->setArguments([$term->tid, $age_args]);
              /*
               * override term name with age param
               */
              $termURL = Url::fromRoute('entity.taxonomy_term.canonical', array('taxonomy_term' => $term->tid, 'age' => $age));
              $termName = \Drupal::l(t($term->name), $termURL);
            }
            else {
              $view->setDisplay('block_1');
              $view->setArguments([$term->tid]);
            }

My else part gets executed and array of term ids goes to block_1, my view block machine name.

What I want is similar like:

              else {
                  $view->setDisplay(['block_1','block_7']);
                  $view->setArguments([$term->tid]);
                }

Is this possible? Can we pass array to $view->setDisplay ???

While rendering a view you can only use on display.
So it is only possible to loop through your display array and generate the view within that loop like:

          else {
              foreach (['block_1','block_7'] as $display) {
                $view->setDisplay($display);
                $view->setArguments([$term->tid]);
                // You need to render here.
                // The loop will overwrite the first display.
              }
            }


Google/search engine links to Drupal site broken, why is domain missing a slash? I noticed that links to my site from search engines don't work. Google links me to https://www.site.comcontent/page-title-1. I am using Pathauto and Clean URLs. The slash is missing at the end of the domain. Is there something obvious I have misconfigured? I can navigate around my site just fine once I am there.

Edit: originally mis-typed the problem - note https instead of http.

This ended up being a problem introduced with the freshly installed SSL cert and redirecting to https, in combination with using Clean URLs. Turns out there is documentation on configuring Clean URLs and HTTPS with Apache.


Warning: Illegal string offset '#access' in views_handler_field_field->set_items() line 862 views_handler_field_field.inc I'm having an error that I can't find an answer for, and was wondering if someone out there can help.

The error i get is...

Warning: Illegal string offset '#access' in views_handler_field_field->set_items() (line 862 of .../sites/all/modules/views/modules/field/views_handler_field_field.inc)

I have created a view, that is showing a multiple value result of a photo gallery from 10 nodes of the same content type. Basically I have a content type for venues, and each venue can upload an unlimited number of photos for their venue. This view sits on one of the main national pages, and shows all photos from all venues.

Looking at line 862, the error is in the following bit of code

  // field_view_field() adds an #access property to the render array that
  // determines whether or not the current user is allowed to view the
  // field in the context of the current entity. We need to respect this
  // parameter when we pull out the children of the field array for
  // rendering.
  if (isset($render_array['#access'])) {
    $items[$count]['rendered']['#access'] = $render_array['#access'];
  }

Can anyone help me and shed a bit of light on this? It looks like a permissions problem if a user doesn't have access to the content, but my permissions are no different than they have been for the last 10 drupal sites I have built.

I found the answer, I realised that as well as the error, I was also seeing a "1" appear after the grid items.

This bug is related to the Grid Field Display module, and the answer and patch can be found at https://drupal.org/node/2046435


Same module for different Drupal versions I've just started developing Drupal module and have completed the simple "Hello "World" module. The module is working fine on both Drupal 6 and 7.

How can I use the same module on both Drupal 6 and 7, instead of packaging it as 2 separate modules?

Sorry, you can't without hacking Drupal's core. By the documentation for Drupal 7 you need to set:

core = 7.x

in module's info file. At the same time documentation for Drupal 6 requires you to set:

core = 6.x

Values without [] may appear only once, so you cannot write:

core = 6.x
core = 7.x

And you cannot make a value to be an array, so following also would not be recognized and accepted:

core[] = 6.x
core[] = 7.x

Safest way to solve it is to keep modules separate, and move common PHP code to a PHP library. With Libraries API it should be pretty easy to do.


Multiple (and differents) crons? In a normal production webiste, there are many tasks that need to be done via crontab, but lets say you dont want all of these tasks to run on every cron.

For example, i would love to have:

A cron that run once a day, for the 'normal' maintenance (updates checks, for example)
B cron that runs every 15 minutes, to send newsletters (from simplenews)
C cron that run twice a day, that pull data from a view (json view) and write down a json file on the server (for a geomapping service with lots of data that doenst need a real-time sincronyzation).

Actually, i have a unique cron that do the A, B and C tasks on every run, every 15 minutes; so i created 2 php scripts that bootstrap drupal, one send the emails, and the other one cache the geomapping file.. it works, but is pretty a manual  way that i dont like too much.

What is the best practice to set different crons, get all the modules hook_cron, and assign them only to a specific cron?

There is a module for that (tm):

http://drupal.org/project/elysia_cron

Have a look at http://2bits.com/drupal-performance/improving-performance-drupals-cron-using-elysia-cron-module.html for more information about it.


Webform component weight within a Fieldset I am creating a settings page for a specific Webform in version 6.x-3.x which finds all select option components in the form and creates a numeric textfield setting correlating to each select option. The Select Options are in fieldsets. On the settings page, I want the numeric textfields to show up in the same order that the select options show up in the form.

db_querying the right select options in the webform_component table is working fine, but the select options show up out of order when ordering by weight.

For example:

The Webform

Fieldset 1
- Textfield 1
- Select Option 1
- Select Option 2
Fieldset 2
- Select Option 3
- Select Option 4

db_query('SELECT * FROM drupal_webform_component WHERE TYPE = "select" AND nid=123 ORDER BY weight'); generates results like this:

Select Option 1
Select Option 3
Select Option 4
Select Option 2

How do I order Webform results of components within fieldsets to reflect the order they appear on the form? What would the db_query look like?

Ok, there is a column pid in webform_components for individual components. This value correlates with the cid of the fieldset. A LEFT OUTER JOIN between the cid and pid columns, filtered by the webform node id - nid, then ordered by the fieldset weight followed by the select option weight returns the components in the correct order as they appear on the node form. Here is the db_query statement.

db_query('SELECT *
FROM webform_component AS f
LEFT OUTER JOIN webform_component AS s ON f.cid = s.pid
WHERE f.nid = 123 AND s.nid = 123 AND f.type = "fieldset" AND s.type = "select"
ORDER BY f.weight, s.weight');

This works. Any advice on optimizing this query is appreciated.


Twig get value of field in entity reference i have a content type "actuality" with a reference to an other content type "event".
In "event" i have a "field_date" which i want to print into my "actuality" node.
What is the best way to do that ?

I've already created a template node--actuality.html.twig and trying to print inside node.field_event_associated.field_date but it's not working.

Regards,

For any type you of field get the value directly like you wrote node.field_name.value. But for reference type you can't get the value directly. For reference type you have to write

ex.:

node.field_team_location.entity.name.value

and for uri u can write:  node.field_team_location.entity.uri.value


Add multiple fields in +Add more button causes problem in sequence I am implementing a form and in that form it requires that two form element should be coming under one Add more button, so user can add any number of fields.

Here is the code which i am using to create a form.

function ajax_example_add_more($form, &$form_state, $no_js_use = FALSE) {
  $form['description'] = array(
    '#markup' => '
' . t('This example shows an add-more and a remove-last button. The AJAX version does it without page reloads; the non-js version is the same code but simulates a non-javascript environment, showing it with page reloads.',
      array('!ajax' => url('examples/ajax_example/add_more'), '!multistep' => url('examples/ajax_example/add_more_no_js')))
    . '
',
  );

  $form['#tree'] = TRUE;
  $form['names_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('People coming to the picnic'),
    '#prefix' => '
',
    '#suffix' => '
',
  );
  if (empty($form_state['num_names'])) {
    $form_state['num_names'] = 1;
  }
  for ($i = 0; $i < $form_state['num_names']; $i++) {
    $form['names_fieldset']['name'][$i] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
    );
    $form['names_fieldset']['surname'][$i] = array(
            '#type' => 'textfield',
            '#title' => t('SurName'),
    );
  }
  $form['names_fieldset']['add_name'] = array(
    '#type' => 'submit',
    '#value' => t('Add one more'),
    '#submit' => array('ajax_example_add_more_add_one'),
    '#ajax' => array(
      'callback' => 'ajax_example_add_more_callback',
      'wrapper' => 'names-fieldset-wrapper',
    ),
  );
  if ($form_state['num_names'] > 1) {
    $form['names_fieldset']['remove_name'] = array(
      '#type' => 'submit',
      '#value' => t('Remove one'),
      '#submit' => array('ajax_example_add_more_remove_one'),
      '#ajax' => array(
        'callback' => 'ajax_example_add_more_callback',
        'wrapper' => 'names-fieldset-wrapper',
      ),
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  if ($no_js_use) {
    // Remove the #ajax from the above, so ajax.js won't be loaded.
    if (!empty($form['names_fieldset']['remove_name']['#ajax'])) {
      unset($form['names_fieldset']['remove_name']['#ajax']);
    }
    unset($form['names_fieldset']['add_name']['#ajax']);
  }

  return $form;
}

/**
 * Callback for both ajax-enabled buttons.
 *
 * Selects and returns the fieldset with the names in it.
 */
function ajax_example_add_more_callback($form, $form_state) {
  return $form['names_fieldset'];
}

/**
 * Submit handler for the "add-one-more" button.
 *
 * Increments the max counter and causes a rebuild.
 */
function ajax_example_add_more_add_one($form, &$form_state) {
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}

/**
 * Submit handler for the "remove one" button.
 *
 * Decrements the max counter and causes a form rebuild.
 */
function ajax_example_add_more_remove_one($form, &$form_state) {
  if ($form_state['num_names'] > 1) {
    $form_state['num_names']--;
  }
  $form_state['rebuild'] = TRUE;
}

The above code is taken from the example module with little modification. In this code i have added one more text field called surname with name textfield.

Now when i access form it gives me the form fields as shown in the image given below.
Before clicking on Add more button:

Now when i click on the Add more button two fields are added as shown in the below image.

Here you can notice that there are two continuous Name and then two continuous Surname fields.

But actually i want to show these fields like in group. So the first group of name and surname and then second group of name and surname field.

How can i achieve as per the above snapshot ?

The answer is - you really shouldn't try. The logic behind your form now shows one person with two Names and two SurNames. What you want, I bet, is two persons with one Name and one SurName each. So just group Name and SurName in fieldset and you're good.

If you insist on not doing it, read further. You use $form['names_fieldset']['name'][$i] and $form['names_fieldset']['surname'][$i]. It means $form['names_fieldset']['name'] is created before $form['names_fieldset']['surname'], so everything you put in it will be together and before surname. Just swap indexes and make them look like this: $form['names_fieldset'][$i]['name'], $form['names_fieldset'][$i]['surname'] and you'll be good. Of course $form['names_fieldset'][$i] can be a fieldset by itself, so we are back to first paragraph.


Content type select field is not listing in front end I created a content type field called  which have widget type select list

But its not displaying the field in frontend. When I changed the widget type to the text field it displays the field in frontend. I  given the edit and view permissions to the filed too

But its not displaying in the front end.

when you create new field of type "list(text)" and then click "save"
you will go to new page where you have to insert the values you want the user to select from, add all the values in that page one value per line.
you can also assign key to the value by using this format "key|label"


How to make the pdf files downloadable? I am able to display file with url: For example

echo ''.$path_parts['basename'].'';

How can I make this file downloadable? In case of pdf files, it is not downloading and opening in new tab as i have added target.

If you want to Force download PDF files.
if your server is Apache

put this line in your .htaccess file.

AddType application/octet-stream .pdf

If there is any issues with browser try this

SetEnvIf Request_URI "\.pdf$" requested_pdf=pdf
Header add Content-Disposition "attachment" env=requested_pdf

If its NGINX

location ~* /orig/(.+\.jpg)$ {
    internal;
    add_header Content-disposition "attachment; filename=$1";
}


How to convert an existing field from Text to Link in Drupal 7 If I have a field in Drupal which of type Text, how do I convert it to to allow a link if the field is already being used on the site without losing data?

Install the Link module in order to allow link fields.
In your database, run:

UPDATE field_config set type='link_field', module='link' WHERE field_name='YOUR_FIELD_ID'
Then run the following query:

UPDATE field_config_instance SET data='a:7:{s:5:"label";s:LENGTH_OF_YOUR_FIELD_NAME:"YOUR_FIELD_NAME";s:6:"widget";a:5:{s:6:"weight";s:1:"9";s:4:"type";s:10:"link_field";s:6:"module";s:4:"link";s:6:"active";i:0;s:8:"settings";a:0:{}}s:8:"settings";a:10:{s:12:"validate_url";i:1;s:3:"url";i:0;s:5:"title";s:8:"optional";s:11:"title_value";s:0:"";s:15:"title_maxlength";s:3:"128";s:13:"enable_tokens";i:1;s:7:"display";a:1:{s:10:"url_cutoff";s:2:"80";}s:10:"attributes";a:5:{s:6:"target";s:6:"_blank";s:3:"rel";s:0:"";s:5:"class";s:0:"";s:18:"configurable_title";i:0;s:5:"title";s:0:"";}s:10:"rel_remove";s:7:"default";s:18:"user_register_form";b:0;}s:7:"display";a:1:{s:7:"default";a:5:{s:5:"label";s:5:"above";s:4:"type";s:12:"link_default";s:8:"settings";a:0:{}s:6:"module";s:4:"link";s:6:"weight";i:16;}}s:8:"required";i:0;s:11:"description";s:0:"";s:13:"default_value";N;}' WHERE field_name='YOUR_FIELD_ID'
(optional) Go into the table for your field name (field_data_field_YOUR_FIELD_NAME) and remove the column field_YOUR_FIELD_NAME_format
In the same table as #4 above, change the column field_YOUR_FIELD_NAME_value to field_YOUR_FIELD_NAME_title. This will make the previous values for these text fields now become the title of any links placed in the new Link field.
In the same table as #4 above, add the columns field_YOUR_FIELD_NAME_url VARCHAR(2048) ALLOW NULL, and field_YOUR_FIELD_NAME_attributes MEDIUMTEXT ALLOW NULL

This solution worked well for me.


How to return all aliases for a path? I'm aware of this question Find all aliases for a given node - but this appears to be for 7, and I'm looking for a solution for 8.

I'm also aware of the AliasStorage and AliasManager classes, which respectively provide the lookupPathAlias and getAliasByPath methods. But these methods only return one path alias per path, even though I have multiple defined.

What is the best way return all aliases for a path?

The answer is the same as in Drupal 7, because there is no API to return multiple aliases for a single source path, so your only option, if you really need that (I guess there is a reason that you are not using redirects), is a custom query, which is the same as in 7.x, with the only difference that it has a leading /.

So, copied from the other issue:

$aliases = \Drupal::database()->query('
  SELECT alias
  FROM {url_alias}
  WHERE source = :source
', array(':source' => '/node/' . $nid))->fetchAll();


dpm breaks only if used in form custom submit on edit node Problem

I have a case where the dpm printout is working fine in all cases except on a specific node type, in a very specific scenario.

If I edit the node type and place  dpm($form_state) in the custom node submit called by hook_form_alter, no messages display on submitting the form.

If I create the node it works fine. If I put dpm($form) in the custom node submit it works fine. It's only that exact scenario which breaks.

I've read other questions where dpm breaks, but never for something so utterly and irritatingly specific.

I've cut down my code to:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id === 'mycustom_node_form_id') {
    $form['#validate'][] = 'mymodule_form_validate';
    $form['actions']['submit']['#submit'][] = 'mymodule_form_submit';
  }
}

function mymodule_form_validate ($form, &$form_state) {
  dpm($form_state);
  dpm($form);
}

function mymodule_form_submit ($form, &$form_state) {
  dpm($form_state); <-- THE PROBLEM
}

The node type itself, contains a fairly complex field collection, a bunch of ordinary fields and a fivestar field.

Can anyone provide any guesses or places to begin debugging this? I'm completely stumped.

Thumbson was spot on. MySQL was hitting it's the packet limit and increasing maximum_allowed_packet in /etc/mysql/my.cnf solved the problem. (ubuntu path)

The error won't show in Drupal, the only place I could find it was in my php-fpm log. See below:

[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "NOTICE: PHP message: PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away' in /srv/w$
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "Stack trace:"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#0 /srv/www/eslsearch.net/public/includes/database/database.inc(2171): PDOStatement->execute(Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#1 /srv/www/eslsearch.net/public/includes/database/database.inc(683): DatabaseStatementBase->execute(Array, Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#2 /srv/www/eslsearch.net/public/includes/database/database.inc(2350): DatabaseConnection->query('SELECT expire, ...', Array, Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#3 /srv/www/eslsearch.net/public/includes/lock.inc(167): db_query('SELECT expire, ...', Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#4 /srv/www/eslsearch.net/public/includes/lock.inc(146): lock_may_be_available('schema:runtime:...')"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#5 /srv/www/eslsearch.net/public/includes/bootstrap.inc(433): lock_acquire('schema:runtime:...')"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#6 /srv/www/eslsearch.net/public/includes/bootstrap.inc(455): DrupalCacheArray->set(Array)"
[13-Jan-2015 00:54:27] WARNING: [pool www1] child 21620 said into stderr: "#7 [internal function]: DrupalCacheArray->__destruct()..."


Hide region when block menu is empty I got the 2nd level main menu in a block in the sidebar, drupal 8 correctly hides the menu (and the block) when the user browses a page that is not in this menu, but the theme continues to show the empty region.
The condition {% if page.region %} is true.
is there any way to solve this problem?

It is better to use construction

{% if page.region|render|striptags|trim|length > 0 %} ... {% endif %}

So you can check if there is some content or not.


Unrecognized migration I am using this example: https://gist.github.com/2596787 as a base for importing some static HTML to a Drupal 7 fresh install.  Using drush ms:

Group:                Total  Imported  Unimported  Status  Last imported

HtmlfilesNodeMigration

HtmlfilesNode         2046   0         2046        Idle    2013-01-23 13:58:01

I can see that the Migration class seems to be setup.  However when I go to run the migration from drush I get:

Unrecognized migration: HtmlfilesNodeMigration                           [error]

Trying through the UI, I get

Fatal error: Class 'HtmlfilesNodeMigration' not found

Any ideas, pointers etc would be a great help.  I can post the info/module/inc files I am using if needed.

I've made a bit of progress.  I had created the HtmlfilesNodeMigration class outside of the actual hook_migrate_api function.

So instead of:

return $api;

}

class HtmlfilesNodeMigration extends Migration {
//code
}

I needed:

return $api;
class HtmlfilesNodeMigration extends Migration {

  }

}


On a content page that references a taxonomy term, how can I display only content that references that taxonomy term's immediate children? In Drupal 8, I have a hierarchical taxonomy vocabulary called "Living Things" containing these terms:

Animals
--Fishes
----Blennies
------Yellow Blenny
------Green Blenny
----Gobies
------Blue Goby
------Red Goby

I have created a custom content type called "Taxon Page" which includes a single reference to the "Living Things" vocabulary.

Using the "Taxon Page" content type I have created a page for each of the terms in the "Living Things" vocabulary. So for example, my "Yellow Blenny Facts" content page contains a reference to the "Yellow Blenny" taxonomy term.

On those "Taxon Page" content pages, how can I display only content that references that taxonomy term's immediate children (if there are any)? For example, the "Fishes Facts" content page should display data from the "Blennies Facts" and "Gobies Facts" content (not just a link to those taxonomy terms), but not their children.

I have tried to achieve this by creating a view for "Content type (= Taxon Page)" and adding a "contextual filter: Content: Has taxonomy term ID (with depth)" (depth of 1) but it did not work.

Note that this question is related but different, as it only refers to taxonomy terms, not content referencing those taxonomy terms.

I think you may be confused about how Views works.  To give a custom display to taxonomy terms, you don't need to create a content type to reference a taxonomy and then use Views to override how the content type is displayed; you can simply create pages with a view that display the taxonomy directly.

This means you may not need the Taxon Page content type; depending on what you intend to do, you could add any fields you need for your fish pages to the Living Things taxonomy and then display this taxonomy as pages by using a view that overrides how the taxonomy is displayed.

For an example, see the taxonomy_term view included in core:

/admin/structure/views/view/taxonomy_term

Another way to do this is to use Panels, which (with Page Manager) allows you to override the display for all taxonomy terms and attach a custom view (and whatever else you want) to those terms.

Yet another option is Display Suite.


500 internal server error on a single node This just happend randomly today. I tried to access a page, but it keeps giving me a 500 internal server error http://www.austravel.com/holiday-destinations/australia

All the other pages are working fine. Any ideas why this may be?

Display PHP errors for that page or examine your Apache log file with errors enabled. Nobody can tell you what's misconfigured, or whatever typo you've made in your PHP ... log files can tell you though.

EDIT:

For further explanation on "errors" and specifically 500 error from Apache see:
https://stackoverflow.com/questions/8564259/php-5-3-troubleshooting-500-errors-debugging-parse-errors

  PHP will respond with a "500" when it encounters a Fatal error, such
  as E_PARSE, E_ERROR and uncaught exceptions. 500 is the HTTP response
  code for "Internal Server Error" - something unrecoverable happened
  while processing the request.

  In your php.ini, on a development machine, you should set your
  error_reporting level to (at least) E_NOTICE - preferably E_ALL - and
  make sure display_errors is on. This will show you the error message
  in the browser, including for "500" errors.

  You can also check your Apache error logs, the errors will be listed
  there, as long as log_errors is enabled in php.ini. By default, this
  will be at \logs\error.log.

  You can also control all this at run time with ini_set() and
  error_reporting()


Selecting image for embedded youtube video Would like to know how to select the image that is shown on the web page for an embedded youtube video. Currently an image from the video seems to be randomly pulled out and used.

Sadly you cant if its not your video. This is chosen either by youtube or if your a youtube partner you can upload your own image (I think they have a tool nowadays which lets regular youtube users choose their thumbnail for their video).

If you visit this page:

https://developers.google.com/youtube/2.0/developers_guide_jsonc

You will see down the page there is a default/hqdefault thumbnail that comes with every video feed.


Insert data from sql file when call hook_schema on drupal 7 I developed a module in drupal 7 that need a database table like "example_table". And i create "example_table" table using example_schema() function. Now I need to insert some default data.

Here, I can use drupal_write_record('example_table', $data); function to insert data into example_install() function.

But, I want to insert data from example_db.sql file.

How can I do it? Any Suggestions?

You can try this, hope it helps.

$db = new PDO($dsn, $user, $password);
$sql = file_get_contents('file.sql');
$qr = $db->exec($sql);

Otherwise try this, but i am also not aware of this correctly,

function my_module_install() {
  // Get the contents of the .sql file.
  $sql = file_get_contents(drupal_get_path('module', 'my_module') . '/module.sql');
  // Split into individual statements based on new lines.
  $statements = preg_split('/[\n\r]+/', $sql);
  foreach ($statements as $query) {
    db_query($query);
  }
}


Display a single view in different view format I want to display a view in both grid and list style, and allow the users to explicitly select the format in which they want to view (Like the picture below)

The JQuery which I used is

(function ($) {
    Drupal.behaviors.mytheme = {
  attach: function (context, settings) {
    $('#content').once('course-view', function() {

  if ($(".view").hasClass("course-view")) {
    $(".view").addClass("grid-view"); // Sets .grid-view as default class on the view

    $(".list").click(function() {
      if ($(".view").hasClass("grid-view")) {
        $(".view").addClass("list-view"); // adds .list-view to the view class
        $(".view").removeClass("grid-view"); // removes .grid-view from the view class
      }
    });

    $(".table").click(function() {
      if ($(".view").hasClass("list-view")) {
        $(".view").addClass("grid-view"); // adds .grid-view to the view class
        $(".view").removeClass("list-view"); // removes .list-view from the view class
      }
    });
  }
});
  }
    };
    })(jQuery);

I think Your Question resembles the video tutorial series in Code karate:

Multiple Views Series

Please Check It out... By adding and removing classes when clicking the grid and list icons using jQuery make this done..


Is this snippet modification correct? (php snippet in a drupal commerce rule) I´ve read about the possibility to use this snippet to hide a specific checkout pane (in Drupalcommerce), according to the cart contents.

Could I use this somewhat modified to hide a pane when the user completing the order is registered?

<?php
function hook_commerce_checkout_pane_info_alter(&$checkout_pane) {
    foreach ($checkout_pane as $pane_name => & $pane_data) {
        if ($pane_name == 'customer_profile_shipping') {
            $order = commerce_cart_order_load($user->uid);
            if (!empty($order->data)) {
                    unset($checkout_pane['customer_profile_shipping']);
}}}}
?>

I understand that I should change this if (!empty($order->data)) { maybe to something like this? if ($user->uid > 0) {

Is that correct? I want tu hide the pofile2 pane:

So it would be like this:

<?php
function hook_commerce_checkout_pane_info_alter(&$checkout_pane) {
    foreach ($checkout_pane as $pane_name => & $pane_data) {
        if ($pane_name == 'customer_profile_shipping') {
            $order = commerce_cart_order_load($user->uid);
            if ($user->uid > 0) {
                    unset($checkout_pane['commerce_p2cp_profile']);
}}}}
?>

I´m not sure how to add that into a rule set...

You can add your PHP code in action of some rules. For this you will have to enable core PHP filter module.
Once you enable it, you go to ADD ACTION in rules and you will find a option "Execute custom PHP code". If the variable you are suppose to use is available there for using with the PHP code then it will work without any problem..

As per your requirement, if you do this by simple small module then also it will work fine as you just have to put this hook in your .module file, declare the module in .info file & enable it....I am suggesting using module as I see you are already checking your condition in code...


Get views to format an image field for HiDPI / high pixel density / Retina displays I have a view showing several nodes that have photos stored in an image field. It works great, but doesn't look so sharp on HiDPI displays (or when the page is zoomed-in on a traditional display) because the image file that views produces is exactly the size used in HTML. Views is giving me something like this:

But I think what I'd like views to do is produce something like:

This way I'm loading images bigger than necessary (downside = slower page load), but it would seem worth it to me because I could get the images to look nice and crisp when the client has a device pixel ratio > 1.

My images in these nodes are not always the same aspect ratio.

Any thoughts on how to get views to produce the image and markup above, or perhaps how to approach this problem a different way?

srcset has (or will have) decent support in browsers.  What I do, is make _2x image styles for everything, and then do a custom theme_image_style():

/**
 * Implements theme_image_style().
 */
function MYTHEME_image_style($variables) {
  // Determine the dimensions of the styled image.
  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
  );

  image_style_transform_dimensions($variables['style_name'], $dimensions);

  $variables['width'] = $dimensions['width'];
  $variables['height'] = $dimensions['height'];

  // Determine the URL for the styled image.
  $path = $variables['path'];

  $variables['path'] = image_style_url($variables['style_name'], $path);

  // See if we have alternates for the srcset
  $image_styles = &drupal_static(__FUNCTION__);
  if (empty($image_styles)) {
    $image_styles = array_keys(image_styles());
  }

  $variables['srcset'] = array('1x' => $variables['path']);

  if (in_array($variables['style_name'] . '_2x', $image_styles)) {
    $variables['srcset']['2x'] = image_style_url($variables['style_name'] . '_2x', $path);
  }

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

and then

/**
 * Implements theme_image().
 */
function MYTHEME_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  // Add in normal attributes.
  foreach (array('alt', 'title', 'width', 'height') as $key) {
    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  // Add in our srcset if we have two or more.
  if (count($variables['srcset']) >= 2) {
    $srcset = array();

    foreach ($variables['srcset'] as $size => $path) {
      $srcset[] = file_create_url($path) . ' ' . $size;
    }

    $attributes['srcset'] = join(', ', $srcset);
  }

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

You can also feature detect with Modernizr for srcset and retina support, and then swap out the image src with JS shenanigans if you want.

You can also see if the Picture module does what you want, but there is debate in the community about when <picture> should be used and not used.


Facet Block : only 10 items are shown Using Search_api, search_api_db and facet_api.

Ive created a view display using 'Facet Block'.

Ive set the facet field to the one I want to use. The facet configuration of this field has no listing limits.

ive set the view setting's 'pagination' to display all items.

When I look at the rendered block, it only shows 10 items.

Does anyone ever face this kind of problem ?

Is there an hard-coded limit ?

You can manually edit this limit in the search_api_views module source file.

You find this here in the commerce kickstart bundle:

/profiles/commerce_kickstart/modules/contrib/search_api/contrib/search_api_views/includes/display_facet_block.inc

Then you correct the limit of 10 on line 167 of display_facet_block.inc

$limit = empty($this->view->query->pager->options['items_per_page']) ? 100


Load current node from block and from display suite field Sorry if this question is too obvious, I need to load the current node from display suite and then execute this php code:

<?php

$project = node_load(5);

foreach ($project->field_gallery['und'] as $val ) {
  echo '<img src="' . $val['filename']  . '">';
}

?>

In display suite I tried:

$project = node_load($nid);

and

$project = $entity->nid;

I also tried the same within a block, and it failed. It only works when I set a static id as node_load(5).

Please, can I get the answer how to load the node from display suite custom field and from a simple block?

Edit: I'm adding a custom field to display suite from this url:
 /admin/structure/ds/fields/manage_custom
Structure > Display Suite > Fields > Add a code field.

You can load the node id from node page using arg function...

  Returns a component of the current Drupal path.

  When viewing a page at the path "admin/structure/types", for example,
  arg(0) returns "admin", arg(1) returns "structure", and arg(2) returns
  "types".

node pages always has path 'node/nid' so arg(1) gives node id...

$nid = arg(1);
$node = node_load($nid);


What variable is responsible for the default admin bar on top of every default Drupal theme? This is basically my html.tpl.php -

</head>
<body>
<?php print $page; ?>
</body>
</html>

What do I need to add to make that horizontal admin bar appear?

It's stored in $page_bottom...you should also output $page_top to make sure you have a complete page:

</head>
<body>
  <?php print $page_top; ?>
  <?php print $page; ?>
  <?php print $page_bottom; ?>
</body>
</html>


Flood table not respecting X_FORWARDED_FOR The flood table IPs are listing the IP of the load balancer, not the one of the request, which is in the X_FORWARDED_FOR header.

I have the 'reverse_proxy' set to TRUE in setting.php, and it works with the CDN as expected, but not with the flood table.

The site hosted at AWS using the CloudFront CDN.

How can I make the flood table look at the IP reported in the X_FORWARDED_FOR header?

$conf['reverse_proxy_addresses'] had my old load balancer IP, thanks to AWS changing the IP without telling me.  Once I updated with the current LB address, it worked as expected.


Aggregated CSS/JS file names, when regenerated? What triggers the aggregated/compressed CSS/JS file names to be regenerated?

Because of the default header for .css and .js set in Drupal's stock .htaccess is 2 weeks, this causes issues with Varnish which obviously just obeys the headers it receives from the application.

Caching .css/.js for 2 weeks isn't really necessary, our web servers can serve hundreds of requests for static files per second. It's the Drupal requests that always worry me. So I can change the .htaccess (though I actually override the Cache-control: max-age header in Varnish so we don't have to modify stock files provided by Drupal).

I have noticed that regeneration can sometimes can be triggered with a drush cc css-js but possibly only if the aggregated files are over a certain age.
Does anyone know what the logic is behind this?

Rather than overriding the header sent by Drupal, it would be useful to know when the file names are regenerated, because that's obviously a way of making sure that HTML code cached in Varnish is picking up a new set of CSS/JS files.

You're looking for drupal_build_css_cache & drupal_build_js_cache. The building happens when the file doesn't exist or when the combination of files used in the aggregate is different than before.

Looking at drupal_clear_css_cache & drupal_clear_js_cache the variable gets removed & any file older than 30 days gets deleted. By removing the variable, drupal will then check to see if the contents of the file has changed, if yes a new aggregate will be built. So the file name is built by using a hash of the files content and the quick lookup is built by a hash of the file names used.

If you want something that's a little smarter than core, doesn't cause a stamped of writes to the variables table on a cache clear, and keeps files around based upon usage instead of a 30 day window give Advanced CSS/JS Aggregation a try.


Hide webform after the user's first submission How would I hide the webform in drupal7 after user's(authenticated user) first submission.Later the user should not be able to view the webform again. Please help me on this.

After creating your webform, go to the "Form Settings" under "Webform". In case you don't find it, here's the URL: node/Nid/webform/configure (I choose not to remind you of the Nid that you should change :)).

Here, you should see an option for "Per User Submission Limit"-
In your scenario, Limit each user to "1" submission(s) "ever".


Point subdomain to root drupal install I have been tasked to flush out the content on a drupal site that utilizes the domain access module for multiple subdomains under one DB.

I have gone to structure->domains  and added all the domains but when I try to visit them I get server not found.
I have found that I need to direct the DNS to each url? I am still a little unsure of how this works. Is there a way to do this without accessing the host like through the .htaccess file or settings.php or httpconfig? I need to "configure all domains to the primary VirtualHost's ServerAlias, or else point all relevant DocumentRoots to my single installation of Drupal."

Can someone please help me get these last two subdomains pointed to the root install of drupal so the site actually shows up? Is this possible to do without editting the httpd.config file as I don't have access to the server files.

Thanks

The Domain Access module has quite thorough documentation.

For your specific issue, you want the Before installing section, which covers the necessary Apache configuration. In short, you're right that you want to configure all domains to point at a single docroot--once that is set up, Domain Access will properly handle which content is available on specific domains.


Setting the admin theme only inside the overlay On my site, I have the Overlay module enabled, and I have selected an admin theme that is different from the theme used as default.
Sometimes, a page for which the admin theme is set is accessed with a direct link, and the admin theme is used. I would like to show the page with the default theme, and use the admin theme only with the overlay.

Is there a way to achieve this (module, or code to use in a custom module)?

The Overlay Theme module would probably be ideal:

  Overlay theme is a small module that provides an option to set the theme of modal frames provided by the core Overlay module, different from the default which is the Administration theme.

Using that you could set your default admin theme to the same as the front end, and set the overlay theme to what ever you like.


Howdo I display all the images from a field in a view? I'm trying to display multiple images from an image field in one view as an Owl Carousel, but I only see a maximum of 5 images to be displayed there.
Googleing it, I found that there's an option ALL, that should display all of the images, but it just doesn't appear to me, so do you know what do I need to configure to enable ALL the images in that field?

General setup: I'm using Drupal 7x, with a sub-theme from Bootstrap and Views 7.x-3.20.

Views setup: it was created as an Unformatted list and it's showing just Fields one of them is the image field you can see below.

In the red box I've seen the ALL option, but it just doesn't appear in my setup.

Thanks,
Daniel.

You see the limited number of values (as a drop-down) in Views instead of a text field where you can type in all or some number because you have limited the number of values this field can take in its settings.

Check your Content type field settings for "Imagenes" and see if it's limited:

Since this is in your field settings it's enough to set your Views field multi-settings to 5 because there are never more than five values in this particular case.


What's are the variables can be used from content.field_name with multiple values I have created a field using test list type and rendering using custom twig code as below:

 {% for key, item in content.field_scope if key|first != '#' %}

{{ item }}

 {% endfor %}

In "for" argument, I manage to get value of key and item from the field. What are the other value which can be used?

{{ content.field_name }} is a renderable array. You are meant to simply print out {{ content.field_name }}.

If you need to change what is actually in the output, then you should create a field--field-name.html.twig or another applicable twig template suggestion name that works for you. Within it, you would have:

{% for item in items %}

{{ item.content }}

{% endfor %}

That way, any time you render either {{ content }} containing this field or {{ content.field_name }} it will use that template and render it consistently.

Here is a real world example. I am working on a project where one of the fields is a select list of about 20 options. These option values correlate to icons in the theme, and they can use this field to attach an icon to a title field for presentation purpose.

Here is my twig file for field--field-icon.html.twig:

{% for item in items %}
  <svg class="icon"><use xlink:href="/themes/custom/mytheme/build/img/svg-sprite.svg#{{ item.content }}"></use></svg>
{% endfor %}

item.content is just my field value, you don't have to do anything special here. So if the editor selects 'Alert', which the select list value is 'alert', item.content will print alert and the proper icon will display from the svg spritesheet.

Here is a similar question I answered which may provide further insight on theming fields.


How to remove default div wrappers from fields output via custom field formatter? I have a custom field and custom field formatter created in Drupal 8. I need to remove the default FIELD VALUE wrappers so that I can build an HTML table with the field values.

The field formatter is currently using a custom twig template, but I <div>'s are being rendered prior to the template, so I can't remove them there.

How can this be accomplished?

The div wrapper you are looking for is probably in field.html.twig. Drupal provides a theme name suggestion for a custom field type automatically, so you can override this template by placing field--myfieldtype.html.twig in the theme templates folder.

If you want you can deliver a default template with the custom field module, like the comment module does for the comment field:

core/modules/comment/templates/field--comment.html.twig

Then you need to define a theme hook in mymodule.module.

Example from the comment module:

/**
 * Implements hook_theme().
 */
function comment_theme() {
  return [
    // ...
    'field__comment' => [
      'base hook' => 'field',
    ],
  ];
}


Help with the sub-groups for Organic groups module I want to have this functionality in my website, but I really do not know how to use this module, I tried to follow this tutorial http://mohitaghera.drupalgardens.com/content/creating-subgroup-organic-groups

But there is a step I do not understand, you have to set the sub-group content type a group or a group content in the og settings?

Please have someone used this module? how to use it. How does it work, what is the workflow of this module.

Read this post, it will help you to figure out how to use the sub-og module

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


Should I run tests for the entire core and contributed modules, or only for the codes I wrote? I am planning to integrate unit testing in CI/CD. I wonder what would be the good practice for running.

Should I run tests for the entire core and contributed modules, or only for the codes I wrote?

The whole point of doing unit testing is verifying code functionality and preventing regression bugs on new code changes. Unless you're working on some development branch (i.e. not a release), running 3rd party vendor (core, contrib modules) unit tests is redundant; you should write unit tests for code that you're maintaining and trying to keep reliable and bug free.


Problem with displaying field using Views My goal is to use Search API so that I can create a custom search page using Views.  I want to add the "rating" widget (rate module), but there is no way to include it in the Search API fields. Thus, I tried to fix it by adding custom field to Search API index.

function rate_entity_property_info_alter(&$info) {
  $info['node']['properties']['widget'] = array(
    'label' => t('Rating widget'),
    'description' => t('Rating widget'),
    'getter callback' => 'display_widget',
  );
}
function display_widget($node) {
     print rate_generate_widget('1', 'node', $node->nid);
}

However, I am getting AJAX errors

and problems with displaying widgets.

Please can someone help me to solve this problem.

Thanks

If this is a Solr/ElasticDB search backend under Search API, you could try this approach.

Create a view mode on the node type (ex. Search Result), then create a template with the html markup when rendered for it. Include all the fields in the display and configure the formatters as you want them.

Next, install Search API View Modes, and configure that view mode to be indexed. It will render that node before indexing it into a new field (search server side). Then, you can create a view display that shows that field, which is just HTML, and bypass some of these issues.

I use this method in every Search API based search I encounter. You're basically storing the rendered HTML on the search server, then printing that as the result.

I can't tell if you are on Drupal 7 or 8. Note that the 8.x branch 'works' but may have some bugs. I have only been able to test simple setups and not use it on production like the 7.x branch.


how to view data row table related to user only? Good day, I need to create a view, which only shows data related to the user logged in user.
When I have a user called "john smith", I create a contents as I like, BUT I don't want other users to see them.

A content can have multiple input from different users, so ONLY admin can see all content.
while, each user, can only see his OWN content which he posted him self.

Think of it like a database system, where each student can add projects for his own records, but each student can see ONLY his own.

I tried looking around first, and I came across this question https://stackoverflow.com/questions/20840490/drupal7-filter-view-based-on-current-users-roles which seemed bit related, but I got lost in the too much explanation because they not entirely related to what I want to achieve.

In user roles permission, I perfectly found (add content, edit own content) but its missing one more thing which I want.."view own content"!!

I think it has something to do with filed permission, or something like when adding a content, set its permission to be view my that user only.

In coding the view to show ONLY table rows related to the that user, maybe something like this:

global $user;
if (in_array (student_field_name  == $user))
//view the row related to that user;

if (in_array('administrator', $user->uid))
//show ALL data rows available

To summarize, I want the user to be able to SEE his own data only.
while admin will be able to see ALL content view of that page.

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

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

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

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


Contextual filter using taxonomy alias I have a list of nodes that I want to attach as a block to another node using a contextual filter. Depending on the URL alias I want a specific node to be attached to it. The problem is that I want the contextual filter to be based on a taxonomy alias as oppose to a taxonomy ID.

I looked at this solution: Contextual filter with a block view and this one: Views contextual filters taxonomy name  and I'm close however the second solution has an option that I can't find on my version. It reference a Filter Value Type option which would allow me to Term name converted to Term ID. This is exactly what I need, however I can't find this option.

I followed the instruction step-by-step; I tried creating different View and display versions, different items as my Contextual filter but nothing works.

These links are from 2011 and 2012, respectively. I'm using Drupal 8, so I'm wondering if this option has been removed or replaced with some other way to accomplish this task. Either way, I'd appreciate it any help.

Thanx

I got it to work by adding a relationship to a taxonomy field that exposed the taxonomy name. Then on the Contextual Filter I followed what the links said in regard to Specify validation criteria. But since I still can't find the Filter Value Type option, I just set the Case option to Capitalize each word and in the More section I checked the Transform spaces to dashes in URL option.

This allowed the value in the URL (which was a URL alias) to match my Taxonomy term field.

I don't know if there's an easier way to accomplish this and I'd still like to know why I couldn't find the Filter Value Type option, but at least it's working.


How to update a field in Drupal 7 without saving whole node I wanted to update a field that is not seen by the user, but I would turn off and on (boolean) quite a lot (and for thousands of nodes). I initially used field_attach, but this had the unhappy effect of removing a file that was also attached to the node (this is a drupal bug).

It took a lot of searching, but I found the solution combining a couple of other peoples snippets. I put it below so hopefully may save someone some time.

For the record: Apparently it is bad practice to edit fields directly like this, however, I really needed to for this use case and I have yet to find any issues. You have been warned!

function common_update_db($entity_id, $field_name, $value, $clear_cache) {
  foreach (array('data', 'revision') as $table) {
    $result = db_update('field_'.$table.'_'.$field_name)
        ->fields(array(
            $field_name.'_value' => $value,
        ))
        ->condition('entity_id',$entity_id,'=')
        ->execute();
  }
  if ($clear_cache) {
    cache_clear_all("field:node:" . $entity_id, 'cache_field');
  }
}

This will update the field and the revision field. If you send clear_cache = TRUE, it will also clear that nodes cache. This only works for *_value fields and nodes, but it's easy to modify.

Examples:

common_update_db(1234, field_run_cron, 1, TRUE);

on node 1234, set field_run_cron value to 1 and clear the cache for immediate visible effect to the user.

common_update_db(1234, field_run_cron, 0, FALSE);

on node 1234, set field_run_cron value to 0, don't clear cache as the user doesn't see this field anyway.


private messages and views I find the perfect module to do what i want to do in private messages (put a "Send author a message" to open a contact between a user and an author)

Unfortunately, i didn't find a way to put that "Send author a message" when i use views module. I display my article by fields and i don't find that field.
I'm just begin to discover Drupal 7 so i don't know if i do the right thing.

I searched on the module section in drupal.org and i saw that the only module available for views with private messages was for Drupal 6.

Maybe someone know if there is a solution to integrate private messages with views (i'd love to have the same behavior that flags has with views: add the flag with add field)
I looked at "advanced section" and "add relationship" to see if i can find something to add like flag but i didn't find anything.

ps: sorry if i made many mistake in english.

Thanks,
Arno

That should be there. Make sure that you add a relationship to the user/author of the nodes that you are displaying, that might be the missing piece.

Note that this is the only available views integration as of now. Privatemsg and it's group of submodules rely heavily on dynamic queries and being able to alter them. That and the rather complex queries which can't be replaced by Views easily.


Using pre-process to wrap multiple regions in html I'm using Omega, and have 6 regions in a particular zone.  The first and second region span the width of the zone with 12 columns, and the other 4 are 1/4 in-line blocks.  I want to set the background for the 4 in-line blocks to a particular color.  How can I wrap those 4 regions inside a div so I can set the background color?

How can I wrap those 4 regions inside a div so I can set the
  background color?

You can use .tpl files for that.

<?php if ($region_first || $region_second): ?>

        <?php if ($region_first): ?>

                <?php print $region_first; ?>

        <?php endif; ?>

        <?php if ($region_second): ?>

                <?php print $region_second; ?>

        <?php endif; ?>

<?php endif; ?>


Override default language via URL parameter With the Internationalization module, is there any way to override the default language selection?

We have a site with two languages, EN and FR, and we'd like to send out an email newsletter that has various links to the secondary (non-default) language content.
The Language Negotiation is set to "Path prefix with language fallback", and directs them to the default language, even if we use the full language prefixed URL, ie:

www.example.com/fr/content
--gets sent to--
www.example.com/en/content

What would be ideal is if we could pass an argument like this:

www.example.com/fr/content?force_language=FR

Any solutions out there?

It's been more than a few years since I've done this in Drupal 6, so things may be a bit vague and hazy. I do remember there being an order menu for this, where you could say that language gets selected first by cookie, then browser language, then user preference, then path prefix, or change the order entirely.