Display user picture in User Relationship block In my social networking site, i have provided for users to be able to forge relationships between themselves using the User relationship module. This is working fine. I am creating a tab using quicktab to display the user their relations when he or she clicks on them. I assign my tab the block value :
My Relationships: All relationships (user_relationship_blocks:my-all)
which is already available in DRUPAL. However it does not show the picture of the user with whom the relationship is. I thought of using views but in views all relationship are showed. What i need is something like this:

Followers

User A (A's Picture)   User B (B's Picture)

Following

User C (C's Picture)   User D (D's Picture)

If this can be done using views or any other way, please advice...thanks

Edit/Update:

I tried using the default block provided:
My Relationships: All relationships (user_relationships_blocks:my-all)
This is under structure/blocks...I just enable it and display it...Its showing:

Now i just need that the user picture also appears besides their name...Please advice/help...DO i have to do some changes in this block, if so, then just get me on starting line, i will carry it forward :)
Thanks

$view = new view();
$view->name = 'user_freinds';
$view->description = 'Shows someone\'s related users';
$view->tag = '';
$view->base_table = 'user_relationships';
$view->human_name = 'User freinds';
$view->core = 0;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Defaults */
$handler = $view->new_display('default', 'Defaults', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'mini';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['style_plugin'] = 'grid';
$handler->display->display_options['style_options']['grouping'] = '';
$handler->display->display_options['style_options']['columns'] = '5';
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['inline'] = array(
  'name_1' => 'name_1',
);
$handler->display->display_options['row_options']['separator'] = ', ';
/* No results behavior: Global: Text area */
$handler->display->display_options['empty']['area']['id'] = 'area';
$handler->display->display_options['empty']['area']['table'] = 'views';
$handler->display->display_options['empty']['area']['field'] = 'area';
$handler->display->display_options['empty']['area']['empty'] = TRUE;
$handler->display->display_options['empty']['area']['content'] = 'لا يوجد محتوى';
$handler->display->display_options['empty']['area']['format'] = 'plain_text';
/* Relationship: User relationships: Requestee user */
$handler->display->display_options['relationships']['requestee_id']['id'] = 'requestee_id';
$handler->display->display_options['relationships']['requestee_id']['table'] = 'user_relationships';
$handler->display->display_options['relationships']['requestee_id']['field'] = 'requestee_id';
/* Relationship: User relationships: Requester user */
$handler->display->display_options['relationships']['requester_id']['id'] = 'requester_id';
$handler->display->display_options['relationships']['requester_id']['table'] = 'user_relationships';
$handler->display->display_options['relationships']['requester_id']['field'] = 'requester_id';
/* Relationship: User relationships: RTID */
$handler->display->display_options['relationships']['rtid']['id'] = 'rtid';
$handler->display->display_options['relationships']['rtid']['table'] = 'user_relationships';
$handler->display->display_options['relationships']['rtid']['field'] = 'rtid';
/* Field: User relationship types: Plural name */
$handler->display->display_options['fields']['plural_name']['id'] = 'plural_name';
$handler->display->display_options['fields']['plural_name']['table'] = 'user_relationship_types';
$handler->display->display_options['fields']['plural_name']['field'] = 'plural_name';
$handler->display->display_options['fields']['plural_name']['relationship'] = 'rtid';
$handler->display->display_options['fields']['plural_name']['label'] = '';
$handler->display->display_options['fields']['plural_name']['exclude'] = TRUE;
/* Field: User: Picture */
$handler->display->display_options['fields']['picture']['id'] = 'picture';
$handler->display->display_options['fields']['picture']['table'] = 'users';
$handler->display->display_options['fields']['picture']['field'] = 'picture';
$handler->display->display_options['fields']['picture']['relationship'] = 'requestee_id';
$handler->display->display_options['fields']['picture']['label'] = '';
$handler->display->display_options['fields']['picture']['element_label_colon'] = FALSE;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'requestee_id';
$handler->display->display_options['fields']['name']['label'] = '';
/* Sort criterion: User relationship types: Plural name */
$handler->display->display_options['sorts']['plural_name']['id'] = 'plural_name';
$handler->display->display_options['sorts']['plural_name']['table'] = 'user_relationship_types';
$handler->display->display_options['sorts']['plural_name']['field'] = 'plural_name';
$handler->display->display_options['sorts']['plural_name']['relationship'] = 'rtid';
/* Contextual filter: User relationships: Requester user */
$handler->display->display_options['arguments']['requester_id']['id'] = 'requester_id';
$handler->display->display_options['arguments']['requester_id']['table'] = 'user_relationships';
$handler->display->display_options['arguments']['requester_id']['field'] = 'requester_id';
$handler->display->display_options['arguments']['requester_id']['default_action'] = 'default';
$handler->display->display_options['arguments']['requester_id']['exception']['title_enable'] = TRUE;
$handler->display->display_options['arguments']['requester_id']['default_argument_type'] = 'user';
$handler->display->display_options['arguments']['requester_id']['default_argument_options']['user'] = FALSE;
$handler->display->display_options['arguments']['requester_id']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['requester_id']['specify_validation'] = TRUE;
$handler->display->display_options['arguments']['requester_id']['validate']['type'] = 'numeric';
$handler->display->display_options['filter_groups']['groups'] = array(
  1 => 'AND',
  2 => 'AND',
);
/* Filter criterion: User relationships: Relationship status */
$handler->display->display_options['filters']['approved']['id'] = 'approved';
$handler->display->display_options['filters']['approved']['table'] = 'user_relationships';
$handler->display->display_options['filters']['approved']['field'] = 'approved';
$handler->display->display_options['filters']['approved']['value'] = '1';
$handler->display->display_options['filters']['approved']['group'] = 1;
$handler->display->display_options['filters']['approved']['expose']['operator'] = FALSE;

/* Display: Block by type */
$handler = $view->new_display('block', 'Block by type', 'block_1');
$handler->display->display_options['defaults']['use_ajax'] = FALSE;
$handler->display->display_options['use_ajax'] = TRUE;
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['block_description'] = 'Display user\'s relationships grouped by relationship type';

/* Display: Block by user */
$handler = $view->new_display('block', 'Block by user', 'block_2');
$handler->display->display_options['defaults']['title'] = FALSE;
$handler->display->display_options['title'] = 'Related users';
$handler->display->display_options['defaults']['hide_admin_links'] = FALSE;
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'list';
$handler->display->display_options['style_options']['grouping'] = 'name';
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['defaults']['row_options'] = FALSE;
$handler->display->display_options['defaults']['fields'] = FALSE;
/* Field: User relationship types: Plural name */
$handler->display->display_options['fields']['plural_name']['id'] = 'plural_name';
$handler->display->display_options['fields']['plural_name']['table'] = 'user_relationship_types';
$handler->display->display_options['fields']['plural_name']['field'] = 'plural_name';
$handler->display->display_options['fields']['plural_name']['relationship'] = 'rtid';
$handler->display->display_options['fields']['plural_name']['label'] = '';
$handler->display->display_options['fields']['plural_name']['exclude'] = TRUE;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'requestee_id';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['exclude'] = TRUE;
/* Field: Broken/missing handler */
$handler->display->display_options['fields']['updated_at']['id'] = 'updated_at';
$handler->display->display_options['fields']['updated_at']['table'] = 'user_relationships';
$handler->display->display_options['fields']['updated_at']['field'] = 'updated_at';
$handler->display->display_options['fields']['updated_at']['label'] = 'Added';
$handler->display->display_options['fields']['updated_at']['exclude'] = TRUE;
/* Field: User relationship types: Name */
$handler->display->display_options['fields']['name_1']['id'] = 'name_1';
$handler->display->display_options['fields']['name_1']['table'] = 'user_relationship_types';
$handler->display->display_options['fields']['name_1']['field'] = 'name';
$handler->display->display_options['fields']['name_1']['relationship'] = 'rtid';
$handler->display->display_options['fields']['name_1']['label'] = '';
$handler->display->display_options['block_description'] = 'Display user\'s relationships grouped by user';


Username as a path to Profile page I am trying to set up username as a main path to the user profiles in Drupal 7; for example, I would like to have mypage.com/someusername as path alias for the profile of the user that uses "someusername" as username.

I am using the Profile 2 module as well. I tried everything, but I cannot achieve this.

If you use the Pathauto module, you can set an automatic alias for the user profiles using a token that is replaced with the username. In Pathauto for Drupal 7, the default pattern for user paths is /users/[user:name], which is the pattern I would suggest to use to avoid conflict with path defined from other module. As you don't control the username chosen from a user, it could happen the username is admin, which conflict with the path used from system.module for its own menu callback.

If you want to use a different token, the list of available tokens is available right after the text field used for the pattern to use.

What I reported is still valid for Drupal 6; the difference is that the token for the username is [user].


Using Php Filter with Ckeditor? I need to use Php Filter with ckeditor.
Problem is that Ckeditor change this:

  <?php echo "hello";?>

to

  <p>&lt;?php echo "hello";?&gt;</p>

How can I solve this?

I already added this:

config.allowedContent = true;

under Custom JavaScript configuration at: admin/config/content/ckeditor/edit/Full

But it didn't help.

I also make sure I checked Php evaluator under Enabled filters at admin/config/content/formats/full_html

Change the 'insertElement' function for 'insertHtml' function

editor.addCommand('phpcode', {
  exec : function() {
    editor.insertHtml('
<?php echo "hello"; ?>
');
  }
});

Hope it will be work.


How to join tables with hook_views_data I have two tables activity and activity_map. I need to join both the tables by aid. Below is my code for hook_views_data. Base table is working fine including custom text handler. But I do not see the joined table(activity_map) fields (entity_id, entity_type)  either in fields section nor in arguments or filters. Am I missing anything?

  <?php

    /**
 * Implements hook_views_data
 */
function activity_teamie_views_data() {
  $data['activity_teamie']['table']['group'] = t('Activity');
  $data['activity_teamie']['table']['base'] = array(
    'title' => t('Activity'),
    'field' => 'aid',
    'help' => t('Activity feed item')
  );
  $data['activity_teamie']['aid'] = array(
    'title' => t('Activity ID (aid)'),
    'help' => t('Activity ID'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_numeric'
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_numeric'
    ),
    'sort' => array(
      'handler' => 'views_handler_sort'
    )
  );
  $data['activity_teamie']['template'] = array(
      'real field' => 'template',
      'title' => 'Activity',
      'help' => 'Text describing the activity',
      'field' => array(
        'handler' => 'activity_teamie_handler_field_activity_text',
      ),

  );
  $data['activity_teamie']['data'] = array(
    'title' => 'Data',
    'help' => 'Data array',
    'field' => array(
      'handler' => 'views_handler_field',
    ),
  );
  $data['activity_teamie']['created'] = array(
    'title' => t('Created'),
    'help' => t('Created timestamp'),
    'sort' => array(
      'handler' => 'views_handler_sort_date'
    )
  );
  $data['activity_teamie']['updated'] = array(
    'title' => t('Updated'),
    'help' => t('Updated timestamp'),
    'field' => array(
      'handler' => 'views_handler_field_date',
    ),
    'sort' => array(
      'handler' => 'views_handler_sort_date'
    )
  );

  /* ACTIVITY MAP */
  $data['activity_teamie_map']['table']['group'] = t('Activity');

  // Join with the {activity} table
  $data['activity_teamie']['table']['join'] = array(
    'activity_teamie_map' => array(
      'left_field' => 'aid',
      'field' => 'aid'
    )
  );
  $data['activity_teamie_map']['aid'] = array(
      'title' => t('Aid Map'),
      'help' => t('Aid Map'),
    'field' => array(
          'handler' => 'views_handler_field',
  ),
      'filter' => array(
        'handler' => 'views_handler_filter_numeric'
  ),
      'argument' => array(
        'handler' => 'views_handler_argument_numeric'
  )
  );
  $data['activity_teamie']['entity_type'] = array(
    'title' => t('Entity type'),
    'help' => t('Entity type of the associated entity'),
  'field' => array(
        'handler' => 'views_handler_field',
  ),
    'filter' => array(
      'handler' => 'views_handler_filter_string'
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string'
    )
  );
  $data['activity_teamie']['entity_id'] = array(
    'title' => t('Entity ID'),
    'help' => t('Entity ID of the associated entity'),
  'field' => array(
        'handler' => 'views_handler_field',
  ),
    'argument' => array(
      'handler' => 'views_handler_argument_numeric'
    )
  );
  return $data;
}

$data['activity_teamie']['table']['join'] = array(
  'activity_teamie_map' => array(
    'left_field' => 'aid',
    'field' => 'aid'
  )
);

You actually want to join the other way round.kk

A general tip, try to think of some kind of similar join relation in Drupal core and look it up in views/modules/$module.views.inc

$data['activity_teamie']['entity_id'] = array(

Isn't entity_id part of activity_teamie_map?


Unable to install Pathauto, pathauto.settings already exists in active configuration After upgrade from 8.7.10 to 8.9.13, i updated the pathauto module from ftp and trying to install from drupal admin but it showing an error like
"Unable to install Pathauto, pathauto.settings already exists in active configuration."
Based on the post
https://www.drupal.org/forum/support/post-installation/2016-01-29/already-exists-in-active-configuration-issue
i deleted the pathauto.settings row from config table and cleared the cache and trying to install the module , but still showing the same error.
Please help me.
Thanks in advance.

Before trying to do whatever I suggest below first of all have a full backup of the site.
It seems pathauto module is not uninstalled properly.
To solve your problem you can just delete the pathauto.settings from config using drush.
Use the below command to delete the conflicting config.
drush cdel pathauto.settings
It will delete the existing pathauto configuration.Then you can install the pathauto module.
You should consider using composer for the module management.


Alter form to have single radio button term reference checked by default I have a taxonomy reference field and in the node creation form there will be only one value allowed and I guess I use a radio button and I want it to be enabled by default.

I thought I can do it with form_alter but on inspection in krumo I see the default values are set to the concrete term id.

If I would want to set that id (which I do not know) it could look like:

 form['field_abteilung'][LANGUAGE_NONE]['#default_value'] = 12345;

For various users and their roles there will be other another allowed option in this form and I just want to do sth like

 form['field_abteilung'][LANGUAGE_NONE].... My-single-radio-button = checked;

Update

I saw I can find out the single option by looking into

$form['field_sektion'][LANGUAGE_NONE]['#options'][2]

I tried it but get an error about missing index 'field_sektion' which confuses me.

update 2
It takes some time, I maybe should have mentioned that the field in the end should be the access control field of https://drupal.org/project/workbench_access , that module also alters the form; I disabled the field's access function first and now need to rebuild all

the way I did it now, is following - First I tried to use a hook provided by workbench access itself which supposed to be for that use case, look here
https://drupal.org/node/2019473

But it would not work for me, so I did :
this results in a select box with only one possibility. Not the best UX style maybe and later I will try to hide the element, maybe with ds module.

function workbench_access_crud_by_state_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id != 'hardware_antrag_node_form') {
    return;
  }
  //sdpm($form);
  $option_arr = $form['field_tu'][LANGUAGE_NONE]['#options'];
  // remove 'none'-option
  array_shift($option_arr);

  // look for field for workbench_access and replace options
  $wb_access_field = $form['workbench_access_fields']['#value'][0];
  $form[$wb_access_field][LANGUAGE_NONE]['#options'] = $option_arr;
}


Insert a view with a context using php? I know I can insert a view using the following code:

 <?php
    $view = views_get_view('VIEWNAME');
    print $view->preview('default');
 ?>

In my view I have a contextual filter of user: name

When I insert this view using the Display Suite module I have this option from Display Suite:

I was wondering if there is a way to pass this context to the view, like Display Suite does, using php code only.

You can set the default value for the contextual filter through URL and then in your code use $view->set_arguments() to pass the argument.


create drupal 7 webform programmatically? I have already created a webform and I need to fill it programatically.

how can I create webform ? Can i create it like node creation:

$node = new stdClass()
$node->type = 'webform'
$node->webform['components'][1]['value'] =  'sss'

See code below:

function _add_webform_components($node) {
  $components = array(
    0 => array(
      'name' => 'First name',
      'form_key' => 'first_name',
      'type' => 'textfield',
      'mandatory' => 1,
      'weight' => 1,
      'pid' => 0
    ),
    1 => array(
      'name' => 'Name',
      'form_key' => 'name',
      'type' => 'textfield',
      'mandatory' => 1,
      'weight' => 2,
      'pid' => 0
    ),
    ... and so on

  );

  webform_ensure_record($node);
  foreach($components as $component) {
    $component['nid'] = $node->nid;
    $component['extra']['title_display'] = 'inline';
    $node->webform['components'][] = $component;
    webform_component_insert($component);
  }
  $email = array(
    'nid' => $node->nid,
    'email' => 'name@example.ch',
    'subject' => 'default',
    'from_name' => 'default',
    'from_address' => 'default',
    'template' => 'default',
    'excluded_components' => array(),
  );
  webform_email_insert($email);
}


Where do I edit the HTML surrounding a field's output? I am working on a site that has an image Field (machine name: field_resp_media) that outputs images.

I simply need to add an attribute to the <img> tag this field outputs.

I've run keyword searches in modules/contrib and modules/custom, and I came up with nothing.

Would anyone know what file I need to edit and add this attribute?

In Drupal, you don't edit any file belonging to a module/theme you didn't create.

Rather, in your case, you use the hooks Drupal makes available to change the output a module or a theme creates with a theme hook.
In the case of an image field created with the field API, the theme hook that outputs the HTML for the image field when it is rendered on page is theme_image_formatter(). What you need to do is overriding that theme hook in a module or in the theme you use for the site.

Since you don't need to totally change the output from that theme hook, you just need to implement hook_preprocess_image_formatter(&$variables) and add your attribute to $variables['item']['attributes'].

Keep in mind that hook_preprocess_image_formatter(&$variables) is invoked for every image field used by Drupal, so you need to be sure you are altering the output of the right image field.

As per implementing hook_preprocess_image_style(), this hook is not necessarily called for an image field, since theme_image_formatter() contains the following code.

  if ($variables['image_style']) {
    $image['style_name'] = $variables['image_style'];
    $output = theme('image_style', $image);
  }
  else {
    $output = theme('image', $image);
  }

It is just invoked when the image field uses an image style. Plus, it would be invoked every time an image style is used, which doesn't necessarily mean when a image field is rendered on a page.

Similar problem there is with hook_preprocess_field(), which would invoked every time a field is rendered with theme('field').


Localizable text in custom layout? I'm customizing Display Suite-suggested tpl by adding "Jump to top" links at the bottom of each teaser and I want to properly localize the link text.

Now I am unclear as per the usability of the Variable module (that had to be installed along with i18n). Can I add my own variable (say, jump_to_top_link) somewhere in the Variable admin panel, without writing my own module? Or is Variable meant only as an API for modules?

I don't want to learn module development now, but I want my custom text to be scalable and easily manageable from one place, instead of hard-coding strings and ifs.

Would anyone be willing to shed light on how to approach the problem?

Regards,
Artur

You can set the translations for each specified language in the strings settings part of the internationalization module: /admin/config/regional/i18n_translation

To show it in a template file you simply use the t() function to wrap your text - which translates text for you and automatically adds new text defined in the t() function to the strings page.

See http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/t/7

If you are hardcoding links with your text you can use l(), so if you have say a text link and want the text to be translated you would use l() and in it define your text using t() - something like this:  http://api.drupal.org/api/drupal/includes--bootstrap.inc/function/t/7

See http://api.drupal.org/api/drupal/includes--common.inc/function/l/7 for its usage.


Server IP Address in Drupal PHP Status How does one get the server IP address of the server you are on to appear at http://examplehost.com/admin/reports/status/php -- at the very bottom ? I keep getting 127.0.0.1. This is on two web servers that are behind a load balancer.

The admin/reports/status/php is actually the output of phpinfo() and it simply shows your PHP configuration summary.

https://stackoverflow.com/questions/3202872/php-serverserver-addr-variable-always-returns-127-0-0-1
suggests using this code to get the real IP:

getHostByName(php_uname('n'));


Uninstalling modules, specificially ANSWERS I have uinstalled and reinstalled this module MANY times, all of the fields i have created and settings, and ADD question content are there no matter what i do.

here's the order i did

unchecked in modules section
then uninstalled, then deleted via ftp
then clear cache

everything is still there, any help is appreciated, thanks!!

signed--newbie

If a module doesn't delete its tables or content in hook_uninstall, then the content is not automatically removed when you disable the module.

You can see here that answers does not clean up after itself when it is uninstalled, probably for good reason.

If you want to purge everything, you will need to delete the nodes, fields, and bundles manually at admin/content and admin/structure/types or by writing some code that uses field_delete_field() or field_attach_delete_bundle().


Display all nodes for which user appears as a field on that user's profile? I have a site with a content type "Projects," which has a field "Project Manager" that takes a user. Is there a good way to display all Projects for which a user appears as the Project Manager for that Project on that user's profile?

Update:

Here is what I have so far in user_profile.tpl.php

...
function my_module_user_view($account, $view_mode, $langcode) {

  $my_field = 'field_pm';
  $uid = $account->uid; // The uid of the user being viewed.
  $query = "SELECT entity_id FROM {field_data_{$my_field}} WHERE {$my_field}_target_id = :uid AND bundle='user'";
  $args = array(':uid' => $uid,);
  $result = db_query($query, $args);
  $nids = $result->fetchCol();
  if (count($nids)) {
    $projects = node_load_multiple($nids); // Load all projects where that user is a PM
    foreach ($projects as $project) {
      $account->content['field_pm_projects'][0]['#markup'] = $project->title;
    }
  }
}
?>

<div class="profile"<?php print $attributes; ?>>
 <?php print render($user_profile); ?>
 <?php print $account->content['field_pm_projects']; ?>

Add a contextual filter for that entity reference field and in its settings, provide default: uid from url. That will only show nodes where the uids match.

There are two options, "referenced" and "referencing".. I'm pretty sure you want referenced but try both.


How to make user pictures public files? I need to pass some URLs to user pictures via AJAX. I can't, however, pass private://filename.jpg because client can't open it.
Are there some settings to configure where I can change to public space?

You need to change the image field associated with the user profile to Public, and then you need to migrate any existing private image files to the new public directory.  Here's a write-up on working with files in Drupal 7.


How to check if search_index's solr is running? To prevent fatal errors, I need to check if solr is running.

Given:

$solrIndex = \Drupal::entityTypeManager()
  ->getStorage('search_api_index')
  ->load('global');

How do I check if the solr server that $solrIndex is pointing to is online?

There is an ->isAvailable() method on the server object when you call the $index's ->getServerInstance() method, but it returns a false positive when the solr server is stopped:

I'm surprised I can't check it from the server object, but this returns a false positive when solr is stopped:

$false_positive = $solrIndex->getServerInstance()->isAvailable();

The SolrConnector plugin provides a pingServer() function that will determine it the endpoint can be accessed, so to really test it you likely need to be able to call that.

I'd first check to see if there is an abled server by calling $solrIndex->isServerEnabled().

Then I'd get the server, its backend, the connector, and run the ping:

$server = $solrIndex->getServerInstance();
$backend = $server->getBackend();
$connector = $backend->getSolrConnector();
$response = $connector->pingServer();

or just

if( $solrIndex->getServerInstance()->getBackend()->getSolrConnector()->pingServer() ){
  // Yup
}
else {
 // nope
}

The return value from pingServer() is:

  The latency in milliseconds if the core can be accessed, otherwise
  FALSE.


Unable to save content title I am using feeds to import content to my custom content type, Clients.

After the Import, the mapping comes up fine, the Content Title displays in the Page View Node, however, when I go to edit the content, the Title comes empty & also does not save the updated title.

It was working fine a few days back. I haven't made any changes or updates to any modules.

Please advice.

Thanks

I've had something similar happen to me before. Turned out that Automatic Entity Label module was overwriting the title field with an empty token.


Taxonomy terms follow/unfollow module Is there any module or options to allow site users to follow or unfollow the taxonomy terms?Basing on the following terms, I have to send a notification if any new post has been created on those particular terms.

I think that this module will do the trick: Subscriptions.


Adding Pager to entity referenCED field display I have two content types: Parent and Child

I have an entity reference field (called "Link") in parent content type referencing it to child content type.

I am using inline entity forms module for the entity reference field .

I want to know if there is a way to achieve the following:

Question 1:

I want to have a read more button on parent content type, which would open the first entity referenced child page.

Question 2:

I want to have a pager in the child page which would link to the other child pages of the same entity referenced parent content type.
(something similar to what books module provides for book child in child pages)

Any help would be highly appreciated. Thank You.

There might be better way of doing that.

But one of the way will be to use views module

Answer to question 1:

Go to your_site/admin/structure/types/manage/content_type/display
Change the reference field format to Rendered entity
Click the setting and make sure Show links is checked

Answer to question 2:

Install the module views if you don't have it already
Go to yoru_site/admin/structure/views/add
Give your view name for example read more button to parent content type
Unchecked Create a page and Check Create a block
Click Continue & edit
Change format to "Table"
Click add filed and select the fields you want to show
Click add Filter criteria and select the criteria you want
Click the Advance and Add Contextual Filters
SelectContent  Content: Nid"
Select Relationship as content entity referenced from your_xyz
Change the option for When the filter value is NOT available to Provide default value and select Content ID from URL.
Change When the filter value IS available or a default is provide to Specify validation criteria and select Content from Validator select field, and select the parent content.
Make sure Filter value format  is = to Node ID
Make sure Action to take if filter value does not validate is = Hide view
Click Apply
Add a Relationship, Click add and select Entity Reference
Click Save.
Go to yoru_site/admin/structure/block, search for the new view name black you just added.
Click configure change the Visibility settings  to content type and select the parent content type.
Set the Region where you want the black to be display.


Organic Group visible only by authenticated user I want to make the list of OG visible only to authenticated user so they can request membership. I have created a view but it only display group the user is already member of.

When I change the group visibility from * Private - accessible only to group members* to Public - accessible to all site users this make the group visible to anonymous user too.

I used the Content Access module to deny access to anonymous user.

In your Organic Group content type admin interface (admin/structure/types/manage/committee) a new ACCESS CONTROL tab appears. Unckeck anonymous user for the view View any committee content.

If authenticated user is check it will over-right Organic Group settings (ie. the Private / Public will have no effect and the content will be accessible to all authenticated user).

source


How can I retrieve the current node ID on a custom route? I have a new route and the yml file looks like this:

rsvplist.form:
  path: '/rsvplist'
  defaults:
    _form: '\Drupal\rsvplist\Form\RSVPForm'
    _title: 'RSVP to this Event'
  requirements:
    _permission: 'access content'

From the module root directory, I have src/Form/RSVPForm.php, and inside is where I have the build form function that looks like the following:

public function buildForm(array $form, FormStateInterface $form_state) {
    $node = \Drupal::routeMatch()->getParameter('node');
    $nid = $node->nid->value;

    $form['email'] = [
        '#title' => t('Email Address'),
        '#type' => 'textfield',
        '#size' => 25,
        '#description' => t('We will send updates to the email you provide.'),
        '#required' => TRUE,
    ];

    $form['submit'] = [
        '#type' => 'submit',
        '#value' => t('RSVP'),
    ];

    return $form;
}

When I clear the site cache and refresh the page: mylocal.com/rsvplist, I see the following error:

Notice: Trying to get property 'nid' of non-object

I initially used the following code to get the node

$node = \Drupal::routeMatch()->getParameter('node');
$nid = $node->nid->value;

If I change the last piece of code to this:

$nid = $node->id();

I see the following error:

Error: Call to a member function id() on null

How can I get the node id when am on the new route?

Reference here

Your route doesn't have a parameter called node, so therefore $node is null.

In order to make node available as a parameter you have to be on a route that has node as a parameter.

So to add the node parameter to your route, you can do like this:

rsvplist.form:
  path: '/rsvplist/{node}'
  defaults:
    _form: '\Drupal\rsvplist\Form\RSVPForm'
    _title: 'RSVP to this Event'
  requirements:
    _permission: 'access content'
    _entity_access: 'node.view'
    node: \d+

And then you can add the $node parameter to your buildForm method, like this:

public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) {
  // Your form.
}

Since I added node: \d+ to your form, $node is now the loaded entity in the buildForm method.


For User i am giving option of color selections for a theme I am giving user the option of selecting the color(color scheme option like bartik) for the theme.For multiple users how do i save there color values for the theme and show their values alone depending on their login ? Colors for their header ,footer etc...

Help me provide with a solution.Thanks in advance

well, usually there are pre-defined color sets (like in batrik), so you save set name and then on hook_preprocess_page you chose which css to include.
So either this or you can add inline css styling using the same function drupal_add_css.

As for how to save this for each user, you can add extra field to user profile at Home » Administration » Configuration » People » Account settings
and then programmatically update it with needed value - example below, details here.

global $user;
$existing = user_load($uid);
unset($existing->pass);
$edit = (array) $existing;
$edit['field_somefield']['und'][0]['value'] = 'blah';
user_save($user, $edit);


Wildcard Search in Views Is there a way to use Wildcards (like *) in Views filters. I do not want to give the user the dropdown with all the operators but use a wildcard.
For example, when he writes name it will use "ends with", on name "begins with", on name "contains" and so on. Is there something out there that can do that, or do I have to write it on my own?

Rather than filtering on a certain field (and then exposing the filter), try adding a filter of the type 'Search terms'. That uses drupal's search module to search, which has much smarter ways of searching.


Set exposed filter date programmatically I would like to programmatically set an exposed filter for a field date (field_date) in a view.

Date has to be > of a specific date or between to dates.

I tried this, but it does not work. It ignores the filter.

$view = views_get_view('myview');
$view->set_display("default");
$view->get_exposed_input();

$exposed_filters["field_date_value_op "] = "between";

$exposed_filters["field_date_value"]["value"]["day"] = "";
$exposed_filters["field_date_value"]["value"]["month"] = "";
$exposed_filters["field_date_value"]["value"]["year"] = "";

$exposed_filters["field_date_value"]["min"]["day"] = 1;
$exposed_filters["field_date_value"]["min"]["month"] = 1;
$exposed_filters["field_date_value"]["min"]["year"] = 2014;

$exposed_filters["field_date_value"]["max"]["day"] = 1;
$exposed_filters["field_date_value"]["max"]["month"] = 12;
$exposed_filters["field_date_value"]["max"]["year"] = 2015;

$view->set_exposed_input($exposed_filters);
$view->execute();

Any idea? Thank you in advance.

Use the below after set_display line.

function mymodule_views_pre_view(&$view) {
  if ($view->name == 'myview_user'){
    $view->get_exposed_input();
    dsm($view->exposed_input['created']['min']);
    $view->exposed_input['created']['min'] = "2015-01-01";
    $view->exposed_input['created']['max'] = "2016-01-01";

    //$view->set_exposed_input($exposed_filters);
    $view->execute();
  }
}

Please refer the example


Facebook profile information display How can i display Facebook profile information like First name, Lastname, address. I am using Drupal for Facebook module in login with facebook a/c in my drupal web site.

You can use the Facebook OAuth (FBOAuth) module for this. Here is a quote about it (from the module's project page):

... provides authentication services and an API to perform actions against Facebook. This module allows users to login to Drupal through the service commonly known as "Facebook Connect". This module is built with simplicity and flexibility in mind, it provides login services (and does it well), and an API for performing any other actions you may want to write yourself to query against Facebook's APIs.
Features:

One-click login through Facebook.
Automatic import of user e-mail and profile information during initial login.
Integration with Profile module to map Facebook data to Profile fields. (Drupal 6)
Integration with Field module to map Facebook data to fields on users. (Drupal 7)
A flexible and direct API for modules to get authenticated and query Facebook's APIs (plus extensive documentation).
Extensive permission settings for Facebook data retrieval.
The ability to de-authenticate or unlink a Facebook account from a Drupal account.
Does not require any external libraries or downloads.


Drupal - user registration form- theming I need to do theming of user registration form

I m doing in this way

Module file

  function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
      $form['#theme'] = 'user_register';
    }

Template file

function mytheme_theme($existing, $type, $theme, $path){
  return array(
    'user_register' => array(
      'render element' => 'form',
      'template' => 'templates/user-register',
    ),
  );
}

function mytheme_preprocess_user_register(&$variables) {
  $variables['rendered'] = drupal_render_children($variables['form']);
}

And then I added user-register.tpl.php with my desired markup, a

<?php echo $rendered; ?>

Which is working fine . Now problem is that i need to rearrnage order of all fileds

Currently i have following

username, email and password, firstname , last name

I need sequence like username , firstname, email, lastname, password

can anybody tell me how to do this

Thanks

Look at poll module for a good example of this.

You can simply (with item being something in your form);

$form = $variables['form'];
$variables['item'] = drupal_render($form['item']);
$variables['rendered'] = drupal_render_children($form);

However there are other ways of achieving this and keeping the rearranging within the UI (/admin/config/people/accounts/fields etc) by using hook_field_extra_fields - poll module does this as well I've noticed.  It can be used for adding existing base fields which don't otherwise show in the Manage Display UI (like node author, created, updated times, etc) - here's an example for user picture.


How to create an average out of 3 Fivestar Fields? I want to create a Fivestar-Field which shows the average of 3 other ones.

Something like:

(Field A + Field B + Field C):3 = Field D

A,B and C are Fivestar-Fields which rate something and Field D is the average value out of the three.

I want the average to be showed via the star-widget of fivestar.

Is there a way to do that?

(I use Drupal 7)

Yes, You can able to do that using hook_node_presave

You can read three field values rating using $node and set using below command

$node->field_name_of_your_fourth_field[$node->language][0]['rating'] = $average_value;


Drupal 7 Commons 3 Vs Drupal Core + Commons modules I read Drupal Commons 3 and Original Drupal Core Updates and I wonder what the difference between installing the Drupal Commons 7 distributions and installing Drupal 7 plus the Drupal Commons modules available freely on Drupal.org is.

It seems to be safer to use Drupal core and the modules, and not to rely on entire distro updates.

Commons 2.x really had a lot of customizations in the install profile, deploying a well organized social network, but when i installed Commons 3.x, i had a sense of "hey, does it really customized anything?", that seems to be your feeling too.

I don't know the roadmap of the project, but it seems a little "naked" in this first version, compared to what they had inside the last Commons 2.x version.

For a project starting now, with what Commons 3.0 has to offer in the install profile(they can improve it, but if you install now, the newer versions of it will not came to you by just upgrading the modules), i think that what you're proposing could be a good thing, because my experience with Commons 2.x updates were really painful just to get some more views and panels improvements(and had to deal with so many Feature overrides), so it could be easier if YOU mantain your own profile, maybe creating one or using the Minimal or Standard themselves.


Use Token in contact form as default value I have a contact form build from the drupal core contact forms.

I am trying to prefill some fields from URL GET parameters like this. /?foo=bar But it seems that "default value" doesnt support tokens.

I want to use something like this: [current-page:url:args:value:foo] in the default field of my form field.

But this gets just rendered as plain text.
Any help is appreciated.

EDIT: Working solution with form_alter:

function MY_MODULE_form_alter(&$form, &$form_state) {
  $args = \Drupal::request()->query->all();
  $form['field_test']['widget'][0]['value']['#default_value'] = $args['foo'];
}

Maybe there is a solution with tokens relating to the topic?

Usually this is done in hook_form_contact_site_form_alter, like this:

function YOUR_MODULE_form_contact_site_form_alter(&$form, &$form_state) {
      $args = \Drupal::request()->query->all();
      $form['subject']['#default_value'] = $args['foo'];
}


Creating a watchdog log when publishing status changes on my own ContentEntityBase I have a hierarchy of Entities derived from ContentEntityBase. Now I want to create a log when the publishing status ( = status field) changes.

What is the best method to override/implement for this purpose? In the Entity that extends ContentEntityBase or in the Form that extends ContentEntityForm?

Or somewhere else? I don't want to use a hook!

Thanks. Rainer.

I would like to go for hooks (maybe events), hook_ENTITY_TYPE_update. You can find more about it in details here.

You only have to check if "status" field is being changed after update, and using the logging factory to put it into logs. This is also "form" independent (means it will run each time when entity gets updated), which is more general approach, and better for your system (more consistency).


Allow .svg logo uploading in theme settings How can I allow using .svg files for the logo field, in the theme settings?

The logo field in the theme settings says it accepts .svg format but it actually does not.  As per the error message that comes up only png jpeg jpg jpe gif extensions are allowed at the moment. Its a bug that is being worked on Unnecessary restrictions on logo format: Can't upload replacement SVG logo. Try any of the patches mentioned in the issue and report there if your issue is resolved.

Alternatively, for your theme (or custom theme) you can just put the logo.svg in the theme folder and modify the page.html.twig template file to use the .svg extension.


Drupal 7 Click tracking / traffic per node I'd like to track the number of times a node shows up in search results, the number of times it's clicked on in a search result, and the number of times it is displayed. I'd like all of this information to be readily available - perhaps stored in the content type? I could use some help determining the best practice here.

Alternatively. Could I use google analytics to track all of this somehow such that I could access the results from a custom designed module (which, can anyone point me in a direction on?)

Ultimately I want uses to look at a node and be able to see how much traffic came from in-site linking, off-site linking, and how many times users followed a link from the node to an external website.

Can I export google analytic data for each node somehow to drupal?

The google_analytics_reports module is a starting point for you to look at. I don't think it will cover all your requirements.


Drupal 7 views add one field as a URL to another I am using Drupal 7. I have a view where i filer a certain content type say "A" and display the below 2 fields
  Content: Title
  Content: File attachments

My File attachment formatter is set "Url to file".

What i am trying to achieve is to make 'Title' as a link with the 'File Attachment' URL

Thanks in advance!

for the Title, set it 'Exclude from display'
for the File attachments, 'Rewrite the output of this field' using the token for Title

Make sure the Title field appears above the file attachment, or the file attachment won't recognize it as a valid token when rewriting the output


How to get and apply current page query parameters from current AJAX request I'm having a hard time figuring out how to do this.

Essentially I have a table displaying users on a page. The table is paginated with the PagerExtender and sortable with the TableSortExtender.

Each user row has links with "use-ajax" classes; these links perform actions on the user, and then rebuild the current table after performing those actions -- this happens all in AJAX.

The problem I am having is, when I rebuild the table in AJAX, the current request is the request for the AJAX action, and not the request which built this page. This means when the table is rebuilt via AJAX, the pager and sort settings are lost and you are reset to the first page, without any sorts.

I have found code somewhere to pull the previous request, and get the URL and parameters, but I don't know how reliable this is or how to implement it:

$current_request = \Drupal::request();
$previous_url = $current_request->server->get('HTTP_REFERER');
$previous_request = Request::create($previous_url);
// $url_object is a Url with the previous page paramters and URL
$url_object = \Drupal::service('path.validator')->getUrlIfValid($previous_request->getRequestUri());

The problem with the above is:

I don't know how reliable the HTTP_REFERER will be
I don't know how to add the previous page request parameters to the current request, so the table is rebuilt properly
If the previous request is NOT the request that built the table/page, I'm stuck again

Is the solution always passing the previous request URL and Params with every AJAX request I make? I feel like someone has solved this somewhere or somehow but I am just lost in this area in Drupal 8, and have been beating my head constantly trying to figure out how to refresh parts of a page in an AJAX request.

EDIT: I am not certain the best place to put the "completed" code, but thanks to 4k4 I've put the following together:

  // create url object from route to render link
  $my_url = Url::fromRoute('my_module.my_route', array('param' => $value));
  // get the current query parameters for our page
  $query_options = \Drupal::request()->query->all();
  // add them to our Url
  $my_url->setOption('query', $query_options);

No, HTTP_REFERER is not reliable and yes, the solution is to add the query parameters of the current request to each AJAX link. Form API does the same for form elements:

RenderElement::preRenderAjaxForm:

    // Add all the current query parameters in order to ensure that we build
    // the same form on the AJAX POST requests. For example,
    // \Drupal\user\AccountForm takes query parameters into account in order
    // to hide the password field dynamically.
    $settings['options']['query'] += \Drupal::request()->query->all();


How do I uninstall RSS? I would like to uninstall RSS completely from Drupal 8, not only hide it from pages, but also disable the core logic behind it.

How do I achieve it?

I am not sure where you encounter RSS, but I am only aware of it being on the front page. That feed is generated from a second display on the frontpage view:

Other modules might define their own feeds in a similar fashion, but I have not found them yet.

There is no such thing as 'disable RSS', so you cannot disable it globally.


How can I let users create their own playlists of a particular content type? How can I let users create their own playlists of a particular content type?

I have used the Flag module but it allows only a single list. I want the user to be able to create multiple lists.

I have tried the Flag Lists module but cannot seem to get it working.

Any help would be appreciated.

Flag module

Use the Flag module to create 1 flag for each of the lists you want to use it for (do NOT make it a 'global' flag though). The flags are to be created by an admin, but each user (authorized to use a flag) will then be able to build their own "lists" using such flag.

Then create a view (with the views module) for each such playlist you want, whereas you create a "views relationship" with one of those flags.

This approach requires the types of flags to be pre-defined (via admin), such as playlist-flags named like Bookmarked, Revisit Later, Add to my queue, Played, etc. Though it is ony like a 5 min admin update to add any other relevant flag later on (eg if a user requests another variation).

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the flag module.

You might also want to look at some of the Flag related modules, such as (partial list):

Views, to create lists of flagged content, users, etc, such as in the video about Creating global flags and listing flagged content in Views.
Rules, to trigger rules for anything that is flagged, such as in the video about Triggering rules with Flag, or to set flags with the Rules module, such as in the video about Setting flags with Rules.
Flag Lists, to allow users to create custom lists.
Flag Weights, to add weights to Flags (to be used for sorting).
DraggableViews, to make Views draggable (so that they can be rearranged by Drag'n'Drop.).
Flag Friend, a pre-built flag for marking other users as friends (using the Flag module).
Flag Abuse, a pre-built flag for marking offensive content, with some extra administrative features.
Flag, Hide & Mute, for users to hide individual nodes, such as site-wide announcements or advertisements, and/or to suppress all posts by users they do not want to see.
Flag Files, to flag media files.
Flag Service, to allow Flag to be accessed via a web services interface through the Services module.
DLike, provides a Facebook like "Like" functionality using the Flag and Lightbox2 module.
Conditional Flags, provides an extra API to Flag module, for custom conditions between flags.
Organic Groups Flag Integration, extends the flag module with organic groups support allowing the administrators of each group to override the global flag settings for their group.
Context Flag, allows the use of Flags as conditional triggers for use with the Context module.

Refer to its community documentation for way more details.

Entity Reference module

Create a content type like "Playlist" for which each user should be able to create/edit "their" nodes for (with 1 node for each Playlist they want). And add a field in it using the Entity reference module for it (with multiple values allowed). Combine this with the Node Access module to ensure that each user can only "edit" their own Playlist nodes.

Other usecases

Refer to my answer to How to motivate visitors to comment (technically)? for other usages of the Flag module as illustrations of other great things you can do with the Flag module, and some other great modules that play well with it (i.e. the Rules module).


Get term from tid in views I have a view which overrides the default taxonomy page. The view has a contextual filter which look for the tid in the URL.

My goal is to get the taxonomy term to display as the title of the page.

I tried setting the view's title to "Department: [field_dept]" (the field which references the taxonomy term and is loaded in the view). This work great, [field_dept] is replaced with the taxonomy term as expected.

There is an exception though. When the view has no results, there is no [field_dept] to look up and my page title looks like this "Department: [field_dept]" :-/

Now I'm trying to figure out how to get the taxonomy term from the tid, which is in the URL and available in my view.

Is there a function available in views that will return the term from a tid? Something like get_term_from_tid(%1), so I can use it in the title of the view or via title override in the contextual filter?

Drupal 7.14

Views 7.x-3.3

Do you use "Content: Has taxonomy term ID" field as contextual filter?

If yes then edit this filter, in "WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED" section check "Override title" and in appeared textfeild input "Department: %1"

"%1" will be replaced by the name of current term. If no term is specified "%1" will be replaced by "all".

If you want change word "all" then in section "WHEN THE FILTER VALUE IS NOT IN THE URL" click on "Exceptions", check "Override title" and specify your value.


How can I check for a duplicate node when rendering a view? This question is closely related to my other question posed a few hours ago:
How to make a node appear across *all* Taxonomy terms?

As a solution, I plan to create a functionality, where my new nodes are added to every country in my 'countries' vocabulary, when a 'check all' button is clicked (this is in addition to a single term in the 'main' classification taxonomy they are assigned to).

But I have a view for the display of these nodes. It accepts a term ID from the main taxonomy via URL, and provides a Hierarchical Select "exposed filter" for further filtering by geography within the displayed nodes.

I will now have the same node teaser multiplied by the number of countries in my vocabulary, when the user first enters this view (because that many nodes were created).

Is there a way I can tell my view to just notice such nodes only once, in the unfiltered state?

If I'm not mistaken, in your view-settings, you can select a distinct query in your Advanced settings in the view. It set under Query settings. I'm not sure if it's already there in D6.


Mail subject and body remain empty using mailManager I have been fiddling with sending a mail in my custom module in Drupal 8.
The mail gets sent but the subject and body are empty.
It has been an issue for days and I can't get it to work. The code and var_dump are below. I just can't find the issue. Maybe someone can!

Code in hook_mail:

<?php
/**
 * Implements hook_mail().
 */
function document_mail($key, $message, $params)
{
    $options = array(
        'langcode' => $message['langcode'],
    );
    switch ($key) {
       case 'send_file':
            $message['from'] = \Drupal::config('system.site')->get('mail');
            $message['subject'] = t('@title', array('@title' => $params['mail_title']), $options);
            $message['body'][] = $params['message'];
        break;
    }
}

Code to send mail:

    $mailManager = \Drupal::service('plugin.manager.mail');
    $module = 'document';
    $key = 'send_file';
    $to = 'info@example.com';
    $params['mail_title'] = 'a title';
    $params['message'] = 'a message';
    $langcode = \Drupal::currentUser()->getPreferredLangcode();
    $send = true;
    $result = $mailManager->mail($module, $key, $to, $langcode, $params, null, $send);
    var_dump($result);
    if ($result['result'] !== true) {
        drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
    } else {
        drupal_set_message(t('Your message has been sent.'));
    }

var_dump of result from $result of mailManager

array(12) {
["id"]=> string(18) "document_send_file"
["module"]=> string(8) "document"
["key"]=> string(9) "send_file"
["to"]=> string(24) "info@example.com,"
["from"]=> string(22) "info@example.com"
["reply-to"]=> NULL
["langcode"]=> string(2) "en"
["params"]=> array(2)
{
    ["mail_title"]=> string(7) "a title"
    ["message"]=> string(9) "a message"
}
["send"]=> bool(true)
["subject"]=> object(Drupal\Core\StringTranslation\TranslatableMarkup)#410 (5)
{
    ["string":protected]=> string(6) "@title"
        ["translatedMarkup":protected]=> NULL
        ["options":protected]=> array(1)
        {
                ["langcode"]=> string(2) "en"
        }
        ["stringTranslation":protected]=> NULL
        ["arguments":protected]=> array(1)
        {
            ["@title"]=> string(7) "a title"
        }
    }
    ["body"]=> array(1)
    {
        [0]=> string(9) "a message"
    }
    ["headers"]=> array(7)
    {
        ["MIME-Version"]=> string(3) "1.0"
        ["Content-Type"]=> string(51) "text/plain; charset=UTF-8; format=flowed; delsp=yes"
        ["Content-Transfer-Encoding"]=> string(4) "8Bit"
        ["X-Mailer"]=> string(6) "Drupal"
        ["Return-Path"]=> string(22) "info@example.com"
        ["Sender"]=> string(22) "info@example.com"
        ["From"]=> string(44) "a string"
    }
    ["result"]=> bool(true)
}

Remove the empty array tag from body as below.

$message['body'] = $params['message'];


Unable to add field to existing view I had previously created a view which is a list of nodes of type 'Banner'. I have added an extra field to the content type, and I have attempted to add this to the view, which seems as if it works ie. adds to the fields list, and reflects the changes in the live preview.

But then the live page doesn't reflect the changes, ie. the new text fields dont show up and the fields aren't populated in the $row or $fields variables in the views-view-fields.... theme files when debugging.

Also, when I go back to edit the view the new added fields are not there, so it seems as though they haven't been inserted into the database.

Does anyone have any idea why this would be?

A couple of things to check:

Confirm you added the field to the right content type and save the changes
Make sure you added the field to right view "display" and save the changes
Clear the cache of the whole site
Make sure if you are using field permissions that they are properly set
If you are using a template file for the view make sure to add the new field.


Drupal 7 globalredirect not working for /node/ redirection I want to redirect my site from URLs like

/node/530

to

/Services/TrainTickets.html

I installed GlobalRedirect module as I've read it would address this problem, but the same page is still accessible at /node/530 path.

Anybody knows what the problem could be and how I could resolve it?

I also want to make it impossible to access the site via

http://www.waytorussia.net/node?page=31 and so on...

Thanks!

UPDATE I use Drupal for Facebook module and I've seen there were issues with that as it uses custom url rewrite but did not find any resolution.

For your first problem why are you not simply using Clean URLs, which is built into Drupal? I'm assuming you're using version 7.x.

I'm not absolutely certain about adding the .html added to your url aliases and whether that will break something, but I'd imagine you could easily fix that by using some mod_rewrite and just appending .html to all your clean URLs.

What I mean then is in your Drupal system your URL aliases will be /Services/TrainTickets. Essentially you'll still be using default/core clean URLs for all your paths. In .htaccess file though you can use mod_rewrite to append .html to all your paths.

For your last problem re: blocking access to all /node/x paths, the first thing I thought of was again to use mod_rewrite to redirect to a custom built 404 Page Not Found page, instead of having to use a Drupal module. However, I've never tried this and am not certain this approach would work. I took a quick look though and it appears someone else thought of this too:

https://www.drupal.org/node/164526#comment-7919767

One issue I see right away is that you'd want to ensure that the path is a node view page (i.e. node/x) and nothing more (e.g node/x/edit - which would mean you're logged in), otherwise you'll run into some issues when logged in and trying to edit content.

Maybe try it out? Worth a shot.


Results of a Views display as an array (D7) With Views in D6, I was able to get the results of a Views display as an array and work with it using php code embedded in a node.

For example, using this code snippet:

$view = views_get_view('view_name', 1);
$view->set_display('block_1');
$view->preview();
$MyArray = $view->result;

This allowed me to get the results of the 'block_1' view display into the $MyArray array.

However, I'm trying to do the same thing in D7 and all I'm getting is a list of all the nodes in the view I'm calling, and not the results of the view display.

How do I get the results of a view display in code for D7??

I think it has been replaced by the views_get_view_result() function. It returns:

  An array containing an object for each view item.

e.g.

$result = views_get_view_result('view_name', 'block_1');


What hook can I use for post-save actions? I've found several posts with this same question, but the answers always diverge to some other topic or they don't work for my needs.

After a node is saved, I want my custom module to insert a row into one of my custom tables which contains the nid of the new node. When hook_node_submit is called, the nid doesn't exist yet. hook_node_insert does have the nid, but only gets called the first time the node is saved, but I potentially need to take action each time the node is saved.

My plan is to separate my functionality into its own method and implement both hooks, but I'm trying to learn to do things properly with Drupal and so I'm wondering if there is a hook that actually fits with my requirements.

Is there a hook which is called every time a node is saved and called AFTER the save is complete?

The correct way of doing this is to respect Drupal's db transaction.
If you want to do any database action in hook_node_insert you must consider that the node is not actually saved yet. which means if it fails and rolled back you end up with orphaned data in your database. So Drupal database API should be used and not direct query execution.

If you want to update the node itself in hook_node_insert, you can't because it's not possible to use node_save since the node is not yet saved in the database and calling it causes exception. One solution is to use register_shutdown_function function and passing nid, you can use node_load to make sure that it's really saved and then do any other action you may want on the new node.

function your_module_node_update($node){
  if($node->type == 'your_node'){
    register_shutdown_function('_your_module_post_insert',$node->nid);
  }
}

function _your_module_post_insert($nid) {
  $node = node_load($nid);
  if ($node) {
      node_save($node);
  }
}

UPDATE: You can also find an easier alternative here https://stackoverflow.com/a/24035797/1726778


Using innerJoin() in TableSort In the examples modules I see a simple example of tableSort with one table.
Searching online I find a post where they claim Drupal 7 allowed a db_select() object to be created and then extended it with a join(), and then the final ->extend('TableSort');

https://www.drupal.org/forum/support/module-development-and-code-questions/2011-12-15/dbtng-tablesort-with-joins-any

I need to do an innerJoin() which appears to be a method of the SelectQuery class, and not necessarily a method of the Tablesort class. That's why the docs I see about extenders say it's critical to invoke the TableSort in the instantiation of the db_select object. Thus, my attempt:

$get_all_members = db_select('users', 'u')->innerJoin('members', 'm', 'u.uid = m.uid')->extend('TableSort');

  Call to a member function extend() on string

is the response. Is there a way to convert a db_query into a TableSort object like it appears the extender is doing?

Or, could I find a way to combine the fields I need in these two tables to pass to the TableSort object?

The issue is addressed in the thread you referenced. Not all methods for the select class return the new query object. In particular, innerJoin() returns an alias string, not the query object.

Assign your query object so you can reference it outside of the method being called:

$query = db_select('users', 'u')->extend('TableSort')
$query->innerJoin('members', 'm', 'u.uid = m.uid');
//@TODO: add ->fields() ->execute() etc...


Making it so registered users can't add/edit taxonomy terms to nodes Is there a way to add a permission so only admins can add/edit taxonomy terms on nodes? I tried http://drupal.org/project/taxonomy_access but I don't really want full module and while rebuilding my content permissions I got an error so that module might not even work.

Found a module that does this: Taxonomy Role


How do I use an image CAPTCHA? I am trying to show a CAPTCHA image in the form of my custom form, but it doesn't appear.

Why doesn't this code show the CAPTCHA as expected?

/**
 * Created by PhpStorm.
 * User: sony
 * Date: 28/02/2016
 * Time: 23:23
 */

/**
 * @file
 * Contains \Drupal\contact_form\Form\ContributeForm.
 */

namespace Drupal\contact_form\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\UrlHelper;

/**
 * Contribute form.
 */
class ContributeForm extends FormBase {
    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'contact_form_contribute_form';
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {
        $form['Full Name'] = array(
            '#type' => 'textfield',
            '#title' => t('Full Name'),
            '#required' => TRUE,
        );
        $form['E-mail'] = array(
            '#type' => 'email',
            '#title' => t('E-mail'),
        );

        $form['Type of feedback'] = array(
            '#type' => 'radios',
            '#title' => t('Feedback'),
            '#description' => t('Type of feedback'),
            '#options' => array(
                t('Comments or suggestions'),
                t('Questions'),
                t('Report a problem(s)'),
                t('Other'),
            )
        );
        $form['Subject'] = array(
            '#type' => 'textfield',
            '#title' => t('Subject'),
        );
        $form['Your Message'] = array(
            '#type' => 'textarea',
            '#title' => t('Your Message'),
        );
        $form['my_captcha_element'] = array(
            '#type' => 'captcha',
            '#captcha_type' => 'Image',
        );

        $form['sendt'] = array(
            '#type' => 'submit',
            '#value' => t('Send'),
        );
        return $form;

    }

    /**
     * {@inheritdoc}
     */
    public function validateForm(array &$form, FormStateInterface $form_state) {
        if (!UrlHelper::isValid($form_state->getValue('video'), TRUE)) {
            $form_state->setErrorByName('video', $this->t("The video url '%url' is invalid.", array('%url' => $form_state->getValue('video'))));
        }
    }

    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        foreach ($form_state->getValues() as $key => $value) {
            drupal_set_message($key . ': ' . $value);
        }
    }

Captcha is not a valid form element in Drupal 8. Since you haven't listed if you are using any other contributed modules, I am not sure what or where #type => captcha comes from.

I advise using Mollom to do captcha handling for forms.

https://www.drupal.org/project/mollom


Drupal 7 + Services : Error 500 on user registration (Integrity constraint violation: 1048 Column 'uid' cannot be null) I'm still working on user registration with Drupal 7 and Services 3 and I got a weird Error 500 :

  Integrity constraint violation: 1048 Column 'uid' cannot be null

Here is the code I'm using :

// REST Server URL for auth
$request_url = SERVER_URL . 'rest/user/register';

// User data
$user_data = array(
  'name' => 'newuser',
  'mail' => 'newmail@mail.com',
  'pass' => 'newpass',
  'field_city' => array('und' => array('0' => array('value' => 'NA'))),
);

$user_data = json_encode($user_data);
// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $user_data);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_VERBOSE, true);

$response = curl_exec($curl);

$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  if ($http_code == 200) {
  return json_decode($response);
}
else {
  $http_message = curl_error($curl);
  return $http_message;
}

Is there something I'm doing wrong ?

I think that on the other side of your code you are trying to save the user. So, to create a new user using user_save() function you have to left the first parameter blank so a new user is created. Also, add the parameter true to your json_decode($response, true) to obtain an array rather than an object.

$account = user_save('', $fields);


Change Administrative theme I have changed my Administrative Theme to a theme I don't like and now I cannot change it back. There is a drop down to change, but no save configuration option anymore.

You can change it back with drush:

drush vset admin_theme seven

Or PHP:

variable_set('admin_theme', 'seven');

Or if you're in a real bind, via the settings.php file temporarily:

$conf['admin_theme'] = 'seven';

Replace "seven" with the machine name of the theme you want to use for the admin pages.


Adding a Image Upload Button in CKEditor I have installed CKEditor in Wysiwyg profiles. While publishing any node if i click on the image upload button it shows options to add images by a image link, but what is the way to add a dynamic image upload button so that users will be able to Browse and choose any image from their computer in content?

Check out IMCE with IMCE WYSIWYG bridge.

Once you install and configure those two modules, select "IMCE" as a button in CKEditor and then you can upload and insert images in WYSIWYG.


Entity Metadata Wrapper - check filtered text value is set I'm seemingly unable to check for the existence of a value of a field if the field in question is set to filtered text. The following code returns an error - and any possible combination I've tried to find online results in the same:

if ($wrapper->__isset('body')) {
  print $wrapper->body->value->value();
}

The error:

EntityMetadataWrapperException: Unable to get the data property value as the parent data structure is not set. in EntityStructureWrapper->getPropertyValue() (line 438 of /Applications/MAMP/htdocs/arch-main/httpdocs/sites/all/modules/contrib/entity/includes/entity.wrapper.inc).

To be clear, the node does have the body field, but no content has been placed in it.

Any ideas on how to check for this?

EDIT:

Ok this seems to work, but there must be a better way

try {
          print $wrap->body->value->value();
        } catch (EntityMetadataWrapperException $e) {
          // ???
        }

but there must be a better way

If you find it, do share :)

Seriously though, this is what the language gives you; exception handling is what you should use to handle exceptional circumstances, and an entity not having a field that you're expecting it to have would probably class as exceptional in most people's book. It does in mine anyway.


How to prevent Cross Site Scripting when input using "Full HTML" mode of CKEditor I am using Drupal version 8.3.7 and ckeditor 4.11.3.
I create a basic page contains some scripts as following:

In the detail page, I can see that the script in onmouseover="alert('222222')" is executed when I move my mouse over the "click" text.

Hacker can easily add a malicious script by this way. How can we avoid this ?

Issue is not only for "Full HTML" mode, but also other modes if we configure a proxy between browser and server to change the encoded value to the raw value.

For example, if we select the "Unfiltered HTML" mode and we input click to the body field. When we save the page, the body value will be sent with a POST request that it is HTML encoded: &lt;a href=&quot;#&quot; onmouseover=&quot;alert(&#39;111111&#39;)&quot;&gt;click&lt;/a&gt;. But in the proxy above, we configure to change the encoded value to the raw value. Then the raw value click is saved into DB which will cause the same issue with "Full HTML" mode.

A solution that we can encode the output in theme preprocessing hook. But it seems require us to add a lot of codes because our system may have many entity types and fields.

See the documentation:

  Finally, it should be obvious that the Full HTML input format, which
  does not use the HTML Filter, is insecure and should be offered only
  to those users who can be trusted not to ruin your site. Most sites
  will be better off deleting this input format.

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

"A solution that we can encode the output in theme preprocessing hook. But it seems require us to add a lot of codes because our system may have many entity types and fields."

Don't do this in preprocessing. You can configure your own safe text format containing as many text filters as you want. If the built in text filters don't provide the security you need then add a custom filter.

Core ships with Full HTML so that site owners are able to create basic pages in CKEditor using almost all HTML features, which they can do anyway when they have access to the template files.


How to have a Conditional Field in node form? My goal is to hide the field until certain value in another field is selected in the node edit form. Is there a way for achieve that?

You have the Conditional Fields module that works very well in Drupal 7, unfortunately there is not a Drupal 8 version, you can check this issue to find out its progress. If you want you can test the dev version, but I don't know if it works.

Other module in dev is the Field States UI

  Field States UI allows sites builders with minimal PHP/Dev skills to
  configure the Field States API. This lets you configure a field to for
  example hide if another field has a certain value or hasn't been
  filled. While doing it via PHP can be be more powerful the UI can be
  very handy and in some cases quicker.

In the other hand you can make use of the #states property.

EDIT:
As the OP says in the comments there is another module named Field Formatter Condition that can be used for accomplish this task.


How to fetch the content author name with views in twig? I am unable to fetch the content author name inside the twig template thorough views.

Below is what i did so far :
- Created a relationship under the advanced tab in views and added the Authored by field.

I can see the author in the preview section of the view but since i have overridden the template with views-view-filed i cant fetch it in twig with {{ fields.author.user.name}}

Kint is not of much help as its freezing the browser.

Better way to answer this is through  debugging the views fields by enabling the page_array check under the devel module settings.We get each and every fields that are available for the twig template.

There are two steps to get this working

Follow the steps mentioned in the comment:

https://www.drupal.org/forum/support/post-installation/2011-06-26/drupal-72-views-adding-authors-name-of-a-node#comment-4919120
You have to be careful while selecting the field .Please select the
field marked in the attached image.

Then in the twig template views-view-fields--VIEWNAME.html.twig the
variable to be used is {{fields.nane.content}}

In addition to the above while researching for the variable name i found that most of the field names commonly used are available under admin/reports/fields in the backend of Drupal 8


users list as a node view I want to create a content type in which one of the field is a list of all users in drupal.I know I can add a node reference field but that reference is showing only normal node view but not user view.Is there a way to add list of all users in a content type?

You can create a Users view, using a module called Views. It's not exactly "content" (node) but Views can create Page displays which can be placed on the menu.


How to add / remove tabs from user profile? By clicking on the "My account" link that on the secondary menu on the site, the user is redirecting to the user's profile page.

In this page there are many tabs. Some tabs are there originally, and some tabs created by some modules. I understood how to add tabs to this menu (by simply create view and give it path of /user/%user/XXX).

Is there another way?
How can I remove tabs from the user's profile menu?

Why this user profile menu is not under the menus section of Drupal?

My goal is to remove the following tabs (see screenshot below): "HybridAuth", "Your Questions" and the "Points" tab.

If you don't want to use a contrib module like TabTamer then, In Drupal 7,   you can use hook_menu_alter to disable the MENU TAB by using access callback

    /**
     * Implementing hook_menu_alter
     * Restrict MENU TABS access
     */
    function MODULE_NAME_menu_alter(&$items) {
        if(/* check your conditions */) {
            $items['user/%user/hybridauth']['access callback'] = FALSE;//Change the MENU PATH as per your requirement.
        }
    }

Note

Get the MENU PATH by printing $items variable.


Display Taxonomy Terms Based on user login in a select list in a view I have created a view with taxonomy term as filter criteria.

I want to display values of taxonomy terms based on the user logged in(i.e. I want to display only the terms which are created by that user alone) in that select list.

Any help will be really appreciated.

There is no way you can get the author uid of taxonomy term. But here is a solution you can try:

Add a user reference field to the vocabulary, the field will contain author uid.
Add term exposed filter to the view.
Using hook_form_alter() alter the exposed filter so that it shows only those taxonomy terms which are created by the currently logged in user.


Why does all links of homepage redirects me to Xampp homepage ( Took backup from Godaddy ) I took backup of SQL from Godaddy and copied all the data from my Godaddy hosting account through FTP.
I imported the SQL in my machine's mysql ( no issues ).
I copied the files to my htdocs/subdir1/drupalDIR/ and made changes in settings.php ( updated mysql connection details ).
Homepage is showed in a perfectly fine way but whenever I click on any link, it takes me to Xampp Homepage.

Perhaps it's a htaccess issue.

What should be the Rewrite rule to make it okay ?

I tried copying the .htaccess file available inside the Drupal package and pasted into my htdocs drupal folder.
Works like charm till yet.


TinyMCE for comment textarea I'm Drupal beginner and I can't figure out one small thing.

How can I use TinyMCE for comments ?

Please, see image below:

I have already defined some custom formats and WYSIWYG profiles, but can't figure out how to "attach" them;

Thanks.

First go to /admin/structure/types and edit your content type.
Click on the "Comment Fields" tab at the top of the page and then edit the comment field.
Here you can choose the text format that your comment field will use.

Now go to /admin/config/content/wysiwyg and choose the text editing you want to use for your text format. You can also edit any configuration setting your editor of choice here.


Drupal Google Maps clustering of nodes. I am trying to find a way I can cluster nodes on a Google Map from a custom entity according to particular regions in a country. I have been using the Geocoder module to geocode addresses but I now want to group these addresses into regional clusters. I need a way I can implement Google Map clustering in Drupal 8.

If there is a way to do it programtically please do not hesitate to illustrate.

In order to cluster your map pins/node results, you'll need to write your own javascript function to call the Google Maps Clustering Library/initialize the map (since as of Feb 23, 2018, the GMap module has yet to be fully ported/available for D8).

Based on Google's Marker Clustering Documentation/Example, I'd recommend creating a custom module that includes:

The Google Maps Marker Clusterer js library.
Setting up a json endpoint/route for the location nodes/entities
Custom module javascript that loads the nodes from the endpoint above and parses them (their latitude & longitude data) for the locations array in the init_map function.

Worth noting:
The Google Maps clustering library is grid-based, dividing the map into squares of a certain size.

If you want regions bounded by state/provincial borders, this library won't satisfy the zoomed out map with multiple regions; you'll need something more custom. In such a case, you can:

add a taxonomy for the regions (with a custom set of geocoordinates for the center or political capital of each region)
load a custom high level map with the regions defined/outlined with svg polygon paths and displaying custom cluster pins
on each specific regional map utilize the grid-based clustering library


Radioactivity module. "how-to" most popular article in one day questions thanks for the time to read this question.

to me not is clear the concept of Radiactivity measures. how to get the most popular article in one day? I must use the half-life in 43200 seconds (12 hours)? when change this results? (each day in this case?), what's happen if I Cut-off energy to 0?. where is stored this results if I want a report per days?

thanks in advance.

According comparison of the Radioactivity results and a Analytics service, seems that 12 hours (in seconds) is the time needed to track 1 day.


How to know the format when programmatically setting a field value I am trying to create a set of entities based on a CSV file on install of a custom module. The entity has a price field and I don't know how to find out what I should be passing in as a value, the following does not work:

$entity = entity_create('item_price', ['type' => 'wand']);
$entity->setName('Harry Potter');
$entity->set('price', 2000);
$entity->save();

Although this problem is specific to the price field I would like to know as a general rule how does one "discover" what format the value should be in for any field type.

You will need to pass price object to it and not just a number. Do like this -

$price = new Price('2000', 'USD');
$entity->set('price', $price);
$entity->save();

You can always look at tests to know how things are working for the module. :)


Database Synchronisation Manually I have a situation where I need to check the changes (what tables) were done at database level after a particular date as the two databases have to be merged now.
Is there any tool or module in Drupal that can fulfill this requirement.

Scenario: My client has given me the database (code also) of his current site to work on. He also did some changes meanwhile (at database level only maybe content) on his live site.

Now I need to integrate these changes into my database, but he did not record the changes that were done. What would be the best solution?

What I have done: I wrote a query fetching records from node table showing all the changes done after the particular date and manually updated his changes into mine. Am I missing something else?

There are a couple of ways I could think I would approach this issue:

If the changes made by me in the old database are reproducible easily to the new database, I'd go for it first. And in most of the cases if you follow Drupal best practices like using update hooks, alter functions, etc. they could be easily done to the new database by (sometimes) running only update.php
So, I'd recommend to move all the custom changes to the update hooks if you have time. Because, considering that the site is live, you could expect more changes to the database. And your code should be flexible enough; unless off course if you could convince the client to stop updating the live site.
If you are sure no database level changes would be done (which I doubt, Drupal being a database driven framework), you could use some tools for comparing the changes between the two databases. Check this stackoverflow question for list of tools that could be used. Take a diff of the database, find out the tables which have differences. From the tables, find out which entities are added/removed from the database. And then make the changes to as required.
I would not recommend this method over the first.


How do I edit the links in a filter I don't know if this is the right forum, but I'm updating our corporate website, and picking up where the previous person in my job left off. From the main horizontal menu on the front page (newsletters, programs and services, departments, doing business, etc), I am clicking on "Programs and Services" which takes me to the page screencapped below. The individual items shown on this page "Counselling, Youth Program, etc" are linking to pages that I want to get rid of and replace with pages I have built elsewhere on the site. I can't seem to figure out where to go to edit these. Ideally I'd like to get rid of the drop-down filter menu entirely and just have links to the pages I have alreayd built for the topics elsewhere within the site.  Any help?

This is an educated guess:

The page "Programs & Services" on the programs-services link is built by Views module.

You can edit the Views by clicking on the small gear icon you see in the top right corner of the content area and choosing "Edit Views". Or find that particular View under Structure > Views and edit from there.

Under Filters on the left you'll probably have several filters listed, with one of them labeled (exposed). You can click on it and Remove - that is how you get rid of the "drop-down" filter currently present above the results.

To change which page titles appear in the results you again have to change something under Filters, but it's impossible to tell what because that depends on your site configuration.

Sometimes (besides the Published filter) there is the filter based on Content type, for example, to list only Articles that are on the site, or only Basic pages.

Sometimes there is a filter that filters by Taxonomy (tags) that the content is labeled with (for example list only content tagged with "Medical").

You need to find out what the current filter configuration is (post a screenshot), and how your new pages you want to list there differ from other content (are they of a different Content type, have they been posted after some date, by a different author, tagged with some tag).

Then you'll be able to change the filters accordingly to show the new content instead of the current list.


How to show pricing attributes in View I'm using Pricing Attributes module, but i don't know how to show its in line item view, in shopping cart view and in shopping cart form view.

How do it?

Thanks

You need to edit the following view: Shopping cart form (Commerce Order).
And add a the field: Commerce Line Item: Product Attributes, this will show the product with the extra attributes.


Missing bundle property on entity of type taxonomy_term I am using the Feeds Import module as described in Drupal as an interface for users to Add/Edit/Search a database.

When we import, we get the following error:

  Missing bundle property on entity of type taxonomy_term

Why does that error message appear?

This error is caused when there is no Vocabulary selected in the Term reference fields of the content type into which feed import is performed.

Go to the Manage fields of your content type into which you are importing. Check all the Term reference fields and reconfirm that in the Field Settings, correct Vocabulary is selected.


Views random 1 image after refresh I'm trying to use Views to randomly display an image(or node) from a content type. So everytime(or every 10secs) a user refresh their browser a new random image should display.

Here is my setting in Views. I added "Global: Random(asc)" in Sort Criteria, 1 item on Pager, and "Never Cache" Query results "10"seconds Rendered output on Caching setting.

However, the page does not render a new image after 10sec browser refresh for Anonymous user, but any login user.

====== Update June 22, 2015 at 12:26pm ======
optional solution:
* exclude cache on specific page by using CacheExclude module
* still looking for solution to exclude cache on specific views(and view block) for anonymous users. Update: Found a solution for Views by using Views Random. This module allow user to enables cached views results randomly.

Pages are cached for anonymous users. Views obtains random image every time it has it's chance to work, but for anonymous your cache time is probably significantly longer.

All you have to do is to disable cache on the page you have this view on. How depends on the cache system you are using.


How to migrate a real real messy Drupal setup to a fresh, new, well structured and totally new stable environment The situation is as follows: there is a Drupal website which has loads of content (it is for a popular Iraqi newspaper), but the way the website has been built is very, very very messy. Content types are awkwardly structured, views are a total chaos, css is a big pile of non-structured, non modular and totally not maintainable setup of statements, there's no consistency whatsoever. Moreover, many things are in such a way implemented that upgrading to a newer version (Drupal 7 for instance, it is still running on 6) is gonna be a real pain in the ass. This site is doomed to be redesigned from bottom up, otherwise every change will make it more inconsistent and more difficult to maintain.

I'd really like to migrate it to OpenPublish. It's been proven to be a good environment for news-outlets, with well established worflows.

But where to start? How do I map these messy, and awkwardly structured content types to the more properly structured ones that OpenPublish uses? And then: how do I migrate the data, without losing any information? Basically they are the same types of content from an abstract perspective: news-articles, blog posts and pages, but internally there's loads of differences and difficult hurdles to overcome.

Are there any modules that are able to map different types of content types and tell which fields correspond to each other? Are there others that enable you to migrate the data without losing information and structure?

edit: added examples below

Two particular problems for instance:

In the messy version, each article has an author. An author is always a regular user account. So the amount of user accounts has exploded with registrations that are actually not used. OpenPublish links user profiles (which are nodes basically) to articles. Problem: howto resolve this inconsistency when migrating data?
Similar problem: in the messy version, each article has a slideshow field (which can contain multiple images) as part of the node article. In OpenPublish you create a reference to a separate gallery node, which also has more meta-information attached to it. How to split those up, without losing their relationship?

Any tips? Best practices? Thoughts?

I think the Migrate module will help you a lot


Is it normal that a site changes to maintenance mode during a module update? I have created a custom module with a .install file, which includes some hook_update_N() hooks, used to update existing nodes.
Whenever I run drush updb, the site automatically enters maintenance mode (anonymous requests get a 503), and if the update is successful, the site goes back online, all by itself.
I couldn't find any resource on the web about this situation.
Is it normal? Is there a way to disable this behavior?

It does look to be normal, yes. Drush's UpdateDBCommands::updateBatch, which is responsible for processing the updates, contains this:

batch_set($batch);

// See updateFinished() for the restore of maint mode.
$this->maintenanceModeOriginalState = \Drupal::service('state')->get('system.maintenance_mode');
\Drupal::service('state')->set('system.maintenance_mode', true);
drush_backend_batch_process();

The code deliberately sets maintenance mode to true before processing the batch, and then restores the original state when it's done.

Running drush help updb lists the following options:

--cache-clear[=CACHE-CLEAR] Clear caches upon completion. [default: "true"]
--entity-updates Run automatic entity schema updates at the end of any update hooks.
--post-updates[=POST-UPDATES] Run post updates after hook_update_n and entity updates. [default: "true"]
--no-cache-clear Negate --cache-clear option.
--no-post-updates Negate --post-updates option.

So there doesn't seem to be an obvious way to disable the behaviour. But if you're updating the database you probably don't want people to be able to access the site at the same time. There's a good explanation for that here.


Global Combine fields filter (Views) does not include Referenced Entities (Content Type) I have an Content type which contains another Content type, I managed to put in place the relationships using Entity Reference I also configured Views module to display the contained content type, the problem is when creating a Global Combine fields filter I can't search with the contained Content type, it always returns an empty result.
Is something wrong with my approach ?

This is not possible with Global Combine fields filter at the moment, see also the feature request for the Entity reference module.

This is possible though with the Views filters populate module. You can use any field of a referenced entity or field collection of which you setup the relation with in your view.

Howto :

Like the instructions on the module's page describe, first step is to
add the fields you want to search on in an OR combination of filters.
With Drupal6 that would have been by using the 'Views Or' module; with
Drupal7 this is just a filter group with internal operator set to
'Or'. These individual filters should  not be exposed.
Then these filters can be exposed as one input by adding the module's provided filter called 'Populate filters', found on the 'Global' section. Expose it and check the filters you added in the Or group.


Auto-increment field based on value of another field How can I have a computed field (field B) that has an auto-incremental number but  based on the value of another field (field A).

For example: I create a node with value "Location X" in field A. Field B should get value X001, I create a second node with value "Location Y" in field A. Field B should get value Y001. I create a third node with, again,  value "Location X" in field A. Field B should get value X002. And so forth

Checkout hook_node_presave() here you can set the values dynamically.
And variable_get() and variable_set() for the increment.

With str_pad() you can add the starting zeros to the increment.

hook_node_presave($node) {
  if ($node->field_A[LANGUAGE_NONE][0]['value'] == 'Location X') {
    $increment = varibable_get('LocationX_increment', 0);
    $increment++;
    $node->field_B[LANGUAGE_NONE][0]['value'] = 'X' . str_pad($increment, 3, '0', STR_PAD_LEFT);
    variable_set('LocationX_increment', $increment);
  }
}

You don't need to save the node in this hook, just change the value of the field.


htmlspecialchars in search When I'm searching my site, I get this error:

  Warning: htmlspecialchars(): Invalid multibyte sequence in argument in check_plain() (line 1476 of /var/www/includes/bootstrap.inc).

What does it mean and how can I correct it?

EDIT:
The problem disappeared after migrating to webhosting server, so the problem should be something in settings in my local computer.

Try adding some instrumentation by replacing the check_plain function with this version:

function check_plain($text) {
  $plain = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
  if (empty($plain) && !empty($text)) {
    dpm($text);
    ddebug_backtrace();
  }
}

You will need to have the devel module enabled.  The next time the error is triggered, the offending text will be displayed along with a backtrace that shows what function triggered the error.  With that info, you can search your code and database for the offending text and remove it.