How can I add a "Back to Search" link to user profiles? I have a view with exposed filters that allows users to search for other users on my site.  The view displays users' profile pictures, and clicking a profile picture takes one to the relevant user's profile (put together using Panels).

I'd like to display a "Back to search results" link on the user profile whenever someone clicks on the link (picture) in the view and visits the profile.  How might I go about doing this?

I'm using D7 with Panels and Views 3.

You can do this wih a new module modifying the user profile view.

// Implements hook_user_view().
function MY_MODULE_user_view($account, $view_mode, $langcode) {
  $account->content['link'] = array(
    '#weight' => -10,
    0 => array(
      '#markup' => 'Back to Search',
    ),
  );
}

Note: When adding a hook always remember to clear caches

If you also want to preserve the filter that the user has applied you can do so within your filter in the view by selecting 'remember the last selection' and selecting the roles that you want this for.


Drupal link inside bootstrap thumbnail I inserted this with a new created Text format

test

E-mail

but drupal outputs this when i save the content

Test

E-mail

I want that the div mail is inside the anchor thumbnail but drupal strips out the anchor automaticly out of the anchour thumbnail.

Can anybody tell me how i can fix that?

Nested <a> elements (anchor tags) are forbidden in HTML syntax.

Nested links are illegal by w3.org rules.


Drupal db_select join 3 fields I want join to my select three fc fields:

field_data_field_show_block_carousel
field_data_field_poster_film
field_data_field_film_link

I try this:

$nids = db_select('node', 'n');
  $nids->join(array('field_data_field_show_block_carousel', 'field_data_field_poster_film', 'field_data_field_film_link',), 'fc', 'n.nid = fc.entity_id');
  $nids->fields('fc', array('field_poster_film_fid','field_film_link_url',));
  $nids->fields('n', array('nid', 'title', 'uid',))
    ->condition('n.type', 'vodeo_library')
    ->condition('fc.field_show_block_carousel_value', 1)
    ->execute(); // returns an indexed array
  $result = $nids->execute()->fetchAllAssoc('nid');

but recived sql error? pls tell me what I do wrong?

You should try to write each join on a new line, not as an array. See Joins and public function SelectQuery::join.

So try it like this:

$nids = db_select('node', 'n');
  $nids->join('field_data_field_show_block_carousel', 'fc', 'n.nid = fc.entity_id');
  $nids->join('field_data_field_poster_film', 'fp', 'n.nid = fp.entity_id');
  $nids->join('field_data_field_film_link', 'fl', 'n.nid = fl.entity_id');
  $nids->fields('fp', array('field_poster_film_fid'));
  $nids->fields('fl', array('field_film_link_url'));
  $nids->fields('n', array('nid', 'title', 'uid',))
    ->condition('n.type', 'vodeo_library')
    ->condition('fc.field_show_block_carousel_value', 1)
    ->execute(); // returns an indexed array
  $result = $nids->execute()->fetchAllAssoc('nid');

Depending on what your module attempts to achieve, you might also want to have a look at the default Drupal functions for attaching fields to nodes (you only have a condition on one field):

field_attach_load()
field_get_items()
field_view_value()

You can get a rendered field value like this:

$node = node_load($nid);
$poster= field_get_items('node', $node, 'field_data_field_poster_film');
$output = field_view_value('node', $node, 'field_data_field_poster_film', $poster[0]);

And if you don't mind a little overhead, you might want to try an EntityFieldQuery. It will give you all fields and is a little slower then a regular SQL query, but is much easier to read and change.

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'vodeo_library')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_show_block_carousel_value', 'value', 1, '=');

$result = $query->execute();

if (isset($result['node'])) {
  $news_items_nids = array_keys($result['node']);
  $news_items = entity_load('node', $news_items_nids);
}


How to make a thumbnail slideshow when hover over album cover? Hi im thinking of making a gallery of photos.

On the front page Id like to display thumbnails of album covers for each collection.

What I want to achieve is when I hover over an image (Album cover) that image will turn into  a slideshow/ transition of images that are included in that album.

Whats the easiest and best approach to accomplish this?

Here are my suggestions. You will need to load both preview and  slideshow, and hide slideshow with css/jQuery. Then with jQuery show whole slideshow on hover.

Or, you could use jQuery load() or other jQuery ajax methods to load slideshow dinamically on-hover, If the page has lots of content.

In any case, you will need to include some custom jQuery scripts in your page.tpl.php (checking if $is_front is true, to include some javascript via drupal_add_js for example). This is type of approach i use.

For slideshows, you can use jQuery scripts (i use http://css-tricks.com/anythingslider-jquery-plugin/ and http://bxslider.com/ ).

If you are fond to php programming you can use content types and EntityFieldQuery to load elements in that slideshows.

If not, you could try and search for existing drupal modules to show slideshows like http://drupal.org/project/nivo_slider


Can't update core with composer: "Your requirements could not be resolved to an installable set of packages" I am not able to perform a security upgrade of Drupal core with composer.  I get "requirements could not be resolved."  Here is my composer.json:
https://pastebin.com/KxEQdPkt

Here is the response:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for symfony/psr-http-message-bridge v0.2 -> satisfiable by symfony/psr-http-message-bridge[v0.2].
    - drupal/core 8.3.2 requires symfony/psr-http-message-bridge ^1.0 -> satisfiable by symfony/psr-http-message-bridge[1.0.x-dev].
    - drupal/core 8.3.3 requires symfony/psr-http-message-bridge ^1.0 -> satisfiable by symfony/psr-http-message-bridge[1.0.x-dev].
    - drupal/core 8.3.x-dev requires symfony/psr-http-message-bridge ^1.0 -> satisfiable by symfony/psr-http-message-bridge[1.0.x-dev].
    - drupal/core 8.4.x-dev requires symfony/psr-http-message-bridge ^1.0 -> satisfiable by symfony/psr-http-message-bridge[1.0.x-dev].
    - Conclusion: don't install symfony/psr-http-message-bridge 1.0.x-dev
    - Installation request for drupal/core ^8.3.2 -> satisfiable by drupal/core[8.3.2, 8.3.3, 8.3.x-dev, 8.4.x-dev].

The solution in my case was to delete the vendor directory and delete composer.lock.

I am not totally sure I needed to delete the vendor directory, because I tried that first without deleting composer.lock, and it didn't work.  Deleting composer.lock was necessary.

I also changed the minimum-stability to "stable" before deleting vendor and composer.lock, but I doubt that was necessary.  In any case, I now have...

  "minimum-stability": "stable",


Are edited files in core modules overwritten on updating Drupal? I have searched related questions but could't really find a decisive YES or NO.

I changed a few files in core/modules/user/ ... to alter the display of the form used on my site. For example:

 $form['account']['name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Username'),
      '#maxlength' => USERNAME_MAX_LENGTH,
      '#description' => $this->t(''),
      '#required' => TRUE,
      '#attributes' => [
        'class' => ['username'],
        'placeholder' => $this->t('Username'),   // ADDED THIS
        'autocorrect' => 'off',
        'autocapitalize' => 'off',
        'spellcheck' => 'false',
      ],
      '#default_value' => (!$register ? $account->getAccountName() : ''),
      '#access' => ($register || ($user->id() == $account->id() && $user->hasPermission('change own username')) || $admin),
    ];

  Do these edited core files revert back to their original state thus deleting my changes when I update Drupal in the future?

YES, for sure. Clear enough ....?

PS: that's also why one should never hack core ...


Drush for Drupal 4.7 I'm trying to find a version of Drush that is compatible with Drupal 4.7. I know it's old and lame and long time ago deprecated but I really need it for a project I'm currently involved in.
I've tried to search it but without any luck.

Thanks,
Alex

You can find it in the last page of the releases for drush on drupal.org (right at the bottom, unsurprisingly).

As Greg mentions in the comments, Drush 1.x is a module so it needs to be put in the modules folder and enabled.


How to retrieve form entry for use as default value? I'm building a form in a custom module, and I'd like to have that form show as it's default value the value that had been saved to the DB during the previous edit, but I have no idea how to do it.

Here is an example of one of my fields:

$form['savings_ages']['savings_age21'] = array(
'#type' => 'textfield',
'#title' => t('21'),
'#size' => 10,
'#maxlength' => 10,
'#default_value' => $whatgoeshere?,
);

My form is the basis for a calculator, so I've got over 80 fields and only ever expect to have 1 row's worth of information in my table.

I have no idea how to pull that out, so any guidance would be welcome. PLease let me know if I need to provide more detail.

EDIT:
I'm still stuck on this, my normal query works when I test in the sql window of PHPmyadmin:

SELECT `factors_age21` FROM `savingfactors` WHERE 1 limit 1

but I can't seem to convert it to the correct format to work with db_query function and echo it out as the default value of my form field. PLus I'll still have to make this query 44 times (I have 44 columns) so if there is a more efficient way, I'd appreciate it.

Second Edit:
I'm starting to get a partial result, but it's still wrong.

$sql = "SELECT factors_age21 FROM {savingfactors} WHERE factors_age21 LIMIT 1";
$res = db_query($sql);
$item = db_fetch_object($res);

//later
$form['savings_factors']['factors_age21'] = array(
'#type' => 'textfield',
'#title' => t('21'),
'#size' => 10,
'#maxlength' => 10,
'#default_value' => print $item,
);

It IS producing a result, but it's showing me the number "1", when my correct value is "14"
any help is appreciated.

Thanks
Stephanie

$form['savings_ages']['savings_age21'] = array(
'#type' => 'textfield',
'#title' => t('21'),
'#size' => 10,
'#maxlength' => 10,
'#default_value' => $whatgoeshere?,
);

I guess $form['savings_ages'] is a fieldset. If so, then you can use the following code to get the default value that was saved in database during previous edit.

Explanation

When you save a form, a variable gets created with the id that you use to create form element. In your case variable_get('savings_age21', '') will fetch the previously saved value.

Documentation variable_get

Edit

$form['savings_ages']['savings_age21'] = array(
    '#type' => 'textfield',
    '#title' => t('21'),
    '#size' => 10,
    '#maxlength' => 10,
    '#default_value' => variable_get('savings_age21', ''),
);

return system_settings_form($form);

Sorry, I forgot about system_settings_form($form), this way when you save the form a variable with id of form element will get created, later you can retrieve it using variable_get().

If you do not wish to use system_settings_form($form), then you can use variable_set() to save a variable with any name. You have to do this variable_set() inside the submit handler of the form. Later while displaying the form, use the same logic variable_get() to retrieve the variable.


Transactions in Drupal 6 I am running drupal 6.22 with MySQL. There is no drupal 6 API for using transactions. Since I am new to drupal, I do not know which is the best way to use transactions using the existing drupal APIs? Can anyone guide me on this?

Transactions are done with SQL and in Drupal 6 you need to write all your SQL. So to use transactions, all you need to do, is to use db_query(SQL) and include transaction in the SQL you create.

This could look like this:

$sql = 'START TRANSACTION;
       SELECT @A:=SUM(salary) FROM table1 WHERE type=1;
       UPDATE table2 SET summary=@A WHERE type=1;
       COMMIT;';
db_query($sql);

Remember to use an engine that supports transactions like innodb.


Views: Filter by whether a node is ? Is there a way to filter a view by whether the item is set to <front>? Seems simple but it's not as easy as I'd have guessed.

You can solve above problem using Views PHP module.

  This module allows the admin account (user 1) to add fields, filters
  and sorts to views which use PHP code. It also supports additional
  accounts when the core PHP Filter module is enabled.

All you need to do is create a filter Global PHP and below code in the php filter. It's highly recommended that you include this within a module rather than directly in views. If it breaks it could be difficult to recover from.

function yourmodule_exclude_front($data) {
  if (!empty($data)) {
    $front_url = variable_get('site_frontpage');
    $url_parts = explode("/", $front_url);
    if (($url_parts[0] == 'node') && ($url_parts[1] == $data->nid)) {
     return TRUE; //Exclude the node
    }
  }
  return FALSE;
}

Then within your view php filter you would do something like:

 if (module_exists('yourmodule')) {
   return yourmodule_exclude_front($data);
 }

Exported view code below (not including module code from above, but inline code)

$view = new view();
$view->name = 'front_view_node';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Front View Node';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Front View Node';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'node';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Global: PHP */
$handler->display->display_options['filters']['php']['id'] = 'php';
$handler->display->display_options['filters']['php']['table'] = 'views';
$handler->display->display_options['filters']['php']['field'] = 'php';
$handler->display->display_options['filters']['php']['use_php_setup'] = 0;
$handler->display->display_options['filters']['php']['php_filter'] = '$front_url = variable_get(\'site_frontpage\');
$url_parts = explode("/", $front_url);
if ($url_parts[0] == \'node\' && $url_parts[1] == $data->nid) {
  return FALSE;
}
else {
  return TRUE;
}';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'front-view-node';


Problem with Unorganized content on page So I am not familiar with Drupal at all and need help. I am a graphic designer and trying to change the order of the layout on one of my pages. We had a developer design and organize our site but she screwed up the organization somehow.

How can I reorganize image on a page again? I tried going through Administrator > content > then I re-published the content in order but it did not work.

I've added an image so you can see my problem. Basically I'm having to manually drag the items in order but row weights but wanted to know if I can somehow organize them by title name and refresh the page to fix the problem. Any help is appreciated!

Since you tagged your question with "Views", I assume your screenprint is created via a view. And the view itself relates to some sort of entities like nodes, products, whatever.

If that's the case, decide about the "sort field" that you want to use in your view, and adapt it to fit your needs. If you cannot find any appropriate field that you want to use for such sorting, then just add an extra field (named something like sequence nr, and like an integer of say 4 digits). Then edit each of your entities to assign a relevant sequence nr, and use that as the sort field for your view.

BTW, this is true for pretty much any Drupal release.

PS: as per the "drag the item" in your question, it could well be that you're using the "DraggableViews" module to create such view.


Bootstrap dropdown parent link not clickable This is the first drupal project i'm working on and i'm having the following problem.
I have my dropdown menu set up as followed:

The problem is that the parent link "Materialen" is not clickable while the children are.
What should i change to be able to click the parent link?

A nice way that work with Drupal 8 would be to override in your subtheme:

menu--main.html.twig

And remove

 data-toggle="dropdown"

Cheers


Allow public to edit content type I have a content type that users can vote on so I need that content type to keep tally of the votes.

I'm assuming I need to allow the public to edit that content type but, unsure how to go about doing so.

I on the daily basis use web services on other projects and would just POST the data to the entry on click of a button or something. Is it a similar way just POST a change to the content type via ajax in drupal?

Sorry if this is a dumb question, majority of my skills are in front-end dev not server side so any help is appreciated.

I'm not sure I understand you correctly but let me clarify:
A.If you have a new content type that users can vote for that. You just use the votingapi http://drupal.org/project/votingapi and use with Fivestar module http://drupal.org/project/fivestar or plus1 module http://drupal.org/project/plus1. You will go to plus1 or fivestar for setting the content type that be voted.
B.To determine the total of the votes of your content type you should do following:

Create a new view and choose the type of your content, remove sort options, fields and other default settings.
Add a field for "Content: Type" Expand the "advanced" part on the right and set "Use aggregation" to "Yes"
Create the relationships with votes table("Content: Votes")
Add another field for "Content: Votes", click "Aggregation settings" and set the aggregation type to "count"
The second "Content: Votes" should now look like " COUNT(Votes: Value)"  and now you can see your content type and the total votes of that.

C. In order to anonymous users can edit your content type just go to permissions and set configuration for anonymous users.


Create a wrapper div within field groups on node displays For ease of formatting I would like to add an inner wrapper div inside of field groups displaying on content nodes and node forms. I'm using the Field Group module to display groups in div format.

Currently it's this:

…

Would like to output this:

 …

Try hook_field_group_build_pre_render_alter() since node content solution seems not longer working.

/**
 * Implements hook_field_group_build_pre_render_alter().
 * Adds additional wrappers
 */
function [your_theme_or_module_name]_field_group_build_pre_render_alter(&$element) {
  if (!empty($element['group_tabs'])) {
    $element['group_tabs']['#prefix'] = '
';
    $element['group_tabs']['#prefix'] .= '
';
    $element['group_tabs']['#suffix'] .= '

';
  }
}

Check Field group for developers for more info.


Simple news - Undefined Variable Error? I am getting this error after transferring my site to another host. Not sure why it broke so need some help troubleshooting.

It seems the block_html_id and the content itself is not coming through. I am using the standard block.tpl file
What could be wrong?

here is the code from simplenews-block.tpl.php

47:     <div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>

50:    <php if ($block->subject): ?>

56:       <?php print $content ?>

Here is all the code from the simplenews-block.tpl.php

<div id="<?php print $block_html_id; ?>" class="<?php print $classes; ?>"<?php print $attributes; ?>>

  <?php print render($title_prefix); ?>
<?php if ($block->subject): ?>
  <h2<?php print $title_attributes; ?>><?php print $block->subject ?>

<?php endif;?>
  <?php print render($title_suffix); ?>

  <div class="content"<?php print $content_attributes; ?>>
    <?php print $content ?>

I am thinking I need to delete the module and all tables related to it in the DB and start fresh...? What else is there to do?

This is the content of the template.php file.

Clear your cache completely. Disable your current them and enable a core theme like Garland. If the error goes away, you'll know it's with your theme.

If not:

Was the database fully migrated?
Were your files (and theme!) fully
migrated?
When you say "standard" block.tpl.php file, where did it
come from? It should have come from /modules/block/block.tpl.php.


How to override default page.tpl from a module, for a specific page? I am coding a module which contains a "please wait" page.

On this page I need to override the default page.tpl template so I can render the "please wait" message alone without all the other regions and "site chrome".

How do I tell drupal not to use the default page.tpl and use my page-special.tpl for the specific "please wait" page ?

EDIT

Please note that I am coding a module, not a theme. So everything should be done from inside the module.

As per Stuart Clark's advice

All you have to do is to create a template, for example : mymodule/theme/special-page.tpl.php

and add this to your module

function mymodule_theme(){
  return array(
    'special_page' =>  array(
      'template' => 'theme/special-page',
      'render element' => 'page'
    ),
  );
}

function mymodule_preprocess_page(&$variables, $hook) {
  if ( my_condition() ) {
    $variables['theme_hook_suggestions'][] = 'special_page';
  }
}


How enable Taxonomy to work with Basic Pages When I create an Article I choose an appropriate Tag from my Taxonomy List and save the article. When I click the tag after I save the article I get a list of articles with the same tag.

But how do you make a Basic Page work this way? I've researched Manage Fields and Manage Displays in admin-structure-types-manage and I CAN choose a tag and save it with the Basic Page...but I can't click on a tag on a Basic Page and get a list of all Basic Pages with the same tag.

Can you assist?

You probably have your field being displayed as Plain text. To display as links:

Go to your content type and Manage Displays
Find the Tags field and make sure the Format column has the Link value

Note that I'm assuming that you added the Tags field to your Basic Page content type and it's showing up in your page.


Date field in view Filter Criteria, where date may be blank I have a date field attached to a content type and it's not a required field. I want to use this date to control the display of the content using a view and it's filter criteria.

Some content may have blank dates and some may have a start and end date.

Is there a way I can set up the view to check for all of these conditions?

content is published
AND content type is TYPE
AND Start date is blank OR Start date is not blank AND start date is <= NOW
AND End date is blank OR End date is not blank AND end date >= NOW

The conditions I had set above were too many

content is published
AND content type is TYPE
AND Start date is blank OR Start date is not blank AND start date is <= NOW
AND End date is blank OR End date is not blank AND end date >= NOW

and should have been:

content is published
AND content type is TYPE
AND Start date is blank OR start date is <= NOW
AND End date is blank OR end date >= NOW

because the NOT blank is implied.

Using the 'And/Or, Rearrange' feature of the Filter Criteria, I was able to create 3 groups joined by AND's with Group 2 and 3 joined by OR's. Like so:


Add a module dependency to a sandboxed project I am developing  custom module which requires the use of the Entity Construction Kit (ECK) and the ECK Extend module. The problem is that the ECK Extend module is a sandboxed module.

I want to add the ECK Extend module as a dependency for my custom module.

How would one do this in the Drupal ecosystem? If I add the sandboxed module as a dependency, will drush recognise it and download it for me when I enable my custom module like drush would normally do with module dependencies?

I am afraid that is not possible.

One dirt-fix would be to add the following in your info file.

dependencies[] = sandbox/mihai_brb/2254845

This will make sure that users will not be able to enable this module by default and cause issues. And then you can add the instructions in your module page and README.txt you can add the instructions about the dependencies and how to download them and then remove the line from the info file.

A better approach would be to use hook_requirements and in phase = "install" you can check for the presence of a function that is present in the sandbox module. If that function is not present, you can block the module installation and show a message to the user to download the sandbox module and then try installing again.


How do I show the latest poll user hasn't voted on, yet? When an authenticated user has voted on a poll, I would like to show the next poll where the user hasn't voted on.

How should I implement that?

I think I figured it out. I copied the hook_block_info and _view from the poll module to my own module and modified the query a bit. It basically now takes any poll that a user hasn't voted on or hasn't voted on during this session.
I don't have voting for anonymous enabled.

function mycustom_block_info() {
  $blocks['recent']['info'] = t('Most recent poll not voted on');
  $blocks['recent']['properties']['administrative'] = TRUE;
  return $blocks;
}

function mycustom_block_view($delta = '') {
  if (user_access('access content')) {
    // Retrieve the latest poll.
    $select = db_select('node', 'n');
    $select->join('poll', 'p', 'p.nid = n.nid');
    $select->leftjoin('poll_vote', 'pv', 'pv.nid = n.nid');
    $select->fields('n', array('nid'))
      ->condition('n.status', 1)
      ->condition('p.active', 1)
      ->condition(db_or()->condition('pv.chid', NULL)->condition('pv.timestamp', REQUEST_TIME - $lifetime, '<'))
      ->orderBy('pv.chid', 'ASC')
      ->orderBy('n.created', 'DESC')
      ->range(0, 1)
      ->addTag('node_access');

    $record = $select->execute()->fetchObject();
    if ($record) {
      $poll = node_load($record->nid);
      if ($poll->nid) {
        $poll = poll_block_latest_poll_view($poll);
        $block['subject'] = t('Poll');
        $block['content'] = $poll->content;
        return $block;
      }
    }
  }
}


How are node IDs generated? How are node IDs generated?  Is there a field in the database, like "last node ID", that's incremented each time a new node is created?  What is the data type, and are there limitations, such as a maximum value?

{nid} is an auto_increment field in the table {node} - As all of the nodes are sourced from that one table it's able to keep its serialization. This is part of why UUID is such an important initiative in Drupal 8. It's not straightforward to maintain portability of content across environments for this reason.

The type is int(10) also known as unsigned so you're only limited by the data type limit of your preferred database and the disk space on your database server to store all those nodes. If it's MySQL that's 0 up to 4294967295.


How to select an address field city from dropdown list? I am using Address field module to populate address. A requirement needs to limit cities to a particular set, and also countries to particular set too. so I would like to present a set of cities in drop down list based on country selection. From the answer here I could figure out that something has to be done in plugins but I could not figure out what exactly. If anyone has sample code for city drop down in Address Field modules's plugins it would be of great help!

Consider using the Select (or other) module. Here is an excerpt about it from its project page.

  Provides a new Forms API element which is a select/radios/checkboxes element that has an 'other' option. When 'other' is selected a textfield appears for the user to provide a custom value.

So basically you could "start" from a few cities (City 1, City 2, City 3), and whenever somebody needs another one (not in the list yet), they just enter "City 4". Here is a sample about it (just replace "Option" by "City" to get the idea):


Get Webform Category Name in Preprocess I am trying to get the Category name (from the General form settings) for webforms in a preprocess function, ultimately to add as a class to the webform wrapper.

MYMODULE.module:

function MYMODULE_preprocess_webform(&$variables) {
  kint($variables);
}

Right now I don't see a "category" value in the array structure.

How do you get this value in preprocess? Maybe I need a different hook?

Not quite clear on the question actually. So you're saying you want to get the settings value from webform element "Category" list before it's submitted and set it as your form wrapper?

Here's some tip I recently learned, hope it helps.

// get all webform submissions id from my_webform
$query = \Drupal::entityQuery('webform_submission')->condition('webform_id', 'my_webform');
$result = $query->execute();

// load all submission data from webform submission storage
$webformStorage = \Drupal::entityTypeManager()->getStorage('webform_submission');
$submissions = $webformStorage->loadMultiple($result);

If you want to get the submission values form webform, then you can use WebformSubmission class.

If your want to get the element settings value that user sees from your category list, then you'll need Webform class to load the options array from the webform element.

use Drupal\webform\Entity\WebformSubmission;
use Drupal\webform\Entity\Webform;

// get sid from your preprocess or elsewhere
$webform_submission = WebformSubmission::load($sid);

// This will return the data array of submitted values from sid given.
$data = $webform_submission->getData();

// Load webform with bundle type id, normally it's your webform machine name
$webform = Webform::load($sid->bundle());

// Get element definition in webform element
$select_list_element = $webform->getElement('key_name');

// for options in Select list. this may vary depending on what element type you're using
$select_list = $select_list_element['#options'];


How to get Drupal 8 View to Accept Parameter as argument? I created a view that shows a bunch of cars. I allow you to filter by brand using an exposed block. If you filter, it results in a path like this:

/?brand=Volkswagen

I want brand to have the path:

/Volkswagen

instead.

How would one do this with Views? Or is this something that should rather be attempted with rewrite rules in htaccess?

You can do it with a contextual filter. In the "Configure contextual filter" menu select "Provide default value". For type choose Raw value from url.

There is more info on contextual filters in this article.

http://redcrackle.com/blog/adding-contextual-filter-view-drupal-8

If you are using taxonomies and want to use the name instead of id in the url you need to setup the relationships first and use name as the contextual filter.


How to change the system path of a taxonomy vocabulary to correspond a view I'm using Drupal 8 and i want different vocabularies to be displayed by different views.
Each view should have a different path with a contextual filter but when i define my path on pathauto the alias will be pointed to the system path.

I know there's modules that solve this like Taxonomy Display and Entity Path but because i'm using version 8 i really can't afford these modules.

Can you help me to change the default system path of each taxonomy vocabulary to correspond to a custom view?

Thank you for reading

I solved my problem installing the module: Taxonomy Views Integrator -  https://www.drupal.org/project/tvi.

It's easy to set a view to display both taxonomy terms and vocabularies.


How to use Rules to send an eMail with a body containing all items of a field collection? I've defined a content type that contains a field collection. The field collection contains 4 fields. When the content is created, it may have one or more of the field collections.

I set up a rule to send the email to users of a specific role.  I've used tokens in the rule to specify some data fields in the body. I'm currently stumbling on how to specify the one or more field collection fields in the body of the email.

I found some posts that indicated that I needed to add a condition for "node has field" which I have done. I wasn't sure what to select from the drop down lists, so, I took a logical guess. That seemed to provide some more tokens.

However, I've tried several different methods to specify the field collection in the body of the email, but, all have failed. The email is empty in the spot where I tried to display the field collection.

How can I specify the fields of a field collection in the body of an email?

Part 1: Custom Rule
Have a look at this rule (in Rules export format), which IMO is a possible answer to your question:
{ "rules_field_collection_msg_and_email_body" : {
    "LABEL" : "Field Collection msg and eMail body",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_details" } },
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "3" : "3" } }
        }
      }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : {
            "type" : "text",
            "value" : "\u003Ch2\u003EThis is a demo of a node containing a field collection ... \u003C\/h2\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EAbout this demo\u003C\/strong\u003E:\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\r\nThe machine name of the field collection is \u003Cstrong\u003Efield_article_details\u003C\/strong\u003E, and the number of values for it is unlimited.\u003Cbr \/\u003E\r\nThis field collection has these fields:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- a text field labeled \u003Cstrong\u003EAuthor\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_author\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a decimal field labeled \u003Cstrong\u003EPrice\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_price\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a boolean field labeled \u003Cstrong\u003EApproval required\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_approval_required\u003C\/strong\u003E.\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 1\u003C\/strong\u003E: The  list of items contained in the field collection with machine name \u003Cstrong\u003E\u0027field_article_details\u0027\u003C\/strong\u003E looks like so (note the comma to separate each item):\r\n\u003Chr \/\u003E\r\n[node:field_article_details]\r\n \u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 2\u003C\/strong\u003E: The result of a \u003Cstrong\u003ERules loop\u003C\/strong\u003E that iterates for each of the field collection items (using its unique ID) ...\r\n\u003Chr \/\u003E"
          },
          "PROVIDE" : { "variable_added" : { "variable_for_email_body" : "Variable to use in eMail body" } }
        }
      },
      { "drupal_message" : { "message" : "\u003Ch2\u003EThis is a demo of a node containing a field collection ... \u003C\/h2\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EAbout this demo\u003C\/strong\u003E:\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\r\nThe machine name of the field collection is \u003Cstrong\u003Efield_article_details\u003C\/strong\u003E, and the number of values for it is unlimited.\u003Cbr \/\u003E\r\nThis field collection has these fields:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- a text field labeled \u003Cstrong\u003EAuthor\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_author\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a decimal field labeled \u003Cstrong\u003EPrice\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_price\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a boolean field labeled \u003Cstrong\u003EApproval required\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_approval_required\u003C\/strong\u003E.\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 1\u003C\/strong\u003E: The list of items contained in the field collection with machine name \u003Cstrong\u003E\u0027field_article_details\u0027\u003C\/strong\u003E looks like so (note the comma to separate each item):\r\n\u003Chr \/\u003E\r\n[node:field_article_details]\r\n \u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 2\u003C\/strong\u003E: The result of a \u003Cstrong\u003ERules loop\u003C\/strong\u003E that iterates for each of the field collection items (using its unique ID) ...\r\n\u003Chr \/\u003E" } },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-article-details" ] },
          "ITEM" : { "article_details_item" : "article details item" },
          "DO" : [
            { "data_set" : {
                "data" : [ "variable-for-email-body" ],
                "value" : "[variable-for-email-body:value]\u003Cbr \/\u003E\r\nThe host entity of this field collection item: [article-details-item:host]\u003Cbr \/\u003E\r\nThe unique ID of the field collection item: [article-details-item:item-id]\u003Cbr \/\u003E\r\nField \u0022field_author\u0022: [article-details-item:field-author]\u003Cbr \/\u003E\r\nField \u0022field_price\u0022: [article-details-item:field-price]\u003Cbr \/\u003E\r\nField \u0022field_approval_required\u0022: [article-details-item:field-approval-required]\u003Cbr \/\u003E\r\n\u003Chr \/\u003E"
              }
            },
            { "drupal_message" : { "message" : "The host entity of this field collection item: [article-details-item:host]\u003Cbr \/\u003E\r\nThe unique ID of the field collection item: [article-details-item:item-id]\u003Cbr \/\u003E\r\nField \u0022field_author\u0022: [article-details-item:field-author]\u003Cbr \/\u003E\r\nField \u0022field_price\u0022: [article-details-item:field-price]\u003Cbr \/\u003E\r\nField \u0022field_approval_required\u0022: [article-details-item:field-approval-required]\u003Cbr \/\u003E\r\n\u003Chr \/\u003E" } }
          ]
        }
      },
      { "mail" : {
          "to" : [ "site:current-user:mail" ],
          "subject" : "Demo of an eMail with a body containing all items of a field collection",
          "message" : [ "variable-for-email-body" ],
          "language" : [ "" ]
        }
      }
    ]
  }
}

Some more details about what this rule does:
- Rules Event: Content is viewed (change to whatever fits).
- Rules Conditions:

Entity has field, for entity=node and field (machine name)= field_article_details (adapt this machine name to whatever fits).
User has role(s), for user=[site:current-user] and role administrator  (adapt this condition to whatever fits, or just delete it entirely, doesn't make any difference).

- Rules Actions (this is where the party starts ... pay attention!):

Add a variable (to use in eMail body later on ...), with machine name variable_for_email_body (adapt to whatever fits), and set an initial value which corresponds in the demo with everything from Part 1 and the header line from Part 2.

Show a message on the site, this is just for QA-testing, to see what's happening when the previous Rules Action is executed. It shows the equivalent of the initial value assigned to the variable_for_email_body variable from the previous step.

Add a Loop for list [node:field-article-details] (are you following, the field collection field!), and for list item use article_details_item. Within this loop, add these Rules Actions:

Set a data value, for variable [variable-for-email-body] (which we added as the very first Rules Action!), and with value (watch out, here comes the clue) ... something that looks like so (in each iteration of this Rules loop, we concatenate (append) the actual data for each field collection item to the end of the our [variable-for-email-body:value], and surround it with whatever other fixed text and/or HTML tags that we want to see in our eMail body):

[variable-for-email-body:value]

Host entity of this field collection item: [article-details-item:host]

Unique ID of the field collection item: [article-details-item:item-id]

Field "field_author": [article-details-item:field-author]

Field "field_price": [article-details-item:field-price]

Field "field_approval_required": [article-details-item:field-approval-required]

Show a message on the site, this is just for QA-testing (also), to see what's happening when the previous Rules Action is executed. It shows what got concatenated (appended) to the previous value assigned to the variable_for_email_body variable.

Send mail, which is extremely basic (after the work completed in the loop above ...):

To: [site:current-user:mail] (adapt to whatever fits)
Subject: Demo of an eMail with a body containing all items of a field collection (adapt to whatever fits)
Message: [variable-for-email-body] (adapt to whatever fits, either you add anything to the message body BEFORE or AFTER this message body here, or you adapt what gets moved as content of this variable in the previous Rules Actions Add a variable or Set a data value)

If you have the Rule UI enabled, you should be able to import the above rule in your own site, provided you first apply some of the changes I suggested, after you adapt the machine names to fit your names. After importing you may want to also change any of its events or conditions in it, or apply changes to any of its actions.
Part 2: Demonstration
Status message
This is a demo of a node containing a field collection ...
About this demo:

The machine name of the field collection is field_article_details, and the number of values for it is unlimited.
This field collection has these fields:

- a text field labeled Author with machine name field_author.
- a decimal field labeled Price with machine name field_price.
- a boolean field labeled Approval required with machine name field_approval_required.

Part 1: The list of items contained in the field collection with machine name 'field_article_details' looks like so (note the comma to separate each item):
Approval required:     No
Price:     12.45
Author:    Pierre Vriens
,
Approval required:     Yes
Price:     9.15
Author:    Barak Obama
,
Approval required:     No
Price:     3.40
Author:    Hillary Trump
,
Approval required:     Yes
Price:     1.23
Author:    Donald Clinton

Part 2: The result of a Rules loop that iterates for each of the field collection items (using its unique ID) ...
Host entity of this field collection item: 73
Unique ID of the field collection item: 1
Field "field_author": Pierre Vriens
Field "field_price": 12.45
Field "field_approval_required": No
Host entity of this field collection item: 73
Unique ID of the field collection item: 2
Field "field_author": Barak Obama
Field "field_price": 9.15
Field "field_approval_required": Yes
Host entity of this field collection item: 73
Unique ID of the field collection item: 3
Field "field_author": Hillary Trump
Field "field_price": 3.40
Field "field_approval_required": No
Host entity of this field collection item: 73
Unique ID of the field collection item: 4
Field "field_author": Donald Clinton
Field "field_price": 1.23
Field "field_approval_required": Yes

eMail body
This is how the entire content of the body of the delivered eMail looks like (look for "Part 2" in it to see the most interesting, I think, part of it):

-------- THIS IS A DEMO OF A NODE CONTAINING A FIELD COLLECTION ...----------

------------------------------------------------------------------------------
*About this demo*:
The machine name of the field collection is *field_article_details*, and the
number of values for it is unlimited.
This field collection has these fields:
- a text field labeled *Author* with machine name *field_author*.
- a decimal field labeled *Price* with machine name *field_price*.
- a boolean field labeled *Approval required* with machine name
*field_approval_required*.
------------------------------------------------------------------------------
*Part 1*: The  list of items contained in the field collection with machine
name *'field_article_details'* looks like so (note the comma to separate each
item):
------------------------------------------------------------------------------
-------- APPROVAL REQUIRED: ------------------------------------------------

No
-------- PRICE: ------------------------------------------------------------

12.45
-------- AUTHOR: -----------------------------------------------------------

Pierre Vriens
 * Delete [1]
 * Edit [2]

,
-------- APPROVAL REQUIRED: ------------------------------------------------

Yes
-------- PRICE: ------------------------------------------------------------

9.15
-------- AUTHOR: -----------------------------------------------------------

Barak Obama
 * Delete [3]
 * Edit [4]

,
-------- APPROVAL REQUIRED: ------------------------------------------------

No
-------- PRICE: ------------------------------------------------------------

3.40
-------- AUTHOR: -----------------------------------------------------------

Hillary Trump
 * Delete [5]
 * Edit [6]

,
-------- APPROVAL REQUIRED: ------------------------------------------------

Yes
-------- PRICE: ------------------------------------------------------------

1.23
-------- AUTHOR: -----------------------------------------------------------

Donald Clinton
 * Delete [7]
 * Edit [8]

 * Add [9]

------------------------------------------------------------------------------
*Part 2*: The result of a *Rules loop* that iterates for each of the field
collection items (using its unique ID) ...
------------------------------------------------------------------------------
Host entity of this field collection item: 73
Unique ID of the field collection item: 1
Field "field_author": Pierre Vriens
Field "field_price": 12.45
Field "field_approval_required": No
------------------------------------------------------------------------------
Host entity of this field collection item: 73
Unique ID of the field collection item: 2
Field "field_author": Barak Obama
Field "field_price": 9.15
Field "field_approval_required": Yes
------------------------------------------------------------------------------
Host entity of this field collection item: 73
Unique ID of the field collection item: 3
Field "field_author": Hillary Trump
Field "field_price": 3.40
Field "field_approval_required": No
------------------------------------------------------------------------------
Host entity of this field collection item: 73
Unique ID of the field collection item: 4
Field "field_author": Donald Clinton
Field "field_price": 1.23
Field "field_approval_required": Yes
------------------------------------------------------------------------------

[1]http://www.example.com/field-collection/field-article-details/1/delete?destination=node/73
[2]http://www.example.com/field-collection/field-article-details/1/edit?destination=node/73
[3]http://www.example.com/field-collection/field-article-details/2/delete?destination=node/73
[4]http://www.example.com/field-collection/field-article-details/2/edit?destination=node/73
[5]http://www.example.com/field-collection/field-article-details/3/delete?destination=node/73
[6]http://www.example.com/field-collection/field-article-details/3/edit?destination=node/73
[7]http://www.example.com/field-collection/field-article-details/4/delete?destination=node/73
[8]http://www.example.com/field-collection/field-article-details/4/edit?destination=node/73
[9]http://www.example.com/field-collection/field-article-details/add/node/73?destination=node/73

I know, the formatting of this eMail body is pretty (really?) poor, but watch what's below the line with "Part 2": everything you possibly may want to know about every item in your field collection, in the eMail body ... which is exactly what this question was about, no? So just reformat the eMail content to your liking (i.e delete everything in it you don't want, and improve the formatting of what you're really interested in).


How to modify the value of a taxonomy field of a node using hook_node_view()? I'm using Drupal 8 and I have a taxonomy field in a content type. I have created a node and added the term reference value to this node. Now the node shows up the link to the term.

I want to show value of the text field added in that taxonomy instead of link to the term.

I want to use this hook and set the value of the term field via code.

function hook_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) { }

You don't have to use the node view hook. It can be achieved using a taxonomy display as well.

Here is how to do it:

Navigate to "Administration / Structure / Display modes / View modes"
Scroll down to "Taxonomy term"
Add a new Taxonomy term view mode by clicking the according link and giving it a name
Now head to the display settings of your Taxonomy at "Administration / Structure / Taxonomy / [Your vocabulary] / Manage display"
Find the "Custom display settings" tab, tick your newly created view mode and save
A new tab with the name of your view mode will appear, where you can just add the field you like to display and disable all others; save again
Head to the manage display settings of your content type that features the entity reference field to this taxonomy at "Administration / Structure / Content types / [Your content type] / Manage display"
Find your entity reference field and switch "Format" to "Rendered entity"
Using the cogwheel at the very right, you can now choose your above created view mode for how to render the referenced taxonomy entity

Save and you have the rendered field of your taxonomy shown at the node page.

PS.: The above procedure can be used for many other referenced entities as well and does not require any custom programming.


How to show paragraph bundles of different types in a view of content containing paragraphs? I am using the Paragraphs module and I want to show the paragraphs of one type at the beginning of the view and the paragraph of a different type at the end. How do I distinguish paragraphs of different types (since the field name is the same)?

I see that they are doing it here but my view doesn't have those options :
https://www.drupal.org/node/2592021

ALSO I want to be able to insert this view of paragraphs into a view of the corresponding content. How can I do that?

You need to create a brand new view. Go to /admin/structure/views/add

For Show: select Paragraph Items

Once in the View, add fields, and you should be able to add Paragraphs item: [Name]

  but I want to see the content that has these paragraphs, not just the
  paragraphs

Then you will need to use Views Fields View to embed this view as a field in your other (node) view.

You will need to add a contextual filter of nid (to this paragraphs view).

Now in our other view (Node view) add views embed view as a field.

I think there is an option (checkbox) to automatically pass the contextual filter of your current node view to the embed view.

If not, simply add nid as a field in your node view, then when you add the view embed view field, use the replacement pattern of the nid as contextual filter.


Aegir tasks not running, after accidentally upgrading drush I have a BOA installation where I accidentally run the command drush self-update. This overrided the aegir-comparible drush with a newer version. When I realized the issue, two days later, I replaced the new drush with old one (4.6-dev), found in the backups.
The issue I am facing is that the tasks in the Aegir queue have stopped running. They give the message that they should run in the next cron, in about a minute, but then nothing happens. It keeps telling me that the last cron was run two days ago.

I have tried sudoing as Aegir and running the following:

drush vdel hosting_queue_cron_running -y
in case a semaphore is left, but this gives the message hosting_queue_cron_running not found.

/var/aegir/drush/drush.php '@hostmaster' hosting-dispatch --debug
and it runs fine, which means that the drush kicks the cron, but for some reason it doesn't reach Aegir

I tried to run barracuda up-stable in order to recover .drush, but it didn't recover it. I also tried to clean cache and rebuild registry. The time of the server is correct. Could you suggest some way to further debug the issue?

I found the solution. The problem occurred due to incomplete barracuda + octopus upgrade. One has to run the following commands to finish update

 barracuda up-stable
 octopus up-stable all


Specify language of Comment using Entity Translation? I'm building a site with multilingual support using Entity Translation. It is allowing authors to specify a language when creating a node, but there's no way to specify language when commenting on a node.

In Configuration > Entity translation, the Comment item is checked in the Translatable Entity Types section.

In Structure > Content Types > Post, I see tabs for Comment Fields, and Comment Display, but language is not one of the options.

I have been looking into the form_comment_form_alter hook, but so far have had no success with that.

In the Permissions panel, I confirmed that Administrator has "Translate entities of type Comment" checked. Even when editing a comment as admin, there is no option to translate.

The site uses Organic Groups 7.x-2.5, if that could influence this problem. The OG Post content type is the main one I'm trying to get fully functional.

Drupal natural way would be to show comments for different languages separately.

For example If you have a node in English and Spanish. Drupal natural way would be to show comments for en/es translation separately (attached to en/es content).

If you are looking for language field you can use Language field module...

  This module creates a Language Field that combines Drupal 7's Field
  list options and Internal language list.

  This is used to simply collect language data.


How to troubleshoot an Ajax HTTP Result Code 200 Error?` I am receiving the following Ajax error when on any Views page. The Drupal logs (/admin/reports/dblog) don't have any corresponding events. I've tried disabling all custom and view related modules and adjusting jQuery versions with no success.

I'm running Drupal 7.57-dev and Views 7.x-3.18

I know there are several other questions about this error but their solutions are specific or not relevant to this specific response text.

How do I begin drupal shooting this error?

The <?php tag at the beginning of the ResponseText indicates that there is a stray <?php in the markup, this was being caused by a syntax error in a completely unrelated template.
After template syntax error was fixed the Ajax Http 200 error pop-up went away.


Display date picker not inline in Drupal 7 Forms API I have installed Date Picker Module and it works fine.

Below is the code:

$form['date'] = array(
    '#title' => t('Select your birthdate'),
    '#type' => 'datepicker',
    '#date_format' => 'd/m/Y',
    '#date_year_range' => '-100:+0',
    '#default_value' => date("Y-m-d H:i:s", time()),
);

I want to display not it inline. I want it to be a textfield and when the focus is on the textfield, the calendar will pop-up. What configuration should I tweak to make it possible? Thanks.

Have you tried using DatePicker inline module?

From module page:

  This module permits inline rendering of date's popup widget. That is,
  it display the datepicker embedded in the page instead of in an
  overlay.

  It integrates with field API, form API and views exposed
  filters (via date_views).


Change Link URL in preprocess function I need to slightly modify some URLs that are in a "Link" field on a custom entity type.
In a mytheme_preprocess_myentity I've found that field with $variables['elements']['field_my_url'][0] I get this output in Kint

I've tried using a number of methods on the #url object but I don't think I'm doing it correctly... I'm just confused on how to modify it at this point.
How can I change the external URL to which this particular field is pointing?

Drupal's Core Url has a static fromUri() method (see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Url.php/function/Url%3A%3AfromUri/8.2.x)
With that in mind you should be able to swap out the ['#url'] with a new one thusly:
...['#url'] = \Drupal\Core\Url::fromUri('externalURL');


How to delete a content type, programmatically? I programmatically created a content type during a module installation (using field storage configuration).

I want to delete that content type while uninstalling the module.

Is there any way to do this with Drupal 8?

Just make sure that the node type depends on your your module, then Drupal will delete it automatically for you.

See node.type.book.yml in the book module for an example, this is the relevant part:

dependencies:
  enforced:
    module:
      - book

Note that users will have to delete all content of that type before they can uninstall the module then.


Multiple field Settings not appearing on an entity referenced field I have a content gallery with a multiple selection entity referenced field to a biblio content. I added the image field to the biblio. Created a view for the gallery, and I'm able to display all the images form the referenced entity.

But for the gallery to work, I need the first image to display only, and when user selects an image a popup appears.

What I'm missing is for the first image to appear only.when configuring the entity referenced field, the multiple field settings is not appearing. Is there another way to do the following or am I missing something?

You could create a relationship to the referenced entity and then add a filter where field_FIELD_NAME:delta = 0. Then either add fields that belong to the referenced entity using the relationship or add a "rendered entity" field using the relationship.


No Ajax gets initialised from inside the modal I've got a bunch of forms that are opening inside a modal so that the user is not redirected off the page. I've then got a few Ajax calls on form items inside the form. They all work when using the form in a page instead of a modal, however when in a modal it just gets an Ajax error.

The simplest Ajax functionality is the following:

function hook_form_alter(&$form, $form_state, $form_id) {
  $form['field_rate']['widget']['#ajax'] = array(
    'callback' => 'changeActualRate',
    'event' => 'change',
    'wrapper' => 'rates-wrapper'
  );
}

function changeActualRate(array &$form, FormStateInterface $form_state) {
  // Get rate from taxonomy term
  $rate = $form_state->getValue('field_rate');
  if (!empty($rate)) {
    // Instantiate an AjaxResponse Object to return.
    $ajax_response = new AjaxResponse();

    $rate = taxonomy_term_load($rate[0]['target_id']);
    $cost = $rate->get('field_cost')->getValue();
    $cost = $cost[0]['value'];
    $ajax_response->addCommand(new InvokeCommand('#edit-field-actual-rate-0-value', 'val' , array($cost)));

    // Return the AjaxResponse Object.
    return $ajax_response;
  }
}

It's a pretty simple bit of functionality but it seems no Ajax gets initialised from inside the modal. Anyone have any ideas on how to initialise Ajax once the modal is open. Modals are being opened via links using class="use-ajax" data-dialog-type="modal".

It could be that your behaviors aren't processing the newly added modal elements because of an internal JS error.

I determined this because that was the problem discussed in this D7 answer:

How to trigger Drupal.attachBehaviors after successful Ajax


How to get rid of the default field markup I need to customize registration form fields. Drupal generates form fields like this:

 Name
 <input type="text">

but I need to leave just <input> and be able to add some other tags around it.

For example:

Name<input type="text" />

It seems to be a common problem as the default html fields markup don't always what needs to be applied in particular html templates.

What is the best approach to this?

As with pretty much everything like this in Drupal, the answer lies in overriding theme functions/templates.

That markup is added by the theme_form_element() function; to override the output for that function simply add a function like this to your theme:

function THEMENAME_form_element($vars) {
  // ...
}

And change what you need to from the original function (e.g. replace <div> with <ul> if that's what you need). You might also need to override some of the individual element templates (depending on exactly what you want to do).

Some examples of those:

theme_textfield()
theme_select()
theme_checkbox()


Give permission to non-admin user to view and edit list of orders I am trying to create a role and assign it to a user who can view the admin orders list page and also edit the orders.

After adding all the permissions under the order sections in the permissions page, I was not able to access the list of the orders but was able to see the orders separately and edit them using the order number.

admin/commerce/orders page was accessible but the list was not showing.

Why is this happening? Is there any way fix this?
From the screenshot, you can see that I have given all the required permissions with respect to orders.

Any help is much appreciated.

After comparing the query being executed for the admin user and the non-admin user I found that 1=0 is being added to the commerce_orders view's query.

Further checking out the code, it seems that in the commerce.module file, the code expects either shipping or billing permission being granted to the user.

After adding one of them, the list was visible. I don't know why it's like this, List of orders must not expect that permission right?

TLDR; Adding the billing/shipping permission fixed the issue.


Exist any way to integrate Google Rich Snippets in D6? I have a dilemma with the topic of Google Rich Snippets in drupal 6.
Looking, no module to do so (Yes in Drupal 7, but work with drupal 6) and looking not find any solution. (I use Fivestar on my site)

So my dilemma is whether or, if it can implement this in Drupal 6 ... And that way you can do.

Someone to do? Someone could find a solution? I'm not as expert in Drupal but I want to know whether and in what way. It is urgent.

Thanks :D

Given the comments, I am thinking all you'd need to do is theme the fivestar summary with google's snippets.  To do that, I pulled the theme_fivestar_summary() out of the module and plopped it into my theme's template.php file like so:

function YOURTHEME_fivestar_summary($user_rating, $average_rating, $votes, $stars = 5, $feedback = TRUE) {
  $output = ''; // ADDITION #1
  $div_class = '';
  if (isset($user_rating)) {
    $div_class = isset($votes) ? 'user-count' : 'user';
    $user_stars = round(($user_rating * $stars) / 100, 1);
    $output .= ''. t('Your rating: !stars', array('!stars' => $user_rating ? $user_stars : t('None'))) .'';
  }
  if (isset($user_rating) && isset($average_rating)) {
    $output .= ' ';
  }
  if (isset($average_rating)) {
    $div_class = isset($votes) ? 'average-count' : 'average';
    $average_stars = round(($average_rating * $stars) / 100, 1);
    $output .= ''. t('Average: !stars', array('!stars' => $average_stars)) .''; // ADDITION #2
  }
  if (isset($user_rating) && isset($average_rating)) {
    $div_class = 'combo';
  }

  if (isset($votes) && !(isset($user_rating) || isset($average_rating))) {
    $output .= ' '. format_plural($votes, '@count vote', '@count votes') .''; // ADDITION #3
    $div_class = 'count';
  }
  elseif (isset($votes)) {
    $output .= ' ('. format_plural($votes, '@count vote', '@count votes') .')'; // ADDITION #4
  }

  if ($votes === 0) {
    $output = ''. t('No votes yet') .'';
  }

  $output = '
'. $output .'
';
  $output .= ''; // ADDITION #5
  return $output;
}

and commented where I added the snippet additions.


setup centos 7 enviorment I try to setup a Centos 7 enviorment in order to install Drupal 8.
I have followed a few tutorials like these ones:

http://orangeweb.com.au/installing-drupal-8-centos-7

http://www.linuxtechi.com/how-to-install-drupal-8-on-centos-7/

Every thing goes well until I try to install the drupal site.
when I try to install it, I get an error massage that Drupal requires a higher PHP version (5.5.9 or higher).

when i try to update the PHP version to 5.6 (according this tutorial). I still get the same error.

writing php -v on the terminal I see that the php version is now 5.6.
but when i upload a phpinfo(); file to the server I still see that the version is still 5.4.

why in the phpinfo I still see the 5.4 version?

It sounds to me like you are running more than one PHP version on the server.

Did you remove the current (old) PHP version before adding the new one? Did you restart apache/the server after installing?

You may need to tell Apache manually to use the new php56.

check your httpd.conf for the LoadModule definition that defines it and make sure it's referencing the correct PHP installation.

Centos 7 http.conf location: /etc/httpd/conf/httpd.conf

Note that any changes you make here require that you restart apache. Also note that changing here has a risk of bringing down apache, so modify with caution.


Unable to install modules with Drush I've got a fresh install of the Drupal 8 Beta 12. I'm trying to install the REST UI module:

$ drush dl restui-8.x-1.x-dev

PHP Fatal error:  Class 'Drupal\Core\Session\AccountInterface' not found in /var/www/html/drup/core/includes/bootstrap.inc on line 64
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: Class 'Drupal\Core\Session\AccountInterface' not found in
/var/www/html/drup/core/includes/bootstrap.inc, line 64

Does anyone know what's going on here?

Drush 6 does not support Drupal 8 and you need to upgrade to drush 7 (well I just upgraded to drush 8):

Drush Version   :  8.0-dev

See duplicate issue: Running Drush returns an error

Edit: If you are working on Drupal 8 you need the Drupal Console its syntax is a bit long-winded, but it is incredibly powerful.


htaccess multisite config crashed after sites move to other host I am on my long way to move my D6 site to other hosting company. It was hard but finally seems it's almost done but I am stacked on multisites configuration.
Situation is like this:

Drupal folder (from ftp/apache access point of view)

/webs/drupal/site  (main )
/webs/drupal/site/sites (multisites)

domains:

www.a.com
www.b.a.com

point to:

/webs/drupal/

/webs/drupal/.htaccess file

#redirect to */site
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www.)?b.a.com$
RewriteRule ^(/)?$ site [L]
RewriteCond %{HTTP_HOST} ^(www.)?a.com$
RewriteRule ^(/)?$ site [L]

/webs/drupal/site/.htaccess

it's standard D6 .htaccess with "always add 'www' prefix" rule on

The problem is that I can:

access default site using all combinations like www.a.com, a.com, a.com/site
access subsite like www.b.a.com/site

but all calls like:

www.b.a.com
b.a.com

redirects to the main site www.a.com/site ...

Any ideas?

It was a matter of the firefox cached data. After cleaning the cache it works.


Workaround for: Message rejected due to DMARC policy for yahoo.com Using Drupal 7 on CentOS 6 with stock Postfix 2.6.6 and since recently any mails sent by Drupal on behalf of users with @yahoo.com mail addresses are bounced hard:

Diagnostic-Code: smtp; 550 5.7.1 Message rejected due to DMARC policy for
    yahoo.com

And also:

Message not accepted for policy reasons.  See
    http://postmaster.yahoo.com/errors/postmaster-28.html (in reply to end of
    DATA command)

I think this is result of Yahoo changing its mail policy, so that all other big mail providers participating in DMARC (like Gmail or Mail.ru or ...) only accept @yahoo.com senders from Yahoo mail servers (and thus not from my little Drupal website).

Has anyone affected by this change found a good workaround on the Drupal site for this problem?

UPDATE:

My Postfix installation works well and is not the problem.

The problem with Yahoo users should be solved in Drupal hook for sending contact and registration mails. I think (from reading Yahoo docs) the "From" header there should be replaced by "Reply-To" or something similar.

Note: My question affects Drupal and has to be solved with Drupal means (which is why IMO it belongs in this SE-site).

You are correct in your update that:

This is a Drupal problem, in that the script must change how it sends emails.
What Drupal uses in the "from" field should actually be in the "reply-to" field.
This can be fixed using a hook. (Specifically, hook_mail_alter().)

If you don't want to write any code, I suggest you use the Contact Reply To module by rfay.

Alternatively, I wrote a more general-use module that I described here.

I use my solution on all of my sites and have not had any trouble yet.

Some of the other suggestions are incorrect, in that hook_mail() does not catch every email, and therefore is not appropriate, and you cannot use some of the other smtp solutions, because the "from" email address is not consistent (ie., it is provided by site visitors).


Allow anonymous users to subscribe to newsletter/mailing list My aim:
Client side: Have a block in the front page to allow any user (including anonymous users) to input their names and email addresses to subscribe the newsletter. Administration Side: being able to see the mailing list and send out newsletter to these emails.

What I have got:
I downloaded and enabled the follow modules: Mail System, Mime Mail, Mime Mail Action, Mime Mail CSS Compressor, Simplenews, SMTP Authentication.

I am using Drupal 7 with Bootstrap theme.

What I have done:
I have added a new simplenews block in the front page only, styled a little bit. In permission section, I ticked both ANONYMOUS USER and AUTHENTICATED USER for 'Subscribe to newsletters' option.

Problems:
I input my email and clicked the subscribe button in the block as a anonymous users, there is an error:

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

Followed by a notice:

  You will receive a confirmation e-mail shortly containing further instructions on how to complete your subscription.

The SMTP Authentication module doesn't work for my account because it said my php doesn't have ssl enabled, which I don't know how to do? I have enabled ssl module in my apache, but what shall I do next?

Also I then see no subscribers added when I log on as an administrator later.

Question:
How can get let anonymous subscribe to mailing list and how can I create newsletter? Any instructions on how to achieve this? Am I using the wrong modules?

Sounds like your site can not send e-mails for whatever reason.

The default newsletter settings require to confirm a subscription, you can disable that in the newsletter settings, optionally also only for testing until you've figured the e-mail problem out.

Unconfirmed subscriptions aren't displayed in the UI, that's why you can't see anything.

Instructions on how to use and configure Simplenews can be found in the README.txt and the online documentation.

Note: You're asking a lot of different questions, and your actual problem (sending e-mails being broken) has nothing to do with initial question (you might not have known that, so that's ok). Remember that you're supposed to accept a (single) answer as the correct one, how can you do that if you ask multiple, different questions?


Ignore "invalid" or incorrectly formatted Emails addresses (on Signup/User Import) I am importing a large set of users from a old CMS that has about 10k+ users that have no email or badly formatted emails.

I want to force this to import, but Drupal wants to validate the email string.

Is there anyway to temporarily disable this?

Better will assign some email (e.g. unknown_XXX@garbage.com, where XXX is row number of csv) to email of unassigned users. There's tonn of software that work with CSV.
After importing, you can run sql update command that will assign to emails '' value for that garbage email.

p.s. Also you can setup Rules module, that check if email equal to garbage email and warn him to change his email.


How to get url and description of FileFieldItemList's items in node template I have a content type called publication which results the node's twig template: node--publication.html.twig.
This content type contains a multiple file fields where the description is allowed.

I would like to share it with you, because it took a lot of time for me to find out how can I iterate through and render the items of a FileFieldItemList which would be a very easy thing without the drupal theming system.

Some of you might find useful it.

I am able to access the uri, and I can generate url from it by a Twig filter.

{{ content.field_document.0['#file'].uri.value|urlFromUri }}
{{ content.field_document.1['#file'].uri.value|urlFromUri }}
{{ content.field_document.2['#file'].uri.value|urlFromUri }}

and the description:

{{ content.field_document.0['#description'] }}
{{ content.field_document.1['#description'] }}
{{ content.field_document.2['#description'] }}

the Twig filter:

<?php

namespace Drupal\something_general\TwigExtension;

use Drupal\Core\Url;

class Custom extends \Twig_Extension
{

  /**
   * Generates a list of all Twig filters that this extension defines.
   */
  public function getFilters()
  {
    return [
      new \Twig_SimpleFilter('urlFromUri', array($this, 'UrlFromUri')),
    ];
  }

  /**
   * Gets a unique identifier for this Twig extension.
   */
  public function getName()
  {
    return 'custom.something_general.twig_extension';
  }

  /**
   * @param $uri
   */
  public static function UrlFromUri($uri)
  {
    $realpath = drupal_realpath($uri);
    $path = str_replace($_SERVER['DOCUMENT_ROOT'], '', $realpath);

    return $path;
  }

}

I am also able, to get the number of the items of the FileFieldItemList:

{% for index in 1..node.field_document.getValue|length %}
{% endfor %}

And finally the iteration in the node--publication.html.twig file:

{% for index in 1..node.field_document.getValue|length %}
  {% set document = content.field_document[ (index-1) ] %}

  {{ dump(document['#file'].uri.value|urlFromUri) }}
  {{ dump(document['#description']) }}

{% endfor %}


How to order multiple values in a field collection I have an Content type which includes a field of type Field collection, of which there can be an unlimited number of values. I can't work out how to order the rows of data that are displayed by this field.

You can order the Items when you are creating it using the widget that is next to the field. I mean this (It is a field collection that contains multiple fields)

and if you need to sort the items after adding the content, you can use  Field Collection views module. This module creates a view of type field collection and by some configurations you can get what you want.


Customize Ubercart checkout page CSS when certain products are in cart? On my Drupal 6 / Ubercart 2.9 cart website, I have the need to modify the CSS of the checkout page when a certain product is in the cart. For instance, if the customer is ordering red flowers, the background would change to a red flower background image. Is this possible via CSS? If not, any other ideas on how it can be done?

Thanks!

I have two ideas:

1) render the code of the article in the class attribute of the cart div. you can do that "intercepting" the render function in your template.php file.

2) using jquery


How do I maintain API versions? I have different REST End points in my Drupal 8 instance, some of them are exposed from REST Views and some are custom controllers. I have a situation where I want to maintain versioning with my end points.
I have replaced some fields in the new version and the users relying on the older API version must not be impacted by the change.
In the case of a controller, how can I manage different output for different API versions?
Also, in the case of REST Views, where the URL is directly exposed, how can new data be added to that?
For example, the /rest/taxonomy-list endpoint gives a certain set of terms as JSON output. In the new API version, I have to add/remove/replace one term which is present in same vocabulary.

One approach to version the API is to add a version number to the URL.
So, for example your Views REST display URL /rest/taxonomy-list would become /rest/v1/taxonomy-list or /rest/v2/taxonomy-list
You could duplicate the existing Views display to adjust the fields and new URL in a new REST display.
For custom REST API plugins, you can extend the existing RestResource and give it a new URL, e.g:
use Drupal\my_module\MyRestResource;

/**
 * Sample Rest Resource
 *
 * @RestResource(
 *   id = “my_rest_resource_v2”,
 *   label = @Translation(“My Rest Resource (v2)“),
 *   uri_paths = {
 *     "canonical" = "/api/rest/v2/endpoint”
 *   }
 * )
 */
class MyRestResourceV2 extends MyRestResource {

  // Extend and override functions here

}


Separate and display only particular parent term from a taxonomy vocabulary Is there a module or a way to separate and display only a particular parent term from a taxonomy name in Drupal 7 for the admin, while adding the content.

Consider the home page main menu with vocabulary Name.

The home page main menu has the following taxonomy terms.

Hello
----Red
----Green
----Blue
Test
----Orange
----Black
----Violet

Here in my case I have a content type called Article(for example);

While admin is creating an article, I need to display only the taxonomy term related to Hello. Right now it is displaying all the taxonomy terms related to Hello and Test. Is there a way to separate the parent terms from the same Vocabulary Name.

I think this is, what you searching for: Taxonomy Term Reference Tree Widget.

Here is a quote about it (from the module's project page):

  ... provides an expandable tree widget for the Taxonomy Term Reference field in Drupal 7. This widget is intended to serve as a replacement for Drupal's core Taxonomy Term Reference widget, which is a flat list of radio buttons or checkboxes and not necessarily fit for medium to large taxonomy trees.


Print Preprocessed username Field Value in User Template $account->getDisplayName() Bypasses "username" Field Preprocessing in User Template?

I am trying to print the value of the username field of the user account in a user--custom.html.twig file.

MYMODULE.module:

function hook_preprocess_user(&$variables) {
  $account = $variables['elements']['#user'];
  $variables['userName'] = $account->getDisplayName();
}

user--custom.html.twig:

{{ user.name.0.value }}

Both the above examples access the username, but seem to access the value directly and circumvent any preprocessing of the username field (e.g. hook_preprocess_username()), so it looks like I need a different approach.

I have a view that shows the "User" entity so does not use fields and relies on the user template. What am I missing when trying to get the processed value of the username field, instead of the user name DB value for the account?

Related: Get username in custom user twig template but different.

In my template, I am rendering content.user_picture and trying to render username. So maybe I need to load the user instead of both fields? Looking for the processed username field value.

You're probably looking for the username theme:

$variables['userName'] = [
  '#theme' => 'username',
  '#account' => $account,
];


Dynamically assign user roles I have an application using domain access and am looking to reuse a set of subscriber roles across domains, assigning them on login.

I was hoping to use hook_user_load to add the additional roles.

I have some code like this:

/**
 * Implements hook_user_load()
 *
 * Dynamically assign configured roles based on active domain and subscription
 */
function EXAMPLE_user_load($users) {

  // Process each account once per request
  $processed_uids = &drupal_static(__FUNCTION__, array());
  // Get defined roles
  $roles = user_roles(TRUE);

  // Process accounts
  foreach ($users as $uid => $account) {
    $grant_rids = array();
    if(!in_array($uid, $processed_uids)){
      // Code to get grant role ids here...
      // ...
      // ...
      // Grant subscriber roles
      if(!empty($grant_rids)){
        foreach($grant_rids as $rid){
          // Matching role exists and not already assigned
          if(!empty($roles[$rid]) && !array_key_exists($rid, $users[$uid]->roles)){
            $users[$uid]->roles[$rid] = $roles[$rid];
          }
        }
      }
      $processed_uids[] = $uid;
    }
  }
}

Using this approach, the roles do get added, and I can see them in the $users array after processing.

However the user logging in, despite running through hook_user_load doesn't appear to have those roles "set" ( i.e aren't authenticated as having that role )

Maybe some kind of cache issue?

Does anyone have any ideas about what needs changing above or how to assign user roles dynamically as the user logs in, or as the user is loaded?

UPDATE:

Well, it turns out, you can actually alter user roles in hook_user_load.

My issue was caused by a ctools bug I discovered in my debug travels whereby the current logged in user context didn't fully load the user entity, and thus the access checks for the Panel page access were failing. It also needed a drupal_static_reset('user_access') to reset the static user_access permission check cache. Patch posted here http://drupal.org/node/2010124

After that, the dynamic role assignment appears to be working fine.

UPDATE 2

I wrote too soon, still having problems...

Will update when resolved.

UPDATE 3

OK, the remaining issues were related to ctools context caching.
I ended up writing my own ctools access plugin to ensure the logged in user context is checked uncached on each access request. After that, all appears well again.

You can try user_multiple_role_edit, something like this might help.

  $user_id = $user->uid;
  // user the role human name
  $role_name = 'My Awesome Role';
  if (user_role_load_by_name($role_name)) {
    // No need to check if the role is already granted
    user_multiple_role_edit(array($user_id), 'add_role', $role->rid);
  }


How to theme a view block I'm a drupal beginner. I'm using drupal 7 and views. I created a block using views in order to list my latest projects. I'm displaying the block in my home page. I would like to know how to override HTML and Css in order to display something like this:

I want to use this code:

Projects One

                                On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire

                            more details

Open the view which you've created, expand Advanced Option column
open Theme:Information
copy the last theme suggestion from Row style output row
go ahead to the theme(project theme) folder and create that file,
example, views-view-fields--docs---page-1.tpl.php (this is how my
template looks like, this is just for an example), rescan the templates, and save the view.
debug $fields array (better install Devel module, it provides useful functions, like dpm(), dsm()..)
Copy the code from the sample template and put into this template.
Lastly, put the output of fields (e.g. something like this <?php print $fields['SOME_FIELD']->content; ?>) to the desired html blocks..

Don't forget to clear the cache;


How to use Token Replace only if the field has a value? So I've been using token replace for a while now with great success in my themes.  For instance I'm using it currently to show the real name of an author by using

<?php print token_replace('[node:author:url]', array('node' => $node)); ?>">

The issue is that I've recently added a byline field in my storys and not all stories have a byline.  I've added it normally by using

<?php print token_replace('[node:field_byline]', array('node' => $node)); ?>

However when the field is empty it simply prints [node:field_byline] so I get stories like...

By: [node:field_byline]

Is there a way to check that the token field has something in it and only show that field if there's a value?  I'd like to just show nothing if there are now authors for the byline.  I tried using something like:

<? !empty [node:field_byline] ?>

but this hasnt worked.  Ideas?

You can use the 'clear' option of token_replace to clear any tokens it can't find a replacement for.

<?php print token_replace('[node:author:url]', array('node' => $node), array('clear' => TRUE,); ?>">

As documented here: https://api.drupal.org/api/drupal/includes%21token.inc/function/token_replace/7.x


How disable view page functionality and revert to pure view with master display? On view setting page

I have view with menu link and path. I want to turn it off, revert to basic view master. I've try to remove menu, but didn't change anything. Then I try to remove path but is mandatory. Clone view make same view with page path.
Only solution I can see is create new view and repeat settings (I don't want to do that!), another is to just change path to some useless one so it dons't conflict with my menu links (paths). Any ideas?

While creating a view uncheck Create a page checkbox and check create a block checkbox;

If you already have created a View, you can add new display as shown in figure below:


Create proof of purchase codes I've made an Ubercart store for our schoolwear. We can't do online purchasing because we're not set up for it.

What happens right now is that when someone buys something from the catalog, they have to go to the office to pay for it. Then, the receipts get sent to the class running the store as proof the order has been paid for.

Here's what I'd like to do with our ubercart:

I create random codes somehow for proof of purchase in the ubercart system. Print them out, and give to the office.
Customer pays at the office for their item (e.g. a sweatshirt) and receives a random code from the office after purchase.
Customer goes to the online catalog and places their order (e.g. sweatshirt size, color, etc).
Customer goes to cart checkout and cannot complete checkout until they type in the random code they got from the office.
The class running the store gets the order through ubercart, and sees the random code as proof that the order has been paid.

I know it's a dumb system, but it's all we have. Is there a way to generate these random codes and have the customer put theirs in at the checkout?

You can create a new node type "vouchers" and use UUID module to add uuids to these nodes. When the office creates a new voucher it will automatically be assigned a uuid which you can then use as your code to give the student.

When the student shows the store their code the store can lookup that voucher in a Vouchers view using the uuid filter. Then the store can mark the voucher with a boolean "Used" custom field to show they are redeemed.


Import RSS Feed to a specific taxonomy term I want to use Feeds (and maybe Feeds Tamper??) to import some RSS feeds.

I want to add a taxonomy to my feeds.

Example : Yahoo Business RSS is tagged with "Business" taxonomy term.
Yahoo News RSS is tagged with "News" taxonomy term.
Reuters News RSS is tagged with "news" taxonomy term.
etc...

How can I add a taxonomy term to my feed import form ?

Thank you,

To use the feeds module you should have a content type set up in which you'll import these items.  I believe the tutorial is just saying that you should set up this new vocabulary and then add a term reference to it in your new content type.

In Drupal 7, to make sure you can set up your vocabulary, verify the following

When you go to /admin/modules on your site, is the Taxonomy module enabled?  If not, check it and save the page
Once that's done, you should be able to go to admin/structure/taxonomy to add your new vocabulary.

Don't forget that you should then add a term_reference field in your content type, so you can tag it with those new terms...

Hope that makes sense!  Let us know if it worked.


How to map Feed Importer with my content type? Here's my problem:

I'm using the "Feeds" module to import data from different RSS feeds. One of the feeds is:

http://www.happynews.com/rss/.aspx

As you can see, one of the elements is the "link" of each article.

How do I map that link with my content type? (note it's NOT the feed's link)

I've updated my content type "Feed item", adding a new text field to it called "Article link", attached it to the importer item and definitely can see the new field in the "target" options, however, it seems that in the "source" options there is no link field.

Is there a way to add "source" options to map them up with our targets?

Big thanks in advance for any help! I really appreciate it.

So far I found this article that might help to my problem above:

http://www.zivtech.com/blog/feed-feeds-importing-referenced-rss-data#comment-1378

How do I map that link with my content type? (note it's NOT the feed's link)

You're right your feed link is NOT a feed link. The URL is simply incorrect and this issue has nothing to do with Feeds module.

http://www.happynews.com/rss/.aspx returns 404 but when you dig a little you can quickly find that http://www.happynews.com/rss/ returns directories and other resources containing XML feeds.

For example https://www.happynews.com/rss/environment.aspx is a correct RSS channel titled "HappyNews - Environment" where you can see <item> XML nodes and each nested <title><description><link><pubDate> data.

To import such single channel you need:

create importer with HTTP Fetcher
and as a parser check Common syndication parser option
in fetcher settings you should provide RSS source channel link, so in Automatically add scheme input simply paste link to the channel you want to import like https://www.happynews.com/rss/environment.aspx
if right address is given Feeds fetcher will be able to"recognize" the scheme and all accessible fields should be visible on mapping tab in "Select a source" select field.

After all steps inluding RSS -> node fields mapping definitions you will be able to import data periodically (when CRON configured) or manually by running http://you-site-address/import

You can also attach importer to specific content type, this way source is imported by creating a node of that content type.
  .


How to avoid showing duplicate content in Views? I have a View block that displays all of the nodes written by an author on their profile. However, I'm having trouble with Views spitting out duplicate content.

For styling and functionality purposes, all of the fields are being outputted through an extra title field. I simply rewrote the output of the added title field, including tokens for all of my fields. I then set all of the fields (except for the rewritten title field) to "Display None", so that the fields were not duplicated.

Below is a screenshot of my current Views setup.

Here is a screenshot of the Views grid on the user profile. Ignore the missing images. I don't have all of the websites images synced to my local environment.

I tried using the "Distinct" option in the query settings, which eliminated most of the duplicates. However, Views continues to duplicate random content. Some content will have no duplicates, some content has multiple duplicates.

I've also tried using aggregation, but Views will not output anything when I turn aggregation on. I'd love for aggregation to be the solution, but I can't figure out how to get it to work.

I have came across this question in past looks like it is same as your Question: Filtered View gives duplicates

Referring that, I came to know you can use Views Distinct.

And you can follow this video tutorial: How To Remove Views Duplicates (Drupal Tutorial).


Combine two or more filter criteria in views I want to combine two or more filter criteria to a dropdown in views filter criteria. so that i can select a filter criteria in the dropdown box and can search with a string in a text box. so that the result will be similar to the string from the filter criteria which is selected from the dropdown listbox(combination of filter criterias).

Is there any way to combine the filter criteria as dropdown...?

I Found this problem interesting and spend little time over this. Here is the solution i come with.

Create a view with title and Body field.
Add two filters Content:Title and Content:Body with Contains operator, expose these two filters.
Create a custom module with the following hooks.

//custom.module
function custom_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {

if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'VIEW_NAME') {

    // Unset the title and body filter info so that it doesn't print any label.
    unset($form['#info']['filter-title']);
    unset($form['#info']['filter-body_value']);
    // Unset the title and body filter
    unset($form['title']);
    unset($form['body_value']);

    $form_element = array();
    $options = array(
    // '' => '-Select-',
      'title' => 'Title',
      'body' => 'Body',
    );
    $form_element['search_within'] = array(
      '#type' => 'select',
      '#title' => t('Search within'),
      '#options' => $options,
      '#default_value' => !empty($form_state['search_within']) ? $form_state['search_within'] : '',
      '#description' => t('Set the Title or Body within which you want to search.'),
      '#prefix' => '
',
      '#suffix' => '
',
    );
    $form_element['search_box'] = array(
      '#type' => 'textfield',
      '#title' => t('Search term'),
      '#default_value' => !empty($form_state['search_box']) ? $form_state['search_box'] : '',
      '#description' => t('Enter the term which you want to search.'),
      '#prefix' => '
',
      '#suffix' => '
',
    );
    $form = $form_element + $form;
}
}

function custom_views_query_alter(&$view, &$query) {
if ($view->name == 'VIEWS_NAME') {
    if (!empty($view->exposed_input['search_box']) && $view->exposed_input['search_within'] == 'title') {
    // Add title filter condition if title is selected
        $query->where[1]['conditions'][] = array(
          'field' => 'node.title',
          'value' => '%' . $view->exposed_input['search_box'] . '%',
          'operator' => 'LIKE',
          );
    }
    if (!empty($view->exposed_input['search_box']) && $view->exposed_input['search_within'] == 'body') {
    // Create join with fiedl_data_body table.
    // source:
    // https://api.drupal.org/api/views/includes!handlers.inc/function/views_join%3a%3aconstruct/
    // https://www.drupal.org/node/2049051#comment-7784967
        $join = new views_join;
        $extra = array();
        $extra[] = array(
          'table' => 'field_data_body',
          'field' => 'entity_type',
          'value' => 'node',
          'operator' => '=',
          );
        $extra[] = array(
          'table' => 'field_data_body',
          'field' => 'deleted',
          'value' => '0',
          'operator' => '=',
          );
        $join->construct('field_data_body', 'node', 'nid', 'entity_id', $extra);
    // Add join to query; 'node' is the left table name
        $view->query->add_relationship('field_data_body',$join,'node');
    // Add fields from table (or where clause, or whatever)
        $view->query->add_field('field_data_body','entity_id');
    // Add body filter condition if body is selected
        $query->where[1]['conditions'][] = array(
          'field' => 'field_data_body.body_value',
          'value' => '%' . $view->exposed_input['search_box'] . '%',
          'operator' => 'LIKE',
          );
    }
}
}

Note: This solution will only work with Contains operator and very case specific. It would be great if somebody will create a generic views filter handler to combine exposed filter as select list and allow search within selected filter.


Export the default system email text to code? Is it possible to move the default system email message text found in the account settings page out of the database and into the code for version control?

Currently using the mimemail module since we use HTML/CSS formatted emails.

Settings in files for version control was one of the biggest changes in the 7 -> 8 jump. Drupal 7 has no built-in way to do it. You may wish to see How to version control data stored in mysql.

If you want Drupal-specific tool, investigate Configuration Management module:

  The configuration management module enables the ability to keep track of specific configurations on a Drupal site, provides the ability to move these configurations between different environments (local, dev, qa, prod), and also move configurations between completely different sites (migrate configurations) without the use of modules with all configuration being owned by the site.