Multi Axes Voting using Fiverstar, Views, Reference I have tried several different tutorials on how to accomplish this. Most were for drupal 6, but there were few for drupal 7 but none seem to make sense to the modules being used currently that are in dev or stable. The Node Review module seems to be the closest thing to what I need but that requires some hacking to make it work for my particular use. I have several other modules that I've experimented with. Rate 7.x-1.3 Seemed to have potential.

How would I be able to make a system like the following use these modules?;

Node Reference   7.x-2.0+8-dev
Fivestar 7.x-2.0-alpha1+22-dev
Views    7.x-3.3

What I am looking for a content-type: Business. These will have several businesses that people can rate based on different criteria. Multi Axes Rating on separate page or tab. The Review can be a separate content type. Not required thou.

You can add as many vote fields (using Rate or Fivestar) as you want to your Reviews, one vote for each criteria you want to make available.
Your Reviews can be a new Content-Type (then you would use a Relationship in the Business View) or you can use Comments (of Business) for this propose. Both Content-Type and Comments are customizable: you can add fields to them.

My first choice would be to add n Fivestar rating fields to Business's Comments. You can do that in Business Content-Type Edition, in the "Comment Fields" tab.

But if you want each user to make only one review and have more control/customizations, then a new Content-Type for Reviews can make your life easier.


Link to a custom entity settings page does not appear at /admin/structure I have several custom entities as part of a module. When I visit /admin/structure, one of the entities is not listed in the groups of setting, or in the lists. However, if I manually type, /admin/structure/{entity}/settings/fields, I can manage the fields, form and display. However, the "Settings" tab is missing.

Similarly, I can manually type /admin/structure/{module}/{entity} to see the entity list, but the link is missing. The entity list is missing the button to add a new entity because the entire #block-seven-local-actions div is missing. Manually typing /admin/structure/{module}/{entity}/add brings up the correct form, and the form works.

It appears the routes are present, but something is preventing some of the links from being displayed. There are no errors in the recent log messages.

Please revise your file:

  yourmodule.links.menu.yml.

and verify if exists the parameter

  parent

A complete example

  yourmodule.admin_content:
  title: Content
  description: 'Find and manage content.'
  route_name: system.admin_content
  parent: system.admin_structure
  weight: -10


Check if cache cid exist I have this code:

$cache = \Drupal::cache();
$result = $cache->get('tdcf_00SPH46T');

Then, I got this notice:

Notice: Undefined index: tdcf_00SPH46T in Drupal\Core\Cache\DatabaseBackend->getMultiple() (line 92 of core/lib/Drupal/Core/Cache/DatabaseBanckend.php).
Drupal\Core\Cache\DatabaseBackend->getMultiple(Array, ) Line: 63
Drupal\Core\Cache\DatabaseBackend->get('tdcf_00SPH46T')_(Line: 46)
...

Is any way for check if this cid is defined, for example:

$cache->has('tdcf_00SPH46T');

What database backend are you using? Sounds like a case problem, that a cache entry with a different upper/lower case version exists and then it can't map that back. I'd suggest using only lowercase but this shouldn't happen IMHO and it doesn't for me:

>>> $cache = \Drupal::cache();
=> Drupal\Core\Cache\DatabaseBackend {#48
     +"_serviceId": "cache.default",
   }
>>> $cache->get('foo');
=> false
>>> $cache->set('foo', 'bar');
=> null
>>> $cache->get('foo');
=> {#9809
     +"cid": "foo",
     +"data": "bar",
     +"created": "1505412278.945",
     +"expire": "-1",
     +"serialized": "0",
     +"tags": [],
     +"checksum": "0",
     +"valid": true,
   }
>>> $cache->get('Foo');
=> false


Rules parameter description to appear in different lines I want the description of a Rule to appear in two lines. In the description field I have tried '' and '\n\r' but without any use.

  $items['my_custom_action'] = array(
    'label' => t('Some Label'),
    'triggers' => array('any'),
    'named parameter' => TRUE,
    'parameter' => array(
      'par1' => array(
        'type' => 'list<text>',
        'label' => t('Select an option'))),
        'options list' => array('1' => t('Option1'), '2' => t('Option2')),
        'description' => t('Line1') . '<br/>' . t('Line2'),
        'restriction' => 'input',
      ),
    ),
    'group' => t('My own group'),
  );

Please let me know how I can make the description appear in two lines.

It has to be simple. May be I am missing something basic :P

This should work

 $descp = "line1 </br> line2";

 $items['my_custom_action'] = array(
    'label' => t('Some Label'),
    'triggers' => array('any'),
    'named parameter' => TRUE,
    'parameter' => array(
      'par1' => array(
        'type' => 'list<text>',
        'label' => t('Select an option'))),
        'options list' => array('1' => t('Option1'), '2' => t('Option2')),
        'description' => t($descp),
        'restriction' => 'input',
      ),
    ),
    'group' => t('My own group'),
  );


How to get node editing form in a custom module how to call a drupal node editing form in a custom module? What i have done so far:

/*
 *  implementing hook_menu()
 */

function mymodule_menu() {
  $items = array();

  $items['custompage'] = array(
    'title' => t('Sometitle'),
    'page callback' => 'custom_page',
    'access callback' => 'user_access',
    'type' => MENU_NORMAL_ITEM
  );
  return $items;
}

function custom_page() {
  $output = '';
  $output = drupal_get_form(15);
  return $output;
}

But it won't output node edit form with nid 15. What i am doing wrong?

15 is the node ID of the node whose edit form you want, not the actual ID of the form. This makes sense since node edit forms are defined per nodetype, not per node.

You'll need to call drupal_get_form() with the form ID, something like [nodetype_name]_node_form.

The second parameter should be the node object, e.g. node_load(15).


Git flow feature in branch on stage server I am testing out a git feature and pushed the branch to the staging server to show the client.
Because it is a drupal feature, I think I need to revert the feature on the branch on the stage server.

My question is if I am in feature/branch and I revert the drupal feature to allow the updates to show up. When I checkout develop will that whipe away the revert I did on the feature/branch?

Thanks

If you switch from the feature branch back to develop, it won't wipe them out because the changes are stored in the database, and you should see an overridden status on the feature. Once you switch back to develop, you can perform a feature-revert again to change the settings back.

Either way, I would backup the database, either using Backup & Migrate, or directly on the server, just in case anything goes wrong.


Language code and country code on the URL I've been trying to achieve this:

I have a multilingual site with 8 languages (en, fr, es, de, etc) and I want to make all those language available for all countries.

I want Drupal to understand that:

/en-CO alias of /en
/en-FR alias of /en
/es-US alias of /es
/es-AR alias of /es
/fr-CO alias of /fr
/de-US alias of /de

And so on... (They share the exact same content)

If I add all those custom languages is easy, but I don't want because more than 1600 combinations are posible.

Do you know if there is a way to achieve that programmatically or with a module ?

I'm currently looking into PathProcessor, but no result for now.

Any help would be greatly appreciated.

I achieved this using Persistent URLs: https://www.drupal.org/project/purl and a custom LanguageNegotiation plugin


Access denied for custom configuration form translation I get access denied for just the translation page of a config form. I can access the configuration form and update it. No problem there.
The form lists in config-translation page as well, but when I click on Translate it gives access denied. I'm logged in as Admin. Below is the code as suggested here in my custom module (samplewil.module).

samplewil.links.menu.yml

samplewil.set_admin:
  title: 'sample settings'
  parent: system.admin_config_system
  description: 'Configure sample settings'
  weight: -10
  route_name: samplewil.set_admin

samplewil.routing.yml

samplewil.set_admin:
  path: '/admin/config/sample-settings'
  defaults:
    _form: '\Drupal\samplewil\Form\SampleForm'
    _title: 'Sample'
  requirements:
    _permission: 'administer site configuration'

samplewil.settings.yml

message: 'Hello'
 langcode: 'ar'

samplewil.config_translation.yml

samplewil.set_admin:
  title: 'Example Translatable config'
  base_route_name: samplewil.set_admin
  names:
    - samplewil.config

samplewil.schema.yml

samplewil.config:
  type: config_object
  label: 'Example config'
  mapping:
    message:
      type: text
      label: 'Message'

My default language is Arabic and I've given 'ar' in settings.yml.
Any idea why I'm not able to translate?

Got it finally working.
The 'name' array in config_translation was not matching with the actual file.

samplewil.settings.yml file should be renamed to samplewil.config.yml :)


Undefined index errors only on one subdomain On only one of my four registered domain names (foo.com, www.foo.com, foo.fr and www.foo.fr) am I'm getting undefined index errors such as:

Notice: Undefined index: vignettes in custom_page_preprocess_charger_accueil() (line 978 of /homez.119/retronom/www/sites/all/modules/custom/custom_page/custom_page.module).

The www.foo.com subdomain spits out these errors and is set up as a CNAME to foo.com.  I'm really stumped as to how this could affect only one of the subdomains.  What could cause these kinds of errors only on one?

Code setting up $varTemp:

//Vignette
if ($node->field_type['und']['0']['value'] == 1 && $node->language == $GLOBALS['language_url']->language) {
  $varTemp['vignettes'][$j]['image'] = theme('image_style', array (
    'style_name' => 'quick_link',
    'path'       => $node->field_image['und']['0']['filename'],
    'alt'        => $node->field_image['und']['0']['alt'],
    'title'      => $node->field_image['und']['0']['title'],
  ));

  $varTemp['vignettes'][$j]['link'] = $node->field_lien_site['und']['0']['value'];

Code that is failing:

While ($j != count($varTemp['vignettes'])) {  <-- Line 978
  if ($varTemp['vignettes'][$i]) {
    if ($varTemp['vignettes'][$i]['column'] == 'A') {
      $vars['vignettes']['A'][$a]['image'] = $varTemp['vignettes'][$i]['image'];
      $vars['vignettes']['A'][$a]['link'] = $varTemp['vignettes'][$i]['link'];
      $vars['vignettes']['A'][$a]['ombre'] = $varTemp['vignettes'][$i]['ombre'];
      $vars['vignettes']['A'][$a]['title_link'] = $varTemp['vignettes'][$i]['title_link'];
      if (isset($varTemp['vignettes'][$i]['body'])) {
        $vars['vignettes']['A'][$a]['body'] = $varTemp['vignettes'][$i]['body'];
      }
      $a++;
    ...
    snip
    ...
}

Since you don't say anything about any debugging effort, it's hard to say, but one thing repeatedly stands out as clearly wrong

$node->field_X['und']['0']

which should always be

field_get_items($node, 'field_X);

Since your domains are foo.com, www.foo.com, foo.fr and www.foo.fr, this might indicate that you use more than one language, which is exactly when ['und']['0'] is likely to break for you. Notice that field_get_items() will return an array instead of a single value, so you will need to amend your code to deal with that.


drupal 7, paths and urls are not working properly I'm developing a website on my localhost. I have a problem with urls.

for a url like this

http://localhost:81/my_website/library

I should output image src this way :

<img src="<?php print $directory; ?>/image/header/headerR.png"/>

but when the above url is changed to this

http://localhost:81/my_website/library/

I should output image src this way :

<img src="../<?php print $directory; ?>/image/header/headerR.png"/>

I mean it should refer to the parent. my website has also contextual filter which must be inserted after library/ .is there any general solution for handling such thing?

Use the global variables for resolving the issue of path of files as below:

Use base_path if your fine with domain name not to be included:
It will return path respect to the drupal root.
Eg:  "/" for drupal root(http://localhost:81/my_website), and
"/images/header" for http://localhost:81/my_website/image/header/header

Example:

/*Assuming image path: http://localhost:81/my_website/image/header/headerR.png*/
global $base_path; /* will return "/" for http://localhost:81/my_website*/
$image_path = $base_path . 'image/header/headerR.png';

Note: Don't use trailing slash / for adding path of files with $base_path as it adds a "/" to the beginning and end of the returned path.
Use base_url if you want to get the full path: It will return
base URL of the Drupal installation.

Example:

/*Assuming image path: http://localhost:81/my_website/image/header/headerR.png*/
global $base_url; /* will return http://localhost:81/my_website in you case*/
$image_path = $base_url . '/image/header/headerR.png';


How to store css & js in separate file & call in custom 'tpl' files through variable in drupal 7? I have created a custom module where I have define my page url's & contents are created through my custom tpl files.

I am applying some css & js on those custom contents/pages/tpl files.

What I want : I don't want to add path of those css & js in all pages. I want to define those css & js in separate file & I want to call that css & js in my custom pages through variable. Simply I want to create a header file which hold my css & js. And I want to call that header file in my custom pages.

Why I want to do this : Right now the path of the css & js is not fixed. So if am I add drupal_add_css() & drupal_add_js() in every tpl file then will change the path in every tpl file. So I want to create a header file where am I put the css & js path & if the path will change then I have to change the path in only header file.

How can I implement this?

If you do not want, or are unable, to modify the theme html or page templates, you can also use drupal_add_css and drupal_add_js in the page_callback function defined in your modules menu array youmodule_menu().

If you have access to the template.php of the theme,  you can use the preprocess hook to assign a variable to the file name, then do an include in the html template.  Or from within your module use drupal_add_html_head, but this has limitations.

Using drupal_add_(css|js) the links go into the head element of those pages by default before the themeing phase begins, but you can also specify the boostrap phase and location.

EDIT

Using drupal_get_path from within yourmodule_init hook or the page_callback, and with the css and js stored within your module structure, you can then add the css and js using the drupal_add functions.  This makes a single place you need to maintain the 'paths' to the files.


Prevent enabling module if private streamwrapper not set I need to create a subdirectory in the private files folder. I can check if the folder is available with variable_get('file_private_path', FALSE) in hook_install or hook_enable.

But how can I prevent my module from getting enabled? And preferably, I want hook_uninstall to run in case this happens so that the user can first setup the private files directory and then try again.

I played with module_disable and drupal_uninstall_modules, but (understandably) those don't seem to work if they target the module they are called from. I'm using Drupal 7.

The hook_requirements(), what do you need.

Implement it your own modules .install phase. Here is an example from one of my module: http://drupalcode.org/project/jquery_localscroll.git/blob/refs/heads/7.x-1.x:/jquery_localscroll.install#l20


Config import conflict, how to remove lock I am trying to import config on my staging site, and I repeatedly get the following message:

  Another request may be synchronizing configuration already.

I know that there are no other processes currently importing config, so there is some rogue lock.

I am using config_split module on the site, but both methods of config import report the lock.
I have updated the site to Drupal 8.6.1 but the issue may have existed prior to the update.

Question: How can I remove the lock using Drush or some other method?

My specific issue was that Redis module update to 1.0 brought with it new redis.services.yml file in the module. Updating my site's Redis services file, in sites/default/, resolved the issue.

What was happening was that the alreadyImporting() method of ConfigImporter defaults to true, when in fact my mis-configuration would have been returning an error I think.

This issue pointed me in the right direction: https://www.drupal.org/project/redis/issues/2996655

If it had been a simple lock issue the following should have worked I think:

drush ev "\Drupal::lock()->release('config_importer');"


Override entire user login / register page I am trying to figure out a way to override the entire /user page in D7.
There is a lot of articles out there that goes about altering the form, but I want to be able to rework the entire page (forms included) to get them into a nice bootstrap layout.

A lot of the information on the web is talking about page--user--login.tpl.php, but this does not work at all.

When using page--user.tpl.php, it seems to render my template file, but I cannot re-render the form.

When using

<?php
  $form = drupal_get_form('user_login');
  print drupal_render($form);
?>
My HTML goes here
<?php
  // Render any remaining elements, such as hidden inputs (token, form_id, etc).
  print drupal_render_children($form);
?>

I keep getting an infinite redirect loop. My best guess is because of a problem with the form_id that does not match.

Ps: I am using a bootstrap subtheme.

All information about this would be greatly appreciated.

In template.php, you could add an alter form to add classes, a wrapper, and I think also be able to add/edit fields in the form. Would that be of any help?

Example:

function THEME_NAME_form_user_login_alter(&$form, &$form_state) {
    $form['#attributes']['class'][] = 'custom-class';
}

in template.php would add the class custom-class around the login form, which you can then use to style the form.

As for using templates, I think they might have to be added in the correct location as well, e.g. I have recently built a site using custom templates with the user pages templates in /sites/all/theme-name/templates/user/. This also allows you to use custom markup. For example:

<div class="custom-class--wrapper">
    <?php print drupal_render_children($form) ?>
</div>

which is used in the file user-register-form.tpl.php.

Also, have you considered using panelizer to customise pages, that would be a lot easier than using template.php or custom templates. And if a change doesn't seem to take effect, you should try and clear the drupal cache.


Output node creation date between two fields I want to print the creation date of nodes of type article between two fields. I know you can do this with Display Suite, but I don't want to install the module only for this functionality. My only idea is to put an if condition into the for loop of field.html.twig to print the date after a certain field occurs, but I wonder if there is a better solution.

Yes, you would need a module like Display Suite only if you want to do this in UI. For a solution in code you can add extra information to the render array $variables['content'] in a preprocess hook:

mytheme.theme:

/**
 * Implements hook_preprocess_HOOK() for node templates.
 */
function mytheme_preprocess_node(&$variables) {

  $node = $variables['node'];

  if ($node->getType() == 'article') {
    $variables['content']['created'] = [
      '#markup' => t('
Node created: @created
', [
        '@created' => format_date($node->getCreatedTime(), 'medium'),
      ]),
      '#weight' => '5',
    ];
  }

}

Adjust weight to position it between the two fields.


Is it safe removing block-inner clearfix classes from block templates? Is it safe to remove block-inner clearfix templates from block? I use mainly context module which works with blocks. Looking at html there is too much wrappers involved. Thank you.

You can remove them, but they are there so that you can properly float elements within your content. That will depend on the modules you use (whether they include clearfix), and your own CSS.

Not sure about whether Admin requires it. In my case, I use an admin theme for all editing, precisely to avoid such complications.


db_query gives PDO Exception "General error: 1366 Incorrect integer value:" when I try to update table I'm trying to execute the following SQL query

$tweet_id_int = intval($tweet->id);
$result = db_query("INSERT INTO tweetsDB (handle,tweet,time_string,tweetid) VALUES     ('%v1','%v2','%v3','%v4')", array('%v1'=>$twitter_handle,'%v2'=>$tweet->text,'%v3'=>$tweet->created_at,'%v4'=> $tweet_id_int));

from inside a Drupal module and getting the error

    PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '%v4' for column 'TweetID' at row 1: INSERT INTO tweetsDB (handle,tweet,time_string,tweetid) VALUES ('%v1','%v2','%v3','%v4'); Array ( [%v1] => davecohen [%v2] => taking it easy - Rosh Hashana [%v3] => Fri Sep 14 08:06:08 +0000 2007 [%v4] => 267918272 )

handle, tweet and time_string are VARCHAR

tweetid is BIGINT

The "TweetID" is the value I received from calling the Twitter API earlier to fetch some tweets. Twitter API returns the Tweet ID as a string, so I called 'intval' before passing it to the SQL query. If I try running the same query into the MySQL database directly via the Sequel Pro console

 INSERT INTO tweetsDB (handle,tweet,time_string,tweetid) VALUES ('davecohen','taking it easy - Rosh Hashana','Fri Sep 14 08:06:08 +0000 2007','267918272')

Then I get no problems at all.

Any help here would be MUCH appreciated!

From the Drupal API on db_query:

  Do not use this function for INSERT, UPDATE, or DELETE queries. Those should be handled via db_insert(), db_update() and db_delete() respectively.

The recommended method:

// Insert values returned from Twitter API.
$tweetsdb_id = db_insert('tweetsDB')
->fields(array(
  'handle' => $handle,
  'tweet' => $tweet,
  'time_string' =>$time_string,
  'tweetid' => $id,
))
->execute();


How do I set allowed extensions for a managed_file form field? Not having any luck find this in Drupal documentation or developer examples.  I need to set a managed_file form field to only allow zip files in a Drupal 7 custom module.

$form['picture']['file'] = array(
  '#type' => 'managed_file',
  '#title' => t('picture'),
  '#description' => t('Allowed extensions: gif png jpg jpeg'),
  '#default_value' => (isset($foo->picture->fid) ? $foo->picture->fid : ''),
  '#upload_location' => variable_get('picture_upload_location'),
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
    // Pass the maximum file size in bytes
    'file_validate_size' => array(MAX_FILE_SIZE*1024*1024),
  ),
);


How to trick feeds into re-importing nodes? I have a content type in a feature. I am using feeds to import actual nodes from one site to another. I added new fields to the content type, and re-exported it into the features module. However, the feed ran before I updated the feature on the downstream site, and now it's not pulling the new field data. I know this will work, because it's worked before when I added new fields. However this time it's grabbed the data before it knew about the new fields.

How can I trick feeds into thinking it needs to update all the nodes? I tried setting the changed value on the nodes in the database to the current timestamp, but that didn't work. What criteria is feeds using to decide if the node data has changed?

In the feeds config area, under "Processor Settings", there is an option checkbox for "Skip Hash Check", which will cause the feed to update the items regardless.


How to move the login form to the header? I need help in moving over the User login form to the header of the same page in Drupal 7. I am new to Drupal and I am not very familiar with the Drupal hooks yet. How should I achieve this?
This is what I have tried so far.
template.php
function bklyn_theme() {
  $items = array();
  // create custom user-login.tpl.php
  $items['user_login'] = array(
  'render element' => 'form',
  'path' => drupal_get_path('theme', 'bklyn') . '/templates',
  'template' => 'user-login',
  'preprocess functions' => array(
  'bklyn_preprocess_user_login'
  ),
 );

 $items['user_pass'] = array(
 'render element' => 'form',
 'path' => drupal_get_path('theme', 'bklyn') . '/templates',
 'template' => 'user-pass',
 'preprocess functions' => array(
 'bklyn_preprocess_user_pass'
 ),
 );

return $items;
}

function bklyn_preprocess_user_login(&$vars) {
  $vars['intro_text'] = t('Username');
}

function bklyn_preprocess_user_pass(&$vars) {
  $vars['intro_text'] = t('Password');
}

I am not sure how I can integrate the login to show up in the header.
Before

After

from the website/user. I need the logon to place on the header content
  area and be able to style it.

All you have to do is edit your theme's page.tpl.php

Since the form gets displayed as the page content:

in the header section of your template file add:

<?php if (current_path() == 'user'): ?>
     <?php print render($page['content']);?>
<?php endif; ?>

Then find the original <?php print render($page['content']); ?> and add:

  <?php if (current_path() != 'user'): ?>
     <?php print render($page['content']);?>
  <?php endif; ?>

OR... do the if (current_path() != 'user') { for everything inside the #main-wrapper

OR... use the if statement to add a div class that will colour your #main-wrapper background to red.


Create a product after form submission using commerce and rules I want to set up a rule which would create a product when the user saves a submission form. The submission form is embedded into a simple node (using entity reference) presenting the "product" being sold. What I would like to do is to use information from that node when the rule creates the product.

The problem I am having is that I cannot find any valid way to get these fields to display in rules' data selector. The only way I found was to add the event "content is viewed" in addition to the event "after saving a new entityform". But I only want to keep the event related to the submission form.

So my question is the following: how can I display the fields contained in the node being viewed in rules' data selector without using this event? Thanks in advance for you help!

It depends on the implementation of this submission form, but a common way to expose fields in Rules is to add a condition 'Entity has field' in your rule.

In your particular case, you would select node as entity and the particular entity reference field.

In this way the rule will only execute if the node indeed has this field, and also will allow you to use the field in your actions below.


How do I find out which what fields are available? I'm looking to access the values of the fields in postSave().

public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
  //what's in $webform_submission? can I use it to get field data that was saved/submitted?
}

How do I get which fields are available from $webform_submission? How do I access them?

I have a field whose machine name is *feedback_type. I need to access its properties from that function.

UPDATE

So essentially what I'm wondering is, is there a way to see the structure of the $webform_submission variable? so that I can retrieve the data that the user submitted? I'd prefer to be able to do a print of it whether that's to a file/log/etc. doesn't matter I'd just like to know the structure of the $message_submission and its fields.

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

CustomHandler.php

For submission data:

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

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

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

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

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

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

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

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

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

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

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

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


How to print a field in a view only when it appears first? I have a View which lists products (nodes). In the View, I first display the taxonomy the node belongs to, and then the title and image of the product. I have ordered the query by taxonomy. The problem is that I get a repeated taxonomy for each row of the View (each product). How can I display the taxonomy just once, the first time it occurs, and then all the products belonging to that taxonomy, then another different taxonomy and its products and so on...

Now I have this result

Sports
    - The great book of soccer
Sports
    - Practicing tennis
Sports
    - Mastering Chess
Science
    - Quantum Mechanics
Science
    - Cold fusion

and I want this result

Sports
    - The great book of soccer
    - Practicing tennis
    - Mastering Chess
Science
    - Quantum Mechanics
    - Cold fusion

You can achieve this using the Grouping field setting in the view's Format settings. You will need to be using Fields (as opposed to Content) in the Format section of your view.

In your Fields list, click on the taxonomy term field to open the field configuration. Check Exclude from display and apply:

In the Format section of your view, click on the Format Settings.

The Grouping field Nr. 1 select list is available in each Format type, so no worries if you have it set to HTML list or another format. Change the field from None to the taxonomy field you want to group by and apply.

Your view will now show products grouped by the taxonomy term. From this point you can use the Sort criteria of the view to get the ordering of products or taxonomy terms you need.


How do I need to configure SMTP Auth? I have dedicated FreeBSD box, The email sending without smtp module is working perfectly but very slow. The receiver receives email after almost 15 mins. I checked the maillog it says delays and timeouts that means the server keeps on trying to send email again and again until it successfully sends one. This is consuming lots of CPU.

I am seeking help for configuring smpt module to use my dedicated box's  smtp server,
I need help in following places where I have ???? sign:

#SMTP server settings
SMTP server -> smpt.mydomain.com  # Tested by pinging, its working
SMTP backup server -> mail.mydomain.com  # Also verified by Ping
SMTP port -> 25
USE SSL

#SMTP Authentication
Username -> ???????
Password -> ???????

I tried using localhost, also username and password of the dedicated box or leaving both lines blank which gives me:

  Unable to send e-mail. Contact the site administrator if the problem
  persists.

also checking the debug log doesn't show any log, it says check admin/reports/dblog but when I got to the link it just shows me the contents from admin/reports no any dblog

Most providers block smtp ports, I had to use a mail redirection service when I set this up.

If the message gets through after 15 minutes though, I suspect you have a  mail server misconfiguration. Nowadays, I usually go for a much simpler approach, I use google's smtp server to send the emails.

An easy way you can test if port 25 is blocked is by connecting by SSH to a remote server, then trying to telnet on local server port 25.

telnet mail.port25.com 25

If the port is open, you should get a response similar to this:

Trying 69.63.149.30...
Connected to mail.port25.com (69.63.149.30).
Escape character is '^]'.
220 mail.port25.com (PowerMTA(TM) v4.0) ESMTP service ready

Another thing to check, if you are using qmail make sure the trigger file has proper permissions. qmail/queue/lock/trigger should be prw--w--w qmails:qmail.


How to merge loggedin and annoymous user's cart in drupal commerce To merge loggedin and annoymous user's cart for same session.

User (username:jone) adds something in the cart (Product 1). Before add to cart: Cart is empty
User adds something in the cart (Product 1). After add to cart: Order ID 15821 Line item IDs 159808

User registers and logins
User logs out

Annoymous User adds something in the cart (Product 1). Before add to cart: Cart is empty
Annoymous User adds something in the cart (Product 1). After add to cart: Order ID 15822 Line item IDs 159809

Annoymous User adds something in the cart (Product 2). Before add to cart: Order ID 15822 Line item IDs 159809
Annoymous User adds something in the cart (Product 2). After add to cart: Order ID 15822 Line item IDs 159809, 159810

Viewing the above log, somebody would assume that this user has bought 2 different products.

Now User checks out and login with username : jone
we want to after the login show/add last order product (159808)
However, currently we have the following situation.

Order 15821 Line item IDs 159808 are exist in database in checkout_checkout mode(status).
Order 15822 exists with 2 line items, 2 different products. Line IDs are 159809, 159810.

I want to be displaying all line items 159808, 159809, 159810.
but line item 159808 are not display

please suggest any solution.

I have solved this, by custom code.
First you create a login handler like.

<?php
function custom_module_form_alter(&$form, $form_state, $form_id) {

    if($form_id == 'commerce_checkout_form_checkout'){
        $form['buttons']['continue']['#submit'][2] = 'paypal_check_handler';
    }
}

function paypal_check_handler(&$form, $form_state){

    $order_number = $form_state['order']->order_number;
    $return = _get_current_stock($order_number);

    if($return['status']=='goto_paypal'){

     }else{
       db_query("UPDATE commerce_order SET status = 'cart' where order_id='$order_number'");
       drupal_set_message("We are sorry - Following items are no longer available in stock after you added them in shopping cart. <br/>".'&ldquo; '.$return['product_name'].' &rdquo;');
       drupal_goto('cart');
    }
}

/**
 * This function check current stock.
 */
function _get_current_stock($order_id) {

    global $user;
    $order = commerce_cart_order_load($user->uid); // get user order details
    // get all product id of current order
    $results = db_query("SELECT cp.product_id AS product_id, cli.quantity AS order_qty,fcs.commerce_stock_value AS stock_qty FROM commerce_line_item AS cli LEFT JOIN commerce_product AS cp ON cli.line_item_label=cp.sku LEFT JOIN field_data_commerce_stock AS fcs ON cp.product_id=fcs.entity_id WHERE cli.order_id='$order_id' AND cli.type IN ('product','commerce_auction_lineitem') ")->fetchAll();
    $product_ids = $qty = $stock_qty = array();
    /*
     * @var $product_ids            : Product ID array.
     * @var $qty[$product_ids]      : get each Product order quantity.
     * @var $stock_qty[$product_ids]: get each Product stock quantity.
     */
    foreach($results As $value){
        if(!empty($value->product_id)){
            $product_ids[] = $value->product_id;
            $qty[$value->product_id] = (int)$value->order_qty;
            $stock_qty[$value->product_id] = (int)$value->stock_qty;
        }
    }
    // product id array convert in string forn sql.
    $product_ids_query = implode($product_ids, ',');
    /*
     * Here get product remaining stock
     * @stock   : Stock
     * @order   : Order qty in order table ( status is checkout_payment).
     * @avail   : available qty
     * @stock - @order = @avail
     */
    $results2 = db_query("SELECT cp.title AS product_name, cli.line_item_label AS line_item, cp.product_id AS product_id,cli.quantity AS order_qty, FORMAT(SUM(cli.quantity),0) total_order_qty,  FORMAT(fcs.commerce_stock_value,0) AS total_stock_qty, FORMAT((fcs.commerce_stock_value - SUM(cli.quantity)),0) As available_qty FROM commerce_line_item AS cli LEFT JOIN commerce_product AS cp ON cli.line_item_label=cp.sku LEFT JOIN field_data_commerce_stock AS fcs ON cp.product_id=fcs.entity_id LEFT JOIN commerce_order AS co ON co.order_id=cli.order_id WHERE co.`status`='checkout_payment' AND fcs.commerce_stock_value!=0 AND cp.product_id IN ($product_ids_query) GROUP BY cp.product_id")->fetchAll();
    $available_qty = array();
    foreach($results2 As $value2){
        $available_qty[$value2->product_id] = $value2->available_qty;
        $available_product_name[$value2->product_id] = $value2->product_name;

    }
    $redirection_var = array();
    $redirection_var['status'] = 'goto_paypal';
    foreach($product_ids AS $product_chk){
        if(!empty($available_qty[$product_chk])){
            $current_stock_qty = (int)$available_qty[$product_chk];
        } else {
            $current_stock_qty = (int)$stock_qty[$product_chk];
        }

        $ordered_qty = $qty[$product_chk];
        if($current_stock_qty > 0){
            // go to paypal
             $redirection_var;
        } else {
            $current_product_name = $available_product_name[$product_chk];
            $redirection_var['product_name'] = $current_product_name;
            $redirection_var['status'] = 'not_goto_paypal';
            return $redirection_var;
        }
    }
    return $redirection_var;
}
?>

Thankyou :)


Custom form template without any region I made a custom log in, register and forget password templates, to hide the theme region and wrote a css code.
the issue here when open the page using colorbox module the regions appear for few second before they hide by css code, what i need to disable the theme region in those custom pages.
any advices?
Thanks.

All you need to do is search your page.tpl.php for parts like:

print render($page['region_name']);

and then wrap them in appropriate if construct, not rendering them at all on pages you don't want to see them rendered.

Alternatively, you can create files named page--user.tpl.php, page--user--login.tpl.php and so on. See this answer for details. Simply copy default page.tpl.php and remove unneeded regions from a copy.


GMap shows on page inspect I am using GMap Module (in Drupal 7). Map does not show on page load, but when I inspect the web page, map shows up.
I tried reinstalling module but in vain.
Map shows in GMap Configuration, but on node page it shows only if user inspects page. I have made no change in default GMap code
If anyone has solution to this issue, please share
A bundle of Thanks.

you need to trigger resize when the map is shown.

Try this code:

 $(document).ready(function () {
      $('#mymodal').on('shown', function () {
        google.maps.event.trigger(map, 'resize');
      });
    });

Hope this will help you.


How to create a user with field collections programmatically? This is what I use to create the user:

    $new_user = array(
        'name' => $form_state['values']['email'],
        'status' => 1,
        'access' => REQUEST_TIME,
        'roles' => array(),
    );

   user_save('', $new_user);

Now I want to add values to the field collection items.
I have a field collection called field_personal_details and a field collection item called field_firstname, but I have no idea how to access it. Can someone help me get started?

I think following code should give you an idea.

    //Create a field collection entity
    $field_collection_item = entity_create('field_collection_item', array('field_name' => 'field_personal_details'));
    $field_collection_item->field_firstname[LANGUAGE_NONE][0]['value'] = "Yassin Tahtah";
    //$field_collection_item->field_firstname['und'][0]['value'] = "Yassin Tahtah";
    $field_collection_item->setHostEntity('user', $user);
    // Save the entity.
    $field_collection_item->save(TRUE);


Product reference field causes $title to be empty Update: After removing fields one by one, I've discovered that the Product reference field caused $title to be empty.

I have several content types which are displaying both the <title> and $title well, but in my "Product Display" content type (of commerce kickstart) I find that the $title  header is missing, although the <title> tag is there, i.e. the title bar of my browser is displaying the page title correctly. The contents of <title> and $title are similar. Excep that <title> has the site name added to the end of the node title.

I've viewed page source it shows that h1 isn't printed. I've never written any code to hide any h1 tags. I'm using Display suite on that page and I've disabled it on that content type and it didn't help. I am not using Context on that page. Please advise me on how I should proceed, thanks!

Update: Devel->load shows that the title is set correctly, but when I created a template for that node (page--node--42.tpl.php), and tested if it worked by hiding the header and footer, I added this line of code

<?php print $title; ?>

but all I got is am empty $title

Update 2: I've inserted a block using  [current-page:title] and it works, however I'd prefer not to stick with this duct-tape solution if possible

Check the content types display tab. It may be set to hide the title.


How does block page whitelisting work? I've created a custom entity which only should to be displayed on pages provided by the user.

To handle multiple pages, I've created a textarea where the user can enter a page per line. Just like the blocks module.

My problem here is that I don't know how to make the query that loads the correct entity by page.

My guess is that it should be something like this:

SELECT * FROM {my_entity} WHERE pages LIKE :path

However, that leads to the problem that 'node/1/edit' also loads the entity when the user has entered 'node/1'.

I know this functionality already exists somewhere in Drupal because it is used for blocks, but I can't find it in the code...

The related code is found in block_block_list_alter() function, inside /modules/block/block.module file.

Here's how you would perform a similar check in your code:

// Get the pages to check. This should be in the same format as what Drupal
// core uses - meaning one path per line and you can use placeholders.
//
// Variable below is just as an example.
$pages_to_check = 'page1' . PHP_EOL . 'page2' . PHP_EOL . 'page3/*';
// This is a good practice, because it will make sure that paths are always
// checked consistently and won't depend on the case.
$pages = drupal_strtolower($pages_to_check);
// Compare the lowercase internal and lowercase path alias (if any).
$page_match = drupal_match_path($path, $pages);
if ($path != $_GET['q']) {
  $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
}
// Now you can do whatever you want based on whether or not the current path
// matches the pattern. For example:
if ($page_match) {
  // You are on one of the listed pages.
}
else {
  // You are not on one of the listed pages.
}

Hope this helps.


Can View content be filtered to what's new since user's last login? We have a View that displays recently created content of a specific custom type – currently, it's showing the titles of the most recent 3 items. The site requires login, so can identify unique individuals. So how might we get this View to display only the items that are new since a particular user's last login? Or is there another way to display such a content list, other than by Views?

In your view, add a new filter criteria for "Content: Has new content." This should do exactly what you want.


Is there a module that makes Taxonomy tags like they are on stackexchange sites? I'm Looking for a module that makes my free tagging taxonomy tags like they are on this or any other stack exchange site. I would like for when a user puts their cursor in the Autocomplete tag field, it displays a list of suggested tags for them to select. Also, I would like to incorporate tag aliases/synonyms so multiple tags relate to one another. I'm running Drupal 7 and I figure I could use permissions on my taxonomy set to allow people to create new tags based on their role. Does anyone know of a module or way to get this functionality? Thanks.

Active tags will give you the look & feel of stackexchange's tags but won't provide the nice description and suggestion list that SE sites have.


Additional tab in custom module's admin configuration page Can't figure out why two admin pages of my custom module are not showing in different tabs. I've disabled and re-enabled the module, cleared cache, however while both pages are accessible and I see the "Leads" link in the menu, unfortunately they are not aligned into tabs. Can anyone help me to get my tabs?

/**
 * Implementation of hook_menu().
 */

function leads_menu() {
  $items = array();

  $items['admin/commerce/leads'] = array(
    'title' => 'Leads',
    'access arguments' => array('administer leads'),
    'page callback' => 'leads_active',
  );
  $items['admin/commerce/leads/subscribed'] = array(
    'title' => 'Subscribed Leads',
    'page callback' => 'leads_subscribed',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

  return $items;
}

It seems that first main path 'admin/commerce/leads' needs to be defined, and then other two items added.  The first item inherits the properties of the main menu item, and the second defines its own callbacks. Far from obvious, but it works for me now:

  function leads_menu() {
  $items = array();

  $items['admin/commerce/leads'] = array(
    'title' => 'Leads',
    'access arguments' => array('administer leads'),
    'page callback' => 'leads_active',
  );
  $items['admin/commerce/leads/active'] = array(
    'title' => 'Active',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );
  $items['admin/commerce/leads/subscribed'] = array(
    'title' => 'Subscribed',
    'page callback' => 'leads_subscribed',
    'type' => MENU_LOCAL_TASK,
    'access arguments' => array('administer leads'),
  );

  return $items;
}


URL in link field adds duplicate parameters in query string when using an internal relative path Newbie Drupal 8 user using a link field to add url's like:

/samples/products?f%5B0%5D=market%3A1

when saved makes the actual link /samples/products?f%5B0%5D=market%3A1&f%5B1%5D=market%3A1&f%5B2%5D=market%3A1

It's really /samples/products?f[0]=market:1 encoded so maybe the link field doesn't like this? Adding links like this in other places like in wysiwyg editors work fine it seems that the link field is adding two more times.

Any ideas on where that might be happening? Could there be a bug in link module or is there an issue with using internal url's this way? Any help would be greatly appreciated. Thanks!

Seems like a bug in Core at the moment. Follow the issue queue: https://www.drupal.org/project/drupal/issues/2885351

Seems like a workaround currently is to use full paths instead of relative ones or use the patch in the issue above to patch core.

There seems to be a module someone made too since patching core isn't ideal:
https://www.drupal.org/project/link_formatter_query_fix


Views one to many relationship, display many records in columns I have a View with a one to many relationship. ID and Session are in my main table, and "mark"'s are rows in a custom table. When I look up a single ID, I get this result because of the 'many' results in the custom table.

ID | Session     | mark

15 | Spring 2013 | 16

15 | Spring 2013 | 3

15 | Spring 2013 | 5.5

My desired result is:

ID | Session     | mark 1 | mark 2 | mark 3

15 | Spring 2013 | 16 | 3 | 5.5

How about using the viewsfield module? You can try solving your problem by creating two views A and B, such that -

View A excepts an argument 'ID' and lists all the marks associated with it, by having only the 'marks' field included for display/output.
View B has an ID field, a session field, and a viewsfield. In this third field the view A is embedded.

I hope this helps. I have not tried this, but I am reasonably sure it should help if the module is doing what it promises to do.


Set body format for a node when it is updated via REST API I noticed that when I PATCH a node and update the body value, the body format and summary are set to null.

If I try to add the summary and format to the json sent to the API, I receive an error saying:

Unprocessable Entity: validation failed.
Body: this field cannot hold more than 1 values

Any ideas why I get this error and how can I preserve the body format?

This is my js object:

{
  title: { value: this.state.title },
  body: { value: this.state.body, format: "basic_html" },
  type: { target_id: 'article' },
  _links: {
    type: {
      href: 'http://localsite.dev/rest/type/node/article'
    }
  },
}

If I remove the format: "basic_html" part, I get no errors but the format and summary are set to null.

Thanks.

Kind of surprised this even works. The value of a field is a list of field items. Try something like this:

body: [ { value: this.state.body, format: "basic_html" } ],


View Slideshow with different effects on the same view I want to create a slideshow with caption using Views Slideshow.
I've set up a view with image | description fields, but everything slide at the same time. How can I set different effects for different field? Should I use different views and attach them together?

If you want to implement different effect for each slide, then you can use views fractionslider module to implement same.

  jQuery plugin for image/text-sliders. It allows you to animate
  multiple elements per slide. Set different animation methods like fade
  or (from) left, delays and easing for each element, or simple set some
  defaults in the plugin options. You also have full layout/design
  control through html and css (every html-element can be animated). Its
  also fully responsive.


Create a checkboxes-field with a radiobutton for all items Usercase:
Have a list with services for shops. Those services can be done with an appointment, or without. So the services are checkboxes, and the radio needs to show if it can be done with or without an appointment.

I am scratching my head over this, tried some modules like double_field and composed_field, but they do not fit this case it seems. End-users must be able to choose the services they sell, and also verify if they sell this with or without an appointment.

Example-sketch:

You can also achieve that using the Double Field module.

Go to your content type and add field Type as Dobule field and Wideget as checkbox and checkbox

You can add Prefix or suffix for each field to display them as label for them.

Additionally you can use the Field Group module to make them under a roof.

Here is the screenshot:


Submit handler does not work I am trying to handle multiple submit buttons, but the handlers does not get called.

I am following http://www.hooksupport.com/blog/drupal-8-how-handle-multiple-submission-buttons-drupal-8-form, and this is the code I am using.

$form['add_field'] = array
    (
      '#type' => 'submit',
      '#value' => $this->t('Create field'),
      '#submit' => array('::create_field_submit'),
    );

 public function create_field_submit(array &$form, FormStateInterface $form_state){
     drupal_set_message(t('Form Submitted Successfully'), 'status', TRUE);
}

The message I've trying to send does not appear. Why?

If this is not working, then the reason for this is, that the block plugin is not the form class. This is BlockForm, which calls the methods in the plugin while building, validating and submitting the form. So if you want to add custom code to the submit in a block plugin override:

public function blockSubmit($form, FormStateInterface $form_state) {}

This code will then be included when the form class calls submitConfigurationForm().

If you have more than one submit button you can check the triggering element in $form_state.

Edit:

Another option is to use a static submit function instead of the class method.


Can failure to increase new user's UID consistently by one be related to this line inside user.module file? I have noticed at my Drupal 7 that there are gaps between the uid's of new users. The UID of a new user should increase by one from the highest assigned UID in database. However, I have noticed gaps of even a thousand.

Inside user.module file, there is the following code:

// Allow 'uid' to be set by the caller. There is no danger of writing an
      // existing user as drupal_write_record will do an INSERT.
      if (empty($account->uid)) {
        $account->uid = db_next_id(db_query('SELECT MAX(uid) FROM {users}')->fetchField());
      }

I have made the QB query read like this:

$account->uid = db_next_id(db_query('SELECT MAX(uid) FROM users')->fetchField());

It appears that this solves the issue. My question, is there really a mistake inside the core user.module file? Is it safe to modify the file the way I did? Thanks.

UPDATE:

The above does not make a difference after all. I have changed the line to this:

$account->uid = db_query('SELECT MAX(uid) FROM users')->fetchField() + 1;

This works with no reference to db_next_id. For me it is very important to increase the uid's always by one and this is one way to do it.

uid and other identifiers are not sequential since Drupal 7. Identifiers are generated using a sequence API, see this issue: https://www.drupal.org/node/356074

If you check the db_next_id you'll see that the number passed as argument is just de minimum id that is considered valid.

See also this question and answer: What could cause uids to not be numbered consecutively?


Assign existing field to new content type programmatically I'm developing a module that create a several new content types:

function create_new_content_type($type, $name){
    $t = get_t();

    $new_node = array(
        'type' => $type,
        'name' => $name,
        'base' => 'node_content',
        'custom' => TRUE,
        //'description' => 'This is an example node type with a few fields.',
    );
    $content_type = node_type_set_defaults($new_node);
    node_add_body_field($content_type);

    // Check if we create content type or update.
    $status = node_type_save($content_type);

    // Replacement rule for the messages.
    $t_args = array('%name' => $content_type->name);

    if ($status == SAVED_NEW) { // create case
        watchdog('node', 'Added content type %name.', $t_args, WATCHDOG_NOTICE, l($t('view'), 'admin/structure/types'));
        return true;
    }

    return false;
}

after that creates a new fields for that type (for example):

function createTextField($name, $label, $bundle, $required=FALSE){
    // Create the field base.
    $field = array(
        'field_name' => $name,
        'type' => 'text',
    );
    field_create_field($field);

    // Create the field instance on the bundle.
    $instance = array(
        'field_name' => $name,
        'entity_type' => 'node',
        'label' => $label,
        'bundle' => $bundle,
        // If you don't set the "required" property then the field wont be required by default.
        'required' => $required,
        'widget' => array(
            'type' => 'textfield',
        ),
    );
    field_create_instance($instance);

}

Lets assume I have already existed field with name field_my_custom how can I attach it to my new created content type? (if I understand right in the method above I only create new fields).

No creating a new instance means you are attaching that field to a content type. Here $bundle is the machine name of the content type


Body field in colorbox Is it possible to have body trimmed to lets say 150 chars with read more link, and when you click read more, full body field opens in colorbox ?

If you have Colorbox installed, you can install Colorbox Node & Overlay which will let you create a colorbox node link with a colorbox-node class (e.g. My Node).

In your theme's node preprocess function, you can add that class to the read more link:

/**
 * Implements hook_preprocess_node() in your theme's template.php
 */
function MYTHEME_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'teaser') {
    $variables['content']['links']['node']['#links']['node-readmore']['attributes']['class'] = 'colorbox-node';
  }
}

You'll need to adjust your theme's stylesheet rules to hide the non-body fields (and other styling as necessary), but it will work.


Shared Database With Domain Access and Multiple Accounts With Same Email We are planning to have the following Drupal architecture:

One install of Drupal.
Multiple domains sharing the same database using the Domain Access module.

Each domain will have user login capabilities, and user accounts will not be shared across domains. This means we will have times when one email address could be associated with multiple accounts (one for each domain where the email address is associated with an account).

Is such an architecture possible using a shared database, or will we have problems trying to associate many accounts to the same email address?

You should not use Domain Access unless you are planning on sharing users and content between the different domains.  In your instance, you do not want to share users -- and yes, you would have problems if you tried to have duplicate user entries sharing the same email address.  You are therefore better off creating multiple independent Drupal sites, and replicating shared content (if any) via other means.


Javascript libraries not loading from block class I am working on porting module to drupal 8.

My block code is as follow

public function build() {
  $delta= $this->getDerivativeId();
  $num           = str_replace('dexp_layerslider_block_', '', $delta);
  $sid = $this->configuration['dexp_layerslider_block_slide_'.$num];
  $block_id = $this->getDerivativeId();
  $slideshow = dexp_layerslider_load($sid);
  if (!$slideshow){
     return 'No slider selected';
  }
  $content =   array(
      'id' => $sid,
      'slides' => $slideshow->slides,
      'settings' => $slideshow->settings
     );
   return array(
     '#theme' => 'dexp_layerslider_slides',
     '#items' => $content,
     '#attached' => array(
        'library' => array('dexp_layerslider/dexp.block'),
        ),
      );
}

my yaml file:

dexp.slides:
  version: 1.x
  css:
    theme:
      plugins/font-awesome/css/font-awesome.min.css: {}
      css/admin.style.css: {}
      plugins/rs-plugin/css/settings.css: {}
  js:
    js/dexp.layerslider.js: {}
    js/layeroption.js: {}
    js/admin.layerslider.js: {}
    plugins/rs-plugin/js/jquery.themepunch.revolution.min.js:  {}
    plugins/rs-plugin/js/jquery.themepunch.tools.min.js:  {}
 dexp.block:
  version: 1.x
  css:
    theme:
      plugins/rs-plugin/css/settings.css: {}
      css/layerslider.css: {}
  js:
    plugins/rs-plugin/js/jquery.themepunch.revolution.min.js:  {}
    plugins/rs-plugin/js/jquery.themepunch.tools.min.js:  {}
  dependencies:
    - core/drupal
    - core/jquery

my theme function :

  $themes['dexp_layerslider_slides'] = array(
    'template' => 'slides',
    'path' => $path . '/theme',
    'pattern' => 'layerslider__',
    'preprocess functions' => array(
      'template_preprocess',
      'dexp_layerslider_preprocess_slides'
    ),
    'variables' => array('items'=>null),
  );

None of  javascript and css files are load , when i try to access items in twig template {{ items }} nothing gets printed , though if write random string in the my slide.html.twig file it get printed. where i could be going wrong?

You don't have a "dexp.slide" defined in your libraries.yml file. Only "dexp.block".

You're trying to attach a library that doesn't exist.


How to manually or programmatically delete a field? I tried creating a field, but my server crapped out halfway with an Internal Server Error due to some spambot attack...

Now, when I try to add the field again, I am getting:

  The machine-readable name is already in use. It must be unique.

I guess some tables were populated in the db. How can I remove these easily?

You can also use drush to run field_delete_field(). Just run:

drush eval 'field_delete_field("yourfield")'


How to show a place holder block if a view is empty I have a site that has multiple inventory views. When a view is empty (no items to list) I need to display a block that tells the user to check back later.

How can I do this?

Views has a feature that already accommodates this; under the Advanced section there is a NO RESULTS BEHAVIOR option that lets you add different fields on the condition there are no results in the view.


Create views from combination of various vocabularies' terms I am trying to find out if there is a module that can work out this magic or if I need to make a custom solution.

The problem:
I have Vocabulary1, Vocabulary2, Vocabulary3. The ideal would be to have something like tagadelic for all 3 vocabularies on the side, so whenever a tag is clicked the content displayed is additionally filtered by that extra tag.

You can have nice block displaying all terms coming from your mentioned vocab by help of Cumulus.

Though its in DEV mode but it works fine. This requires module Tagadelic to be enabled first.

You can create a cumulus block by visiting admin/structure/block/add-cumulus-block, where you can mention name of the block & setting for it such as Vocabulary IDs to be included, Number of tags to display, Width, Height etc..


Callback function on change event I need to execute some functions when a field value changes. I tried both Drupal AJAX framework and classical Jquery, but in both cases the callback function is not executed.  Adding a Jquery .change() :

(function ($, Drupal, window, document, undefined) {
  $(document).ready(function(){
    $("#foo").change( function(){
      var selected_date = $(this).val();
      $.ajax({
        type: "POST",
        url: "MYURL/"+selected_date ,
        data: selected_date,
        success: alert( selected_date)
      });
    });
  })
})(jQuery, Drupal, this, this.document);

The Jquery works fine. Then

/**
* Implementation of hook_menu().
*/
function MYMODULE_menu() {
  $items['MYURL/%'] = array(
    'page callback' => 'MYMODULE_get_liberte_id',
    'page arguments' => array(1),
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
  );
  return $items;
}

function MYMODULE_get_liberte_id ($selected_date) {
  //DB queries and form alter or error messages here
}

I also tried with AJAX Framework :

//hook form alter
$form['foo']['#ajax'] = array(
  'callback' => 'MYMODULE_ajax_callback',
  'wrapper' => '.center-wrapper',
 );

function MYMODULE_ajax_callback($form, $form_state) {
  //is the function fired ???
  $commands[] = ajax_command_alert(t('MYMODULE_ajax_callback fired'));
  return '
'.date('Y-m-d').'<xmp>'.print_r($form_state['values'], true).'</xmp>
';
  //DB queries and form alter or error messages here
}

dsm($form) shows that the field got #ajax attribute, but the callback function isn't executed.

I'm afraid I'm not on the right way, or at list I'm missing something :(

The #ajax['wrapper'] value should be id attribute, not a class, and without '#'. You can look about this here. The callback function should return a html content, a renderable array (which will replace the 'wrapper' on a call) or array of drupal ajax commands. You can try this and your code should work:

function MYMODULE_ajax_callback($form, $form_state) {
   $commands[] = ajax_command_alert(t('MYMODULE_ajax_callback fired'));
   return array('#type' => 'ajax', '#commands' => $commands);
}


How to use HTML tags in email? I have a triggered rule, when a content is Published the author receives email.
I want to show my logo in the email but so far I could not find how to do that.
Any help appreciated?

I wrote this in email message body, but instead of an image, I see only HTML text.

<img src="http://www.vragenenislam.com/misc/logomuz.png" alt="Vragen en Islam" />

Check out Mime Mail; that should do the trick.

  This is a Mime Mail component module (for use by other modules).

  It permits users to recieve HTML email and can be used by other modules. The mail functionality accepts an HTML message body, mime-endcodes it and sends it.
  If the HTML has embedded graphics, these graphics are MIME-encoded and included as a message attachment.
  Adopts your site's style by automatically including your theme's stylesheet files in a themeable HTML message format
  If the recipient's preference is available and they prefer plaintext, the HTML will be converted to plain text and sent as-is. Otherwise, the email will be sent in themeable HTML with a plaintext alternative.
  Allows you to theme messages with a specific mailkey.
  Converts CSS styles into inline style attributes.
  Provides simple system actions and Rules actions to send HTML email with embedded images and attachments.


Avoid admin users editing other admin users I'm in a Drupal 7 installation, trying to find a way to avoid admin-users to edit other admin-user's account.

I've created a role for 'content administrators' and this users tasks involve user administration, but I don't want them to be able to edit other content administrators or admin accounts.

I wasn't able to find an option for this or a module providing the functionality and I'm a bit lost about how this can be achieved.

In D6 I guess could use hook_user() to catch an edit and check the target role in order to allow that edit or not, but this hook is gone on D7. The closest thing is hook_user_alter(), but this is called after the edit, so I can't use it.

Any pointers?

Just use the User Protect module.

This module provides various editing protection for users. The protections can be specific to a user, or applied to all users in a role.

Note: User Protect has a complicated configuration -- please take the time to read the very extensive module help before using it!

The following protections are supported:

username
e-mail address
password
status changes
roles
deletion
OpenID identities
all edits (any accessed via user/X/edit)

When a protection is enabled for a specified user (or the protection is enabled because the user belongs to a role that has the protection), it prevents the editing operation in question that anyone might try to perform on the user--unless an administrator who is permitted to bypass the protection is editing the specified user. The module will protect fields by disabling them at user/X/edit.

User administrators may be configured to bypass specified protections, on either a global or per-administrator basis.

These protections are valid both when trying to edit the user directly from their user/X/edit page, or using the mass user editing operations.

The module also provides protection at the paths user/X/edit and user/X/delete, should anyone try to visit those paths directly.


Commerce Stripe webhook I use the Drupal Commerce Stripe module to create subscription charges in a Drupal web, through the Stripe platform. Everything seems to work well, the clients are created, the charges are produced and appear in Stripe's Dashboard .... I also have a webhook that seems to work too. The problem I have is that I need to implement within the webhook itself the ability to complete certain fields with the response that Stripe sends to that webhook. These data must complete the profile of the user who made the payment. Any idea what this would be like?

I'm talking about Drupal 7

This is my webhook

<?php

require_once('vendor/autoload.php');
\Stripe\Stripe::setApiKey("sk_test_*************");

$input = @file_get_contents("php://input");
$event_json = json_decode($input);

$event_id = $event_json ->id;
$event_type = $event_json -> type;
$customer_email = $event_json -> receipt_email;

if ($event_type == "charge.succeeded") {
  $msg = "test webhook";
  mail($customer_email, "Test suscrip", $msg);

*/*Here I would like to be able to send certain data of the json object to certain fields of the user profile*/*

}

http_response_code(200);

?>

It sounds like you want to load the user object from the email address, set some field values, and save it again.

In code that would look something like this:

if ( ($account = user_load_by_mail($customer_email) ) {
  $account->field_foo[LANGUAGE_NONE][0]['value'] = $event_json->foo;
  $account->field_bar[LANGUAGE_NONE][0]['value'] = $event_json->bar;

  user_save($account);
}


Elysia cron stuck in (w) state (wating to be executed) I have a few crons set up to run every 15 min. My system cron is set to execute every 5 mins. However one cron keeps getting stuck in the (w) state. I updated its setting to run every minute (* * * *) and still every time the cron run all jobs get executed except for one
homepage_extensions_cron (w)   - [run]
* * * * *   09/06/2013 - 15:14  7s  4   3s / 7s
This is really troubling me.

When I run the cron manually ( replicating what the system is doing) the cron runs fine. I do it through curl. When I execute the curl through command line, the task runs. I am suspecting there is some timing tricky stuff here. Can someone please explain how this work? Also, I am trying to clear a certain cache id in the cron task and do an http request. Could this cause an issue?

The "(w)" flag means only that the job is ready to be executed (waiting for the system crontab to start and execute it).

If a job has a rule like "* * * * *" (= execute it EVERY minute), it's quite normal that the "(w)" is always on.

If you use a rule like "* * * * *", assure that system crontab is set to "* * * * *" too. That way you minimize the (w), because system crontab runs every minute too and executes the job as fast as possible.

(However, a little time with (w) is normal and not to be considered a problem).


How can I use UUID in a Views relationship? Two content types: subscriptions and sites. Each site belongs to a subscription. I use the UUID module, since subscriptions and sites are synced from websites elsewhere. Each site has a field_subscription_uuid field to identify the subscription it belongs to. There can be multiple sites on each subscription.

I want to make a view that lists sites alongside some of the data from their subscription. I thought I would use the Equi Join module to relate a site's field_subscription_uuid to a subscription's uuid. However, Equi Join only lists custom fields (and body), not UUID.

Although I could create a new custom field for subscriptions and sync its own UUID to that field to make it visible to Equi Join, I would rather not because it would be redundant (since the UUID is already a column in the node table).

So I think I have to write a views relationship handler in order to bring a node's uuid into the scope of Views relationships, but I don't know where to start and the API documentation has only confused me more.

How can use a specific node type's UUID in a views relationship without storing the UUID in a custom field?

I figured out how to do this. It doesn't require a custom relationship handler. In MYMODULE.views.inc:

/**
 * Implements hook_views_data_alter()
 */
function MYMODULE_views_data_alter(&$data) {
  // Add a relationship between the field_subscription_uuid field and node UUIDs
  $data['field_data_field_subscription_uuid']['field_subscription_uuid_value']['relationship'] = array(
    'title' => t('UUID'),
    'help' => t('Relationship for field_subscription_uuid to node UUID.'),
    'handler' => 'views_handler_relationship',
    'base' => 'node',
    'base field' => 'uuid',
    'label' => t('UUID'),
  );
}


Get/print current Ubercart currency via template.php I am using Ubercart on D7.

Does anybody know how I can get the current Ubercart currency (e.g. $, €, etc) in template.php?

I am overriding the add to cart button via hook_form_alter, and need to print the site's current currency (in case of multi-currency) in the button markup.

thanks

/**
 * Implements hook_node_load().
 */
function NAME_OF_MY_MODULE_node_load($nodes, $types) {
    $language = $GLOBALS['language']->language;

    if($language == 'en') {
        $variables['uc_currency_code'] = 'EUR';
        $variables['uc_currency_sign'] = '€';
        $variables['uc_currency_thou'] = ' ';
        $variables['uc_currency_dec'] = ',';
        $variables['uc_currency_prec'] = '2';
        $variables['uc_sign_after_amount'] = 1;

        variable_realm_switch('currency', 'eur', $variables);

        // increase price by 1000
        foreach($nodes as $key => $value) {
            if(isset($value->price)) {
                $nodes[$key]->price += 1000;
                $nodes[$key]->sell_price += 1000;
            }
        }
    }
}

Requires Variable module. I hope it helps


How to combine multiple view result sets, limiting the combined result set I want to create a 'suggested content' display that, by default, displays 4 nodes that share terms on a term reference field belonging to the currently node. So, if the current node is tagged with "baking" and "family", it should display nodes that have those terms in common. I have this working — all is good here.

Also, on the reference node I've added an entity reference field that allows editors to curate their own suggested content. My intention is to put this curated content at the beginning of the suggested results, so that if an editor specifies 2 nodes, the other view will populate the other 2 nodes.

Basically, what I think I need to do (correct me if I'm wrong), is to combine the results from two views (one displaying the curated nodes, the other displaying the term-related nodes), and limit them to the top 4 entries, ensuring that the curated nodes are displayed first.

If this was confusing, this image should make it clearer;

How can I combine the results from two views and limit the combined result set? Also, note that each view only uses a single field for each row (a rendered node).

Here's what I ended up doing (not using views). I'm using Panels on this site, and my default view for this content-type is controlled via Panelizer. Since I couldn't find a way to do this with Views, I created a custom panels pane (code below).

Basically, this pane accepts one setting: the number of related events to display. The render callback counts the editor-defined related nodes, and grabs more (if needed) based on shared terms.

<?php

$plugin = array(
'single' => TRUE,
'title' => t('Suggested Events'),
'description' => t('Combines curated suggested events with those related by category.'),
'category' => t('Custom Panes'),
'edit form' => 'MYMODULE_suggested_events_edit_form',
'render callback' => 'MYMODULE_suggested_events_render',
'admin info' => 'MYMODULE_suggested_events_info',
'defaults' => array(
  'events_to_show' => 4
),
'all contexts' => TRUE,
);

/**
 * Edit Form.
 */
function MYMODULE_suggested_events_edit_form($form, &$form_state) {
$conf = $form_state['conf'];

$form['events_to_show'] = array(
  '#title' => t('Number of events to show'),
  '#description' => t('Used to control the number of suggested events shown. Defaults to 4.'),
  '#type' => 'select',
  '#options' => drupal_map_assoc(range(3, 6)),
  '#default_value' => $conf['events_to_show'],
  '#required' => TRUE,
);

return $form;
}

/**
 * Submit callback for settings form.
 */
function MYMODULE_suggested_events_edit_form_submit($form, &$form_state) {

foreach (array_keys($form_state['plugin']['defaults']) as $key) {
  if (isset($form_state['values'][$key])) {
    $form_state['conf'][$key] = $form_state['values'][$key];
  }
}
}

/**
 * Run-time rendering of the content
 */
function MYMODULE_suggested_events_render($subtype, $conf, $args, $contexts) {

  if (isset($contexts['panelizer'])) {
    $nid = $contexts['panelizer']->data->nid;
  } else {
    return false;
  }

  // Grab the Category Term IDs from referenced node.
  $node = node_load($nid);
  $categoryField = field_get_items('node', $node, 'field_category');
  $categoryTIDs = array_column($categoryField, 'tid');

  // suggestedEvents are the events which are selected by the editor.
  $suggestedEventsField = field_get_items('node', $node, 'field_event_suggested');

  if (empty($suggestedEventsField)) {
    $suggestedEvents = array();
  } else {
    $suggestedEventsNIDs = array_column($suggestedEventsField, 'target_id');
    $suggestedEvents = entity_load('node', $suggestedEventsNIDs ); // @returns array of entities
  }

  // determine how many events we need to find
  // based upon the total to display and how many are site-editor-defined
  $relatedEvents = array();
  $relatedEventsCount = 0;
  if (count($suggestedEvents) < $conf['events_to_show']) {
    $relatedEventsCount = $conf['events_to_show'] - count($suggestedEvents);
  }

  if ($relatedEventsCount > 0) {
    // Query for other events that share the referenced categories.
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'event')
      ->propertyCondition('status', NODE_PUBLISHED)
      ->propertyCondition('nid', $nid, '<>')
      ->fieldCondition('field_category', 'tid', $categoryTIDs, 'IN')
      ->fieldCondition('field_datetime', 'value', date('Y-m-d').'00:00:00', '>=', 0)
      ->range(0, $relatedEventsCount)
      // Run the query as user 1.
      ->addMetaData('account', user_load(1));

    $result = $query->execute();
    if (isset($result['node'])) {
      $relatedEventsNIDs = array_keys($result['node']);
      $relatedEvents = entity_load('node', $relatedEventsNIDs);
    }
  }

  $events = array_merge($suggestedEvents, $relatedEvents);

  $block = new stdClass();
  $block->title = 'You may also enjoy...';
  $block->content = '';
  if (!empty($events)) {
    $block->content .= '
';
    $eventsRenderArray = entity_view('node', $events, 'showcase_card');
    $block->content .= render( $eventsRenderArray );
    $block->content .= '
';

    return $block;
  } else {
    return false;
  }

}

/**
 * Admin info.
 */
function MYMODULE_suggested_events_info($subtype, $conf, $contexts) {
if (!empty($conf)) {
  $block = new stdClass;
  $block->title = $conf['override_title'] ? $conf['override_title_text'] : '';
  $block->content = t('Show @events_to_show suggested events.', array(
    '@events_to_show' => $conf['events_to_show']
  ));

  return $block;
}
}


Where can I declare the compute field function? Computed fields have a computed_field_YOUR_FIELD_MACHINE_NAME_compute() function to compute the field value.

In Drupal in which module I use this?


How do you troubleshoot search tracking not working with the Google Analytics module? I have a site that uses the Google Analytics module. Analytics is working fine. However, I enabled search tracking in the module -- and updated the query string to search in GA -- but search data is not being tracked. After 72 hours I'm not seeing any search data.

I'm unsure how I can troubleshoot this. I reviewed the JS routine being output on the search page and verified the GA code is appearing, though I don't see anything specifically relating to search (not sure it would output anything different).

How do I go about troubleshooting this?

You could try the GA debug chrome extension for troubleshooting this issue. It will give you better insight into what is being sent to GA from Drupal


How to create a view mode preview within the display suite module I am using Display Suite to create two new view modes within my D7 instance. They are:

Wide
Square

I can get them created and and added to the content creation form BUT I'd like to create a preview image for those two view modes to give the end user some type of visual of what they're selecting.

I see there are layout previews when a layout is chosen but not for view modes. Do i just need to create a new layout template for the view mode? if so where should these files live?

First time using this module.

View modes are a Drupal concept, and layouts (in this context) are specific to Display Suite. Selecting a preview image for a view mode (if it can be done) has got nothing to do with Display Suite. The preview images that Display Suite show is specific to the layouts that it offers.

In Display Suite, you can define your own custom layouts, and there are a few ways of doing so. Some modules add layouts as well. To investigate how a module does that, download Display Suite Bootstrap Layouts and have a look at the files. You will see the module file, wherein the layout is declared as such:

$layouts['bootstrap_12'] = array(
    'label' => t('Bootstrap One Column: 12'),
    'path' => $onecol . '/bootstrap_12',
    'regions' => array(
      'central' => t('Content'),
    ),
    'form' => TRUE,
    'image' => TRUE, // this tells it that there is an image for the layout
  );

Note the key 'image' is set to TRUE to indicate the presence of an layout image, which you will find in the sub folders.

The template files that goes with this declaration is found in layouts -> onecol -> bootstrap_12 -> bootstrap-12.tpl.php and looks like this:

<<?php print $layout_wrapper; print $layout_attributes; ?> class="<?php print $classes; ?>">
  <?php if (isset($title_suffix['contextual_links'])): ?>
    <?php print render($title_suffix['contextual_links']); ?>
  <?php endif; ?>
  <div class="row">
    <<?php print $central_wrapper; ?> class="col-sm-12 <?php print $central_classes; ?>">
      <?php print $central; ?>
    </<?php print $central_wrapper; ?>>
  </div>
</<?php print $layout_wrapper ?>>

<!-- Needed to activate display suite support on forms -->
<?php if (!empty($drupal_render_children)): ?>
  <?php print $drupal_render_children ?>
<?php endif; ?>

Here you can see how the central region defined in the module file is rendered within the template using a naming convention.

You can add layouts to this module directly if you want by following the convention above. But better would be to define them in your own theme folder so that you don't wipe out your changes during an upgrade.

You can do that manually or using drush, and the layout files will live in a subfolder 'ds_layouts' within your theme folder. The process is fully described in Adding custom layouts to your theme. It is really very easy to do, and well worth the effort.

So to come back to your question, in order to associate a preview image with a view mode, you could declare a new layout with a peview image that is used only for a specific view mode, thereby creating a one-to-one relationship between them.


Editing Theme In Existing Drupal Site I work at a non-profit, and the person in charge of the website has left.  I have taught myself how to edit the website online through our web log in, but can't figure out how to edit the theme.  All I need to do is add a logo to the theme (we use the Zen subtheme).  Is this something I can even do online, or do I need to set up a server shell or server test site on my desktop?

Go to /admin/appearance/settings/YOUR_THEME_NAME and scroll to the bottom and find the logo field and upload your custom logo

See the following for a nice visual walkthrough.

http://www.inmotionhosting.com/support/edu/drupal-7/customize-theme/upload-custom-logo


How can I hide the active language in the language switcher block? I have a site with two languages, but it's pointless to show the name of the currently selected language in the language switcher block.  How can I hide it?

The links generated by the Language API are alterable via hook_language_switch_links_alter(), so you can do this:

/**
 * Implements hook_language_switch_links_alter().
 */
function MYMODULE_language_switch_links_alter(array &$links, $type, $path) {
  global $language;

  unset($links[$language->language]);
}


Whats faster db_query, db_select, or EntityFieldQuery So I'm trying to find out what is faster db_query, db_select, or EntityFieldQuery. Currently I'm using EntityFieldQuery. I'm grabbing about 1600 node entries.

I realize this can be taxing on the system so I just want to figure out which is the best option to grab 1600 nodes. Shaving off seconds or even milliseconds would matter a lot with the application I'm building.

Thanks in advance for your answers.

To answer your question in short, db_query is the fastest! Here are some reasons, facts and figure compiled from different questions, sources:

A simple googling of this question, come up with following results:

For simple queries, db_query() is 22% faster than db_select()
For simple queries, db_query() is 124% faster than EFQ
For queries with two joins, db_query() is 29% faster than db_select()

and this

db_query():

Total Incl. Wall Time (microsec):   796 microsecs
Total Incl. CPU (microsecs):    0 microsecs
Total Incl. MemUse (bytes): 123,352 bytes
Total Incl. PeakMemUse (bytes): 124,248 bytes
Number of Function Calls:   38

db_select()

Total Incl. Wall Time (microsec):   1,118 microsecs
Total Incl. CPU (microsecs):    0 microsecs
Total Incl. MemUse (bytes): 425,216 bytes
Total Incl. PeakMemUse (bytes): 436,392 bytes
Number of Function Calls:   88

If you notice above db_select makes more function calls and utilize more memory than db_query.

See here for reasons on why to use db_select
See here for reasons on why to use EntityFieldQuery over
db_select
See here for performance comparison of db_query and db_select

I guess the choice should be solely based on your requirements. EntityFieldQuery might be slower but, offers many advantages such as simple syntax, field storage is pluggable, loose coupling and many more.


Use relationship for Views taxonomy term filter I'm using the Commerce module, and I'm trying to create a view that displays the nodes with several exposed filters that should apply for the products.

Now, the node has a term field that references to a category. A normal taxonomy term filter works just fine for this case.

The products has a term field that references to a color.

What I would like to do is adding another taxonomy term filter for the color vocabulary (just like the one described above) that uses a relationship to the product. AFAIK, it's not possible to use a relationship for a taxonomy term filter.

Can I achieve what I am trying, in any way?

I'm using Drupal 7.2 and Views 3-beta3.

I've been able to do this with a simple "Content: Referenced product" relationship in my view. If you try using any of the "Content: xxxxx" filter fields, they won't work, as you're noting here. So, "Content: has taxonomy term ID," won't let you choose the relationship.
However, if you use the "Commerce Product: xxxx" (where xxxx is the term refrerence field) field for your contextual filter, it'll work with the relationship.


db_update query in custom installation profile gets ignored I am currenty working on a custom installation profile that enables modules, performs some db queries and so forth.

It also sets my default theme and admin_theme...

Nothing too special ;-)

I have 2 db_update queries as well, located in my .install file.

The first one works perfectly

// Enable the admin theme.
db_update('system')
->fields(array('status' => 1))
->condition('type', 'theme')
->condition('name', 'rubik')
->execute();

The second one gets 'ignored'

// Locate menus is right regions
db_update('block')
->fields(array('status' => 1, 'region' => 'sidebar_first'))
->condition('delta','menu-left-menu')
->condition('theme', 'mytheme')
->execute();

I have tried the last query with devel/php and then everything works perfectly.

What am i missing?

When i put the query in a .module file it works as well...

Thanks for any advice!

db_update it is a selectable object. It builds SQL queries. https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_update/7

Yes. Everything is in database. You can changes by queries. You should use api functions or common approaches.

Theme data is stored as variables, for Drupal it is enough.

variable_set('theme', 'my_theme');
variable_set('admin_theme', 'theme_name');

https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/variable_set/7
It says that if you want change it by queries you need update the variable table.

Also when you manipulate with cache-able objects(blocks here) you need clean cache.

cache_clear_all();


How to render an image at its original size? There are plenty of examples on the internet on how to render a styled image; for instance this one from web omelette:

$render = [
    '#theme' => 'image_style',
    '#style_name' => 'thumbnail',
    '#uri' => 'public://my-image.png',
    // optional parameters
];

However I do not want to use an image style. I want to render the original untouched image. So I tried:

$render = [
    '#theme' => 'image_style',
    '#style_name' => NULL,
    '#uri' => 'public://my-image.png',
    // optional parameters
];

Which did not work.
How do I render the original full-size image?

You can also use the #theme property image (which does not appear to be documented anywhere), but gives a valid image tag.

$render= [
  '#theme' => 'image',
  '#uri' => $file->getFileUri(),
];

Which becomes <img src="/sites/default/files/image.png" alt="" /> once rendered.


Is there a way to stop comment_node_view from firing? I need to use the Commentsblock module, but it is turning out to be pretty buggy.  I've got an issue in the queue with a patch for comments not displaying for anonymous users.

Now I've got a second issue posted about how paging is broken, but I'm stumped on how to fix it so wanted to see if anyone else had an idea.

Here is the issue: http://drupal.org/node/1513910

My question is: Is there a way to prevent the comment_node_view function from executing?

Or....should I be going about this an entirely different way (backup plan is to use Views to display comments in a block, but I can't think of a way to respect threading so would like to avoid that if possible).

You can implement hook_module_implements_alter() and stop the hook being run for the comment module:

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_view') {
    unset($implementations['comment']);
  }
}

Once you clear the cache comment_node_view() won't be called any more.


Set default image when file not found (404) I have many images but when one of them is missing it displays an empty <img>. Is there a method or hook that can be used to display a default image instead this empty <img> tag?

Install and configure ImageCache Defaults module.

  ImageCache Defaults detects file paths in broken images (404 errors) generated by ImageCache (D6) and Image (D7). ImageCache Defaults can either remove images with broken paths from your markup completely or replace them with a configurable default image.


Adding Calendar page to another page? I am using the Calendar module. I was asked if it was possible to take the calendar page and put it inside of another.
I'm not so sure about this.
How would I add this to be inside the Content region of the other page?
I see how it is possible to add the Calendar block to the Content region of the page but that is not what these people want...they want the full Calendar view inside of another page!
Any ideas how I would go about doing this?

This is the Calendar module installed in Drupal 6.

If I am understanding you correctly, all you should need to do is go into the View UI and click on the clone link of the existing calendar view and then enter the new path in the page display and appropriate date field to use.

ADDITION:

based upon your comment below, you could set a variable in a preprocess hook to the output of this view, eg:

$vars['cal']=views_embed_view('calendar','calendar_1');

and then you would have $cal inside your template to use however you wanted.  If you needed this information inside of a node, eg in a text field that would be displayed between those paragraphs of other text, you could probably hook into nodeapi() and set it there on display of the node.  If you need it embeddable inside a field amongst other text, that gets trickier, but doable with a custom filter of your own (or http://drupal.org/project/customfilter might be able to do it with their php filter but I've not used it personally) but then you'd have something along the lines of [calendar] that your users could have inside of a text field that would be transformed into the calendar view output on view.

Regardless of any of the above, I have no idea what CSS style issues you would have to fiddle with, if any, or what to do with the previous and next links of the calendar and if they would also work or not as expected on this new page.


Can there be content sent the a vanilla Drupal 8 sites' views that isn't a node? Is it possible to add content into views that is not searchable from google? I am trying to find out if the content sent to views has to be of a type node. (I think there are other modules for importing xml into views and such, but I am asking for just the vanilla views)

You don't import things into a View; you configure a View with certain criteria, and that basically runs a query against the database, the results of which are formatted and rendered according to the rest of the View config.

It's not restricted to nodes, many entity types and pseudo-entity types can be queried, as Views is very extensible.

You mention importing xml into views - in reality that happens by 2 separate processes - importing XML and creating content/entities from it, then setting up a View to display that content.

Don't think of a View as a container. It's essentially a sophisticated HTML report builder that knows how to get and format Drupal data.


Multilingual multisite problem after changing standard language We have a multisite and one site is multilingual with (i18n). It contains a lot of translated views (title and standard words like "more" being translated with Views translation (i18nviews)). This works very well as long as the standard language (atm german) is not changed. If we change to another language as standard the view translations are not working anymore, which means the new language gets mixed up with the old standard language on that specific view items.

Has someone else run into this? Where is the configuration setting to get this solved?

Thanks in advance.

Background for this is, that the client wanted another language as front page (so if there's a hint how to solve this in a multisite environment other than changing the standard language, be welcome. We have tried a bunch of htaccess redirects to no avail).

Here is a hint (as in your question), that might help: make sure the URL of the homepage is defined as a "multilingual" variable. The relative URL to display as the front page is specified within admin/config/system/site-information.

If you want to be able to specify a value for it that is different for each of the site's languages, make sure you have made it a "multilingual" variable (it should say "This is a multilingual variable." in the description of that variable on that page).

For more details about how to get this done, refer to my answer to "How to make content translation available for front page?".


How to create invisible widget in Drupal I need to create an auto-generated value for every user on my site. No one should be able to edit this field so it should not appear on the user edit form. Is there a better way to achive this than simply removing its edit field with hook_form_alter?

Install the Field Permissions module:

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

And the Computed Field module:

  Computed Field is a very powerful CCK field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it.

You can then create a field for your value, hide it from the registration/profile form, and use Computed Field to set its value to whatever you need it to be automatically.


Rendering a form to a block I have created a block named 'xyz'. I also created a form whose id is 'form-type-node-form' and i want this form to display in that block. How can i do this?
please help me to get solution.

You can achieve that in couple of ways. You can create custom module or simply by using on the modules mentioned below.

Advanced Form Block

  With this module you can do the following:

  1) Create any number of blocks with a particular node edit form.

  2) create any number of blocks with a particular node add form of a
  content type.

  3) Create as many blocks as you like of each kind.

  4) From the content type choose which fields to display on a per block
  basis.However required fields will be automatically displayed.

  5) All forms will be saved through ajax. So multiple node forms can be
  independently placed on a single page and worked with simultaneously.

OR

Form Block

  Enables the presentation of user registration, site wide contact, or node creation forms in blocks. This is particularly useful for including forms on panels.

OR

You can also achieve that by creating custom module. Follow this link


Put a field in views with the vocabulary of the taxonomy term from a contextual filter I have a view which accepts taxonomy terms as contextual filters.
Now, what I would like to have is to put the vocabulary of the term in a field. Relationships?...
On the nodes that arewhown by views there are two fields with taxonony terms, and the view can be sorted by both. I want to access the very one the view is filtered with.

Add a term relationship based on the term field.

Then add a taxonomy Vocabulary Name Field using that relationship.