How to add a view inside a view? I have 2 groups of blocks in a view, I would like to join both of them in one view, showing the first block (I have the groups all linked one to the other).
I did download Views Field View but I can not manage the way to get it work, joining these 2 views.

The module 'Views Field View' that you have mentioned is very good imo. In order to use it, you have to edit a view A and add another existing view B as a field of view A.

But this is as far as it gets, it does not facilitate a 'joining' of views of any sort, for that matter I think it would be better for you to rebuild a new view with relationships etc, if Views Field View is not adequate for you.


using User Import module with date I was planning on using the user module to import more than 300 new users into my website. However, the birth date fields cannot be imported. Even before the actual import has started, I get these errors and warnings.

Warning: Creating default object from empty value in _user_import_settings_save()
(line 574 of /sites/mywebsite.nl/dev/sites/all/modules/user_import/user_import.module).

Field Birthdate is not supported

Apparently the User Import module can't handle date fields. Can this be solved with the User Import module? Or is there another module that I can use to import my users? Or do I have to php this manually?

thanks in advance

You can use feeds module to import User. It can handle external fields also.
For more information go through the module documentation.


Embedding Storify posts I help manage a site with about 20-30 staff/trusted users and thousands more regular authenticated users. We would like to be able to allow our staff to embed Storify entries in their blog posts without exposing ourselves to undue risk.

We have Media, with add-on modules for YouTube and Vimeo embeds, but there is no Media: Storify module. We tried Media: oEmbed paired with the third-party Embedly service which can provide a Storify post in oEmbed format. However we could not get this to work. Possibly because of this bug.

We also tried the StoryPal module, but it doesn't seem well maintained and produces a WSOD. We are apparently not alone with this problem either.

Has anyone found a good solution for Storify embeds or maybe know how to get the above solutions to work? Thanks for all advice!

Perhaps the lack of activity is an indicator of the obscurity of my problem, but Storify is a very popular tool so I imagine someone else might also have this issue. Here is how I solved it, thanks to a couple of colleagues helping me think creatively about this. Unfortunately my solution only works for one tool, but it could be made to work for any service with a consistent embed code.

Make a new field called Storify slug that contains the URL of the storify after storify.com/.
Add the embed code to the field's template. Below is field--field-storify-slug.tpl.php

<?php foreach ($items as $delta => $item): ?>
  <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>>

    <iframe allowtransparency="true" frameborder="no" height="750" src="//storify.com/<?php print render($item); ?>/embed?header=false&amp;border=false" width="100%">

    [<a href="//storify.com/<?php print render($item); ?>" target="_blank">View on Storify]

<?php endforeach; ?>

I added the storify-story ID to deal with some bad behavior where the Storify script was rewriting the DIV it was in and adding clear: left; as in inline style.


Custom module and template.tpl.php files I am just getting started with custom modules for my test site on my localhost. Is there a simple demonstration online where there is an example of using a mymodule.tpl.php files to render my content?

At the moment I have create a hook_menu() function also a function for the page call, all it does is return some text.

There are a lot of examples of use of the Drupal API for module developers in the Drupal documentation. In particular, you may find the Examples for Developers module handy, especially the "theming_example" sub-module. This is not an actually functional module, but just a container for a lot of example code that new developers can test, manipulate and learn from.


How to customize the url of a field in views? I have a view that displays product images using a jcarousel. In the view, I have a jCarousel format and it displays fields. In the Fields section, I'm displaying Content: Image. I want to link the image to a specific url. I can modify it using Rewrite Results and selecting Output this field as a link.

According to the answer I got from how to make a field in a view be the link destination to another field? & http://64sqft.danapellerin.com/2011/06/07/drupal-custom-cck-field-tokens-in-views. Views takes into consideration the order in which your fields are in the view. The taxonomy field that you want to use as a token needs to be reordered above the field you want to use the token in the url.

Things I've tried:

I tried content:category (which is my taxonomy field), and hid it so it wouldn't display. In the field's replacement patterns it gave me [taxonomy_catalog] & [taxonomy_catalog-tid]. I tried [taxonomy_catalog] but the replacement gave me the text from taxonomy description.
I tried Content: All taxonomy terms, but it gave me the name of the term instead of the ID.

How can I modify the rewrite to include the taxonomy term id associated with the node?

The problem was the way that Content: All taxonomy terms required a rewrite to [term_node_tid-tid]. Otherwise it would display the term name instead of the tid.


Passing values to a view block I have a page that contains 4 separate blocks, from the same view,

Items block 1 - this contains a list of item titles
Items block 2 - this contains a different list of item titles
Content block 3 contains content unrelated to this functionality
Results block 4 - this needs to display the details of the items that are highlighted in the above 2 sections after the user selects 'Next' in list 2.

I've found some information about passing variables to a view using contextual filters, but I'm not clear on exactly how this works still

how do I set up a filter - does it go in the source or target block or both?
how do I access the value in the target block?
how do the values get passed, on the URL, or as session values?

also my situation involves passing variables from 2 view blocks to another view block.

And presumably AJAX would need to be used to load the third view?

I could split the third block into 2 and display results from block one and block two separately, if that's any easier.

But I'm really not sure how to set up a filter or how to use the passed values, or how exactly contextual filters work, any guidance appreciated.

Update:
I have updated this question to try to make it clearer what I have and what I need to do.

Thanks to Remy I understand how the filter value is accessible, but I still don't understand the following:

Is there something I have to do to enable a block to be able to receive parameters (does it need to be an attachment, an embedded view, or something else)?

Placing the contextual filter in the master view makes sense if every display has it, thus it still can be overridden. If there is only one block display out of X other displays, I would place the contextual filter in that display.

The contextual filter will be available as 'field' in your view and you can use it in the filter-criteria.

Contextual filters are passed via the url (in most cases), no matter if AJAX or not.
Or when using views_embed_view as method-arguments.

For your propose, conditional filters nor relationships will not work.

You could then add the other view display as fields and make them conditional. But this is not really good practice nor performant. (Use also a caching module)

From views_field_view:

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.

A ctools tools multi step form wizard is a better approach. here's an example https://github.com/jgottwig/ctools-wizard-example.


error from drupalroot We have a live system.

define('DRUPAL_ROOT', getcwd());
define ('DRUPAL_ROOT', getcwd ());

I couldn't log in with the command

define('DRUPAL_ROOT', 'D:/www/webhosting/o3800_7Z55V5Hop2Ff/wwwroot/vts/')

I changed it this way

I entered the site but the page is broken as it appears in the photo

I request help on this subject, thanks.

Firstly, will be better if you host a Drupal site on the separate domain/subdomain.

About your error, seems you forget copy all files (for example a folder with themes).

About the DRUPAL_ROOT constant, you shouldn't change it.


Drupal Views: Taxonomy Stripes for Calendar I've got a bit of an issue with taxonomy stripes on Calendar.
If I wanted to define colour stripes for Content Types, I get this choice:

Simple. I just choose the type and add a colour.
However, I want to do it for Taxonomy. So I choose Taxonomy in the Stripes menu:

I successfully link it to the relevant taxonomy field, but I see no option for colour choice?

I'm using the most recent stable version of the calendar and the views modules.

How do I do this?
Is there another way?

Use the latest development snapshot. See http://drupal.org/node/1392306#comment-5581466 for the patch.


How to add a 2nd submit button to a node form? I need to have an extra Save button at the top of my node form.

Pressing the 2nd button should do the same action like the regular one.

The following code creates a 2nd save button:

function MYMODULE_form_MYFORM_alter(&$form, &$form_state, $form_id) {

  $form['actions']['submit2'] = array(
    '#type' => 'submit',
    '#value' => t('Save & View'),
    '#access' => TRUE,
    '#submit' => array('node_form_submit'),
    '#weight' => -10,
  );
}

But how do I put it at the top of the page (the form length is not fixed).

The following code does create a 2nd submit button.

function MYMODULE_form_MYFORM_alter(&$form, &$form_state, $form_id) {

  $form['actions']['submit2'] = array(
    '#type' => 'submit',
    '#value' => t('Save & View'),
    '#access' => TRUE,
    '#submit' => array('node_form_submit'),
    '#weight' => -10,
  );
}

But since we want it on the top of the form, it's better to put it outside the 'actions' group. So the following code puts it just below the title, ready for styling:

function MYMODULE_form_MYFORM_alter(&$form, &$form_state, $form_id) {

  $form['submit2'] = array(
    '#type' => 'submit',
    '#value' => t('Save & View'),
    '#access' => TRUE,
    '#submit' => array('node_form_submit'),
    '#weight' => -10,
  );


Fatal error "Cannot redeclare template_preprocess_select()" on every attempt to install modules or themes Fatal error: Cannot redeclare template_preprocess_select() (previously declared in /Users/ron/Sites/provgmc.dev/core/includes/form.inc:30) in /Users/ron/sites/provgmc.dev/core/includes/form.inc on line 37

This is not an issue with code I've written or altered. I'm just trying to install a theme using the user interface. I tried Bootstrap and Zymphonies, then a simple module or two; they give the same error when trying to install them.

I am using Drupal 8.2.6, running on Mac OS X Sierra, with PHP 5.6.28. I am not using OPCache, and there are no changes from Mac OS pre-installed versions.

I've used Drupal 7 (under El Capitan) in the past, and I have never had any issues like this.

Mac OS X should have any of these possible reasons:

Your site folder name is mixed case
You cd'd into your site folder name with the wrong case i.e. cd ~/sites/myproject instead of cd ~/Sites/myproject
Your groups are incorrect (use staff not wheel)
Drush is using a different version of PHP from MAMP (Check the output of php --version.)

If you get a redeclare error running drush cc all, check one of the above issues. If sudo drush cc all does not produce the error, it could be one of them. In my case, changing the case of my project from ~/Sites/MyProject to ~/Sites/myproject made the issue go away.

For more in-depth discussion, see:

https://www.drupal.org/node/1305254
https://www.drupal.org/node/1296594


Function preprocess_views_view if not logged in I have added two javascripts for one page only using preprosess in template.php. The two scripts seem to work well.

The jquery version I include on this page/view is interfering with admin overlay and other stuff for the editor. I'd like to apply this preprosess only if the user is not logged in.

/**
 * Equal height row javascript + jquery 1.10.2 - in page-view (my-view-page)
 */
function mytheme_preprocess_views_view(&$vars) {
   $view = $vars['view'];
   // Make sure it's the correct view
  if($view->name == 'myview') {
     // add needed javascript
     drupal_add_js(drupal_get_path('theme', 'mytheme') . '/js/jquery-v1-10-2.js');
     drupal_add_js(drupal_get_path('theme', 'mytheme') .'/js/equal-height-row.js');
  }
}

Is it possible to correct this function to make sure the scripts are not served to logged in users? Or does it require a different approach like preprocess_html?

(For now there is not going to be registered users other than editors)

(Using Drupal 7.25 and custom subtheme of Responsive Bartik)

Sure, add either:

global $user;

to your function and check its uid status or wrap the drupal_add_js in an IF block using the Core API function user_is_logged_in()

For exmaple:

$user_is_not_logged_in = (user_is_logged_in() === FALSE);
if ($user_is_not_logged_in) {
  if ($view->name == 'foo') {
    /* drupal_add_js(...); */
  }
}

EDIT:

So the full thing (doing your homework for you) would look like this:

/**
 * Equal height row javascript + jquery 1.10.2 - in page-view (my-view-page)
 */
function mytheme_preprocess_views_view(&$vars) {
   $view = $vars['view'];
   // Make sure it's the correct view
  if($view->name == 'myview') {
    if (!user_is_logged_in()) {
      // add needed javascript
       drupal_add_js(drupal_get_path('theme', 'mytheme') . '/js/jquery-v1-10-2.js');
       drupal_add_js(drupal_get_path('theme', 'mytheme') .'/js/equal-height-row.js');
    }
  }
}


Multiple forms in same page from single form builder returning the first form's value in submit I have written a single form builder and a form submit handler corresponding to that form.

What I have done is that I have rendered the form multiple times using for loop and then concatenated them into a single variable and then displayed it on a single page.

Each form has separate submit buttons.

But the problem is that whenever I press the submit button of any of the forms I am only getting the form that was built first in the form_state['values'] in the submit handler.

For now, I have made it work by taking the form_state['input'] which seem to have the correct set of values based on the form submit clicked.

I need the corresponding form values in the submit handler. How can I achieve this?

Is this some kind of bug or am I doing it wrong?

$form_markup = '';
  foreach ($ids as $key => $value) {
    $req_form = drupal_get_form('_request_form', $value, $key, $node);
    $form_markup .= render($req_form);
  }

My form and form_submit

function _request_form($form, &$form_state, $value, $key, $node) {
    $form['name'] = array(
      '#type' => 'item',
      '
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Ask',
    );
    return $form;
  }
}

    function _request_form_submit($form, &$form_state) {
      dpm(form_state['values']);
      dpm(form_state['input']);
    }

Any help is much appreciated.
thanks.

You'll need to implement hook_forms(), so that you can create 'aliases' of your forms.

For example, let's imagine a form named 'message_form', that you want to include multiple times on the page. To do this, you append a unique number to the form name each time when calling the form:

$page = [
  'form_1' => drupal_get_form('message_form-1'),
  'form_2' => drupal_get_form('message_form-2'),
];

return $page;

Next, you implement hook_forms() to watch for form names in the format above:

function hook_forms($form_id, $args) {
  // Act on form IDs that match the pattern message_form-[NUMBER].
  if (preg_match('/^message_form-\d+$/', $form_id)) {
    // The key is the form ID that has been passed.
    $forms[$form_id] = [
      // The callback is the actual form definition to be called.
      'callback' => 'message_form',
    ];
  }
}

Now each form being put on the page will have a custom form ID and therefore the system will know which form the submitted data refers to.


7: How to import simple channel-level rss data to the parent feed node created by Feeds module? The Feeds module is properly importing Child/Feed Item-level data to the generated Child-level Drupal nodes.

What I need now is to import Parent/Channel/Feed-level info to the Parent/Feed=level Drupal entity that the Feeds module also creates.

It would/should be a simple mapping that imports the Parent/Channel-level RSS feed data (channel title, channel description, channel image etc) to the Parent/Feed Drupal node that the Feeds module creates (NOT the item/child-level nodes that it also creates.)

<channel>
  <title>Some Feed Title</title>
  <description>Some description...</description>
  <image>
   <url>http://example.com/image.jpg</url>
  </image>

  <item>item info starts here....</item>
  <item>more item stuff here....</item>
</channel>

It seems the Feeds module does not account for this.

I see mention of creating a new parser (https://drupal.org/node/622700) but that is still only affecting the creation of the child/item-level nodes yes?
On that same page I see "Create a feed node programmatically" but that ignores the core Feeds child/item-level functionality yes?
I have installed the Rules module (and its Feeds patch) and am able to get from the $source object the created Parent/Channel-level node ID that Feeds generates when importing the feed, but I don't have any of the feed's data to send to that ID (I don't think anyway - there is a FeedsFetcherResult numerical value but not sure that that is of any help.)

Any assistance in pointing me in the right direction would be much appreciated! Seems like a common need related to this module but oddly haven't seen any solutions out there. Thanks.

You can try to use the patch supplied in https://drupal.org/node/1689374?


Suggestions for storing private user content lists I have a feature on my Drupal7 site where users can store a list of personal stock symbols (NYSE, NASDAQ, etc) and then do different actions on that list; quote, chart, etc. These lists are private to each user.
For the first iteration, using a custom module, I've stored them in a custom table after the user enters them using the Drupal Form API. The form has a text box for list title, and a text area for entering symbols separated by space or comma. They can have multipe lists by clicking a 'add more' button. The data is stored in a flat structure of "-list_title1 sym1 sym2... -list_title2 sym1 sym2..." It is then split out for use in the UI. Some users have more than 300 symbols.

For the second iteration I would like to be able to store these symbols so that they can be referenced individually (deleted or added, notes about symbol) and the lists sortable. I would like to be able to utilize Views and features like Draggable_views so that the symbols could be re-orderd in a list. I would like users to be able to add symbols to their list from other content eg: news, trending symbols, symbol lookup.

There's a reference to $user->data in this Drupal8 article but I couldn't find more details on it.
https://www.webomelette.com/storing-user-data-such-preferences-drupal-8-using-userdata-service
The user_save api may work but I'm not sure how you would store this two-level data structure.
https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_save/7.x

I could not find any contrib modules for storing this data privately other than Profile2 which I don't think would work for this kind of content.
I'm looking for Drupal APIs to store this data on a per-user basis.

You could use ECK and link it to the user using Entity Reference. You'll need to some small custom coding to auto fill the entity reference field with the logged in user's id. Better yet, you can use Rules for a no code solution to autofill the entity reference with the logged in user ID.

Here is a video on ECK and for entity reference.


Taxonomy terms not translating on the edit/add node form I'm trying to translate the interface on a drupal 7 installation but somehow the terms and the taxonomy names are not being translated.

The vocabulary names and the terms names are already translated and the field names were also translated but the node creation form are still just showing on the default language.

Has anyone had the same problem?

Here's the page where this is happening:
http://www.cuipcairo.org/ar/node/add/initiative

Best guess based on your description is that you need to enable the URL detection at

  /admin/config/regional/language/configure

since that appears to be how you are distinguishing the interface. This recipe from http://drupal.org/node/1281704#comment-5253460 should also help:

Enable ALL i18n modules
Add your extra languages
(optional) - Enable Localization update and run Update translations at /admin/config/regional/translate/update
Enable URL detection method at /admin/config/regional/language/configure
(optional) - Throw that Language Switcher block into a visible section of your site
Add your Localized vocabularies and translate them
Add your terms and translate them
Edit the content types you want term references to appear in and Enable Multilingual Support (with translation) in Publication Options vertical tab
(recommended) - In the Synchronize Translations vertical tab check the first two checkboxes of the Extended language options. That is: "Set current language as default for new content" and "Require language (Do not allow Language Neutral)"
Add term reference fields to the content types you want


Are there any performance comparisons? Are there any reliable performance comparisons between vanilla Drupal 8 versus Drupal 7?

I have searched the web but only find the post "Drupal 7 vs Drupal 8 Performance Comparison", which is far from encouraging.

No, there is no reliable comparison, because doing that is almost impossible. There are various reasons for that, one is that D8 vanilla is like D7 vanilla + a whole bunch of modules, especially views.

If you compare a single request on a vanilla installation, then D8 is clearly slower than D7 (even if you add views), quite a bit actually. That might still improve more or less until the release, but it's not going turn around completely.

D8 is just running a lot more code, our own and vendor code like symfony underneath, so that takes more time. The service container also adds quite a bit of overhead.

However, D8 has a number of things that are hopefully going to make more than up for that on real sites

Javascript by default runs in the footer, which improves front-end performance, as pages build up faster and you can see and use them earlier.
The highly improved caching, especially render caching with cache tags and contexts, means that caches on real sites with changing content will perform much better. In D7, every time a node was changed or created, the complete block and page cache were invalidated. In D8, thanks to cache tags, D8 knows where that node shows up and might show up and only has to invalidate the relevant pieces. There's still a lot of work going on to improve that, but D8 provides a lot more tools to build faster big sites.
There's also the argument that you would have to run D7 on hardware that is as old as that version while running D8 on modern hardware, which is considerably faster. Also, early benchmarks show that vanilla D8 runs up to 50% faster with PHP7, because that version is much better at running a lot of code fast. (You can also run D7 on modern hardware and with PHP7 (probably), so that argument only works so far...)
Thanks to those decoupled services and better API's, which in a first step make things slower, is D8 going to have much better support for running partially/completely (depending on how daring you are I guess) with MongoDB and other alternative backends (like redis for the key value store). Again, for big sites, that allows to take at least part of the load away from MySQL, and store parts of your data (or, again, everything) elsewhere, which in turn helps to distribute the load across multiple servers.

Also keep in mind, if you care about performance, then you're very likely not running vanilla D7/D8 sites, you have large sites with a lot of content. And as mentioned above, D8 brings a lot of tools to help you to make those kind of sites faster. Some things will require work as a developer and need to be done right (just like in D7), but if you do, then I think that D8 can perform pretty well in real world scenarios.


How can i add a property(uuid) to existing custom entity base_table? I want to add uuid property to existing custom entity extending ContentEntityBase.
I've tried to a add the uuid entity key and installed field storage definition by:
function my_module_post_update_adduuid() {
  \Drupal::entityTypeManager()->clearCachedDefinitions();
  $definition_update_manager = \Drupal::entityDefinitionUpdateManager();

  /** @var \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface $last_installed_schema_repository */
  $field_storage_definition = BaseFieldDefinition::create('uuid')
    ->setLabel(new TranslatableMarkup('UUID'))
    ->setReadOnly(TRUE);

  $definition_update_manager->installFieldStorageDefinition('uuid', 'custom_entity_id', 'custom_entity_id', $field_storage_definition);
}

The "problem" is that for custom entity with data_table defined the property is added to the data_table and not to the base_table as expected. If the custom entity doesn't have data table defined the uuid property is written properly in base_table.
Everything seems to work even though the uuid property is defined in data_table but the schema is inconsistent compared to clean install with the uuid key present from the beginning.

Found a workaround for this:
Step 1: Add uuid to entity keys in annotation.
Step 2: Add custom storage handler in annotation.
Step 3: Create the custom storage handler class extending SqlContentEntityStorage with getCustomTableMapping overridden:
/**
 * Use AddUuidTablemaaping to support adding uuid to base table.
 */
public function getCustomTableMapping(ContentEntityTypeInterface $entity_type, array $storage_definitions, $prefix = '') {
  $prefix = $prefix ?: ($this->temporary ? 'tmp_' : '');
  return AddUuidTableMapping::create($entity_type, $storage_definitions, $prefix);
}

Step 4: Create AddUuidTableMapping extending DefaultTableMapping and override create method.
public static function create(ContentEntityTypeInterface $entity_type, array $storage_definitions, $prefix = '') {
  $table_mapping = new static($entity_type, $storage_definitions, $prefix);

  $revisionable = $entity_type->isRevisionable();
  $translatable = $entity_type->isTranslatable();

  $id_key = $entity_type->getKey('id');
  $revision_key = $entity_type->getKey('revision');
  $bundle_key = $entity_type->getKey('bundle');
  $uuid_key = $entity_type->getKey('uuid');
  $langcode_key = $entity_type->getKey('langcode');

+ // The Magic, without this uuid will be added to dataTable if such exists.
+ if (array_key_exists('uuid', $storage_definitions)) {
+   $uuid_key = 'uuid';
+ }
+ // end Magic.

  $shared_table_definitions = array_filter($storage_definitions, function (FieldStorageDefinitionInterface $definition) use ($table_mapping) {
    return $table_mapping->allowsSharedTableStorage($definition);
  });

  $key_fields = array_values(
    array_filter(
      [$id_key, $revision_key, $bundle_key, $uuid_key, $langcode_key]
    )
  );

  $all_fields = array_keys($shared_table_definitions);
  $revisionable_fields = array_keys(array_filter($shared_table_definitions, function (FieldStorageDefinitionInterface $definition) {
    return $definition->isRevisionable();
  }));
  // Make sure the key fields come first in the list of fields.
  $all_fields = array_merge($key_fields, array_diff($all_fields, $key_fields));

  ...
}

Step 5: Create the field storage definition in post update hook:
$definition_update_manager = \Drupal::entityDefinitionUpdateManager();

/** @var \Drupal\Core\Entity\EntityLastInstalledSchemaRepositoryInterface $last_installed_schema_repository */
$field_storage_definition = BaseFieldDefinition::create('uuid')
  ->setLabel(new TranslatableMarkup('UUID'))
  ->setReadOnly(TRUE);

$definition_update_manager->installFieldStorageDefinition('uuid', $entity_type_id, 'my_custom_module', $field_storage_definition);

Step 6: Set uuid values for existing entities in baseTable:
$rows = $db_connection->select($entity_type_id, 'e')
  ->fields('e', ['id'])
  ->isNull('uuid')
  ->execute()
  ->fetchAll();

foreach ($rows as $row) {
  $db_connection->update($entity_type_id)
    ->fields(['uuid' => \Drupal::service('uuid')->generate()])
    ->condition('id', $row->id)
    ->execute();
}

Step 7: Update entity type and field storage schema:
$definition_update_manager = \Drupal::entityDefinitionUpdateManager();

$e = $definition_update_manager->getEntityType($entity_type_id);
$keys = $e->getKeys();
$keys['uuid'] = 'uuid';
$e->set('entity_keys', $keys);

$definition_update_manager->updateEntityType($e);
$field_storage_definition = $definition_update_manager->getFieldStorageDefinition('uuid', $entity_type_id);
$definition_update_manager->updateFieldStorageDefinition($field_storage_definition);

This last step will update the entity type definition in db + make uuid field not_null in in baseTable.
Done.
Alternate solution is to use $definition_update_manager->updateFieldableEntityType, but will require overriding storage_schema handler(assuming there are existing entities) for the entity type as it forces not_null for entity keys by default.


How can I render a result row using the Views API I'm trying to render the rows in a view manually using the Views API. The style plugin is the "Unformatted" plugin. This is my code:

<?php
$view = views_get_view('nearme');
$view->execute('default');
$view->preview();

$renderer = $view->style_plugin->row_plugin;
foreach ($view->result as $row) {
  echo $renderer->render($row);
}
?>

This code almost works - it renders essentially a blank row. My "Global: custom text" field is rendered, as are some generic labels and field HTML, but the actual values from $view->result are not interpolated.

What am I doing wrong?

The tokens in views requires $view->row_index to be set to be able to get the right rendered fields.

$view = views_get_view('nearme');
$view->execute('default');
$view->preview();

$renderer = $view->style_plugin->row_plugin;
foreach ($view->result as $index => $row) {
  $view->row_index = $index;
  echo $renderer->render($row);
}


Calling a procedure from drupal I have a procedure structure like this in an Oracle database:

procedure overlapping_course (
  v_id  number,
  v_program varchar2,
  v_message_type  varchar2,
  v_user_type varchar2,
  v_language  varchar2,
  v_channel varchar2,
  v_country varchar2,
  v_start_date  date,
  v_end_date  date,
 v_return_val  out varchar2
 )

I am trying to call this procedure from Drupal 7 and I am following this link. My code looks like this:

 $conn = Database::getConnection();
 $saved_class = $conn->getAttribute(PDO::ATTR_STATEMENT_CLASS);
 $conn->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('PDOStatement'));
 $statement = $conn->prepare('call overlapping_course(?,?,?,?,?,?,?,?,?,?)');

$statement->bindParam(1, $id,PDO::PARAM_INT);

$id=1;

$statement->bindParam(1, $program,PDO::PARAM_STRING);

$program='c++';
 -------
 --------

but I am always getting the following error

Fatal error: Call to undefined method DatabaseStatementPrefetch::bindParam()   in C:\Apache24\htdocs\drupal\includes\database\oracle\database.inc on line 655.

I don't know the problem, but after adding the  following piece of code in my database.ini of oracle directory and changing my calling method prepare('-----') to oraclePrepare('-------') I am able to access the stored procedure with parameters. I got the reference from here

Check for the oraclePrepare('-------') method in database.ini. If it is not there then add following lines in the DatabaseConnection_oracle class.

code Added in DatabaseConnection_oracle class of oracle's database.ini:

 public function oraclePrepare($query)
 {
     return parent::prepare($query);
  }


Views contextual filters taxonomy name 2 fields using same vocabulary I have a content where two fields using the same vocabulary.
I want to show nodes related content filtered by the these fields.

I try with relation

Relationships

content:field_1
(term from field_field_1) Taxonomy term: Content using field1 (Relationship term from field_field_1 ;  Require this relationship )

Contextual filters

   (field_field_1) Content: field_2

   Provide default value : Taxonomy term id from url
   Load default filter from node page
   Limit terms by vocabulary ( country)

   Specify validation criteria ( taxonomy term )

    Vocabularies : Country
    Filter value type : Term name converted to Term ID
    Transform dashes in URL to spaces in term name filter values

This query returns nothing.

I don't want to use Views PHP code fields because of security concerns.

If I understand your question correctly, out of the box the easiest way is to add a Contextual Filter Content: Has Taxonomy Term Id. This one does not care whether you have 1 field or 20 that reference taxonomy terms.  Further details within are whether you want to match from URL on term id or term name, etc.

I came across your question whilst seeking an answer to mine How to filter on taxonomy term but only match one field on the node, where two fields (primary and secondary) both use the same vocabulary which I think is different.


How to put a Token in a path in a view Path setting? I have a view page display to show some content and I added a contextual filter to filter by user id [uid]. It works fine.

I need to create the path to be shown in the Main Menu including the token for user id at the end of the path. Something like /tus-lotes/[uid]

If I try with: /tus-lotes/% I get this error message:

Views cannot create normal menu items for paths with a % in them.

But I see that the path doesn't accept token. How can I accomplish this?

Please look the capture:

In the contextual filter settings:
When the filter value is NOT available -> provide default value ->User ID from url

and edit link of the view just without the argument/token


Error When Create Drupal Commerce Product Display I have managed to create a product type and import my product data, so I now have a list of products.
then i follow ryan szrama instruction http://drupalwatchdog.com/1/1/building-commerce-product-display

After that i get this error.
EntityMetadataWrapperException: Unknown data property commerce_product. in EntityStructureWrapper->getPropertyInfo() (line 339 of C:\xampp\htdocs\drupal7\modules\entity\includes\entity.wrapper.inc).

what i should do??

This in a known bug, you should either start fresh or use the Commerce repair. The problem is most likely that a field that was expected wasn't installed properly. This could happen if you add hook_line_item_info to a module that's enabled.


How to make "Page specific visibility settings" for blocks more flexible? My problem is that depending on a running mode my Drupal website might have either regular permalinks, or pretty, aliased ones. And "Page specific visibility settings" for blocks on specific pages (Show on only the listed pages) do not work across the modes.

It would be logical if let's say: node/23 syntax could work in any case, but it seems that it doesn't.

Do I have to change every setting for every block every time I switch permalink structure? Or there is more flexible solution to this?

If you need to control block visibility then the Context module is the way to it.

(edit) If you use the Context module you won't have to mess around with these types of things and more importantly neither does Drupal which in fact makes it faster. You can read more about Blocks, Context and Panels, another alternative to Blocks, here.


Render menu separately within admin I need to render the main menu within the admin section of my website.  I am setting up a module to do this on a new page.  I need to theme this menu custom for just the admin, and leave it as it typically would be on the front-end of the site.

How can do do this?

$menu = menu_tree_all_data('main-menu');
// ...customize template/output for this menu and render from my module...

You can use one of these method.

Below method is used to print Main Menu in page.tpl.php file:

$main_menu = menu_navigation_links('main-menu');
$output = '
';
$output .= theme('links__system_main_menu', array(
    'links' => $main_menu,
    'attributes' => array(
      'id' => 'main-menu-links',
      'class' => array('links', 'clearfix'),
    ),
    'heading' => array(
      'text' => t('Main menu'),
      'level' => 'h2',
      'class' => array('element-invisible'),
    ),
  ));
$output .= '
';
print $output;

Or the example provided here:

$tree = menu_tree_all_data('main-menu');
menu_tree_add_active_path($tree);
print drupal_render(menu_tree_output($tree));


How to discover events for event dispatcher I want to write an implementation of EventSubscriberInterface for an event in commerce, there is a handy example, but

How do I find out what events are available (as a whole for my site) and/or
How do I know what events are getting hit on a request?

This question is not specific to the commerce module, it is just the context of my current problem.

You can simply use the Drupal console.

List all the events that could be debugged:

drupal debug:event

drupal dev

Show the information for the specific event, for example "commerce_order.commerce_order.update":

drupal dev commerce_order.commerce_order.update


How to rename address labels on Address field module? I wanted to know if it's possible to change the input labels on the address field module 'Address 1' and 'Address 2' without using the string overrides module?

I want to be able to change them to say 'Address line 1' and 'Address line 2'.

Can this be done in a template preprocess function?

This can be done with hook_form_alter:

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {

    //drupal_set_message("Form ID is : " . $form_id);

    switch($form_id) {

        case 'MY_FORM_ID':

            // dpm($form);

            // $form['NAME_OF_YOUR_FIELD'] - this is the field you want to edit

            // check that the field is set before looping over values
            if(isset($form['NAME_OF_YOUR_FIELD'][LANGUAGE_NONE])) {
                // loop over each values passing $item by reference
                foreach($form['NAME_OF_YOUR_FIELD'][LANGUAGE_NONE] as &$item) {
                    if(is_array($item) && isset($item['street_block'])) {
                        $item['street_block']['thoroughfare']['#title'] = 'Address Line 1';
                        $item['street_block']['premise']['#title'] = 'Address Line 2';
                    }
                }
            }
            break;
    }

}

I found the path to the variable I wanted to change by outputting the $form array to the message area using devel's dpm function, and then searching though the array for the value "Address 1" using the search krumo module.


How do I prevent anonymous sessions? I'm working on a site hosted on Acquia and we're using Varnish and Akamai.  We don't want anonymous sessions from being saved in the db, as it breaks the caching.  I've made a few tweaks, and I'm trying to track down where the sessions are coming from.  We're using simplesamlphp_auth for admin logins using Okta and LoginRadius module from /user/login, so it's not a default Drupal 8 installation in regards to login and sessions.

I'm trying to track down where the anonymous sessions are coming from.  But I was wondering if there's a way outside of fixing either of these modules to force Drupal 8 to NOT save anonymous sessions to the database.  Is there a hook or event that I could use to prevent the anonymous sessions from being saved?

If so, what are the implications?  I guess lost cookies that some contrib module may be trying to set?

I'm seeing sessions like this appear:

*************************** 333. row ***************************
      uid: 0
      sid: _oo8QqyuF4tMOIIWr-uCOj8aqsknzV1WWkmf0bHzlmQ
 hostname: 23.220.148.70
timestamp: 1557934618
  session: messages|a:1:{s:7:"warning";a:1:{i:0;O:48:"Drupal\Core\StringTranslation\TranslatableMarkup":3:{s:9:" * string";s:57:"Your session was deliberately ended from another session.";s:12:" * arguments";a:0:{}s:10:" * options";a:0:{}}}}
*************************** 334. row ***************************

or this:

          uid: 0
      sid: _VmVWTDsbgQYOcZFxN15Z5j-s4jt4YmsjSZGggphAIM
 hostname: 72.247.190.102
timestamp: 1557928795
  session: _symfony_flashes|a:1:{s:5:"error";a:1:{i:0;s:49:"Access denied. You must log in to view this page.";}}_sf2_meta|a:3:{s:1:"u";i:1557928795;s:1:"c";i:1557928795;s:1:"l";s:7:"2000000";}
*************************** 335. row ***************************

I think part of the issue may be that messages aren't getting displayed to the user on cached pages, so the anonymous sessions aren't being emptied of their _symfony_flashes

The most concerning one dumps a ton of user data, I think this from loginradius:

*************************** 332. row ***************************
      uid: 0
      sid: _2PXluVM2rAY29hE-HFkNQQ8_nPdP4QeU4Y3PoX40ws
 hostname: 184.25.157.170
timestamp: 1557870161
  session: _sf2_attributes|a:5:{s:12:"access_token";s:36:"fb98d952-f1a2-4ba3-820e-2db2c7313008";s:17:"user_profile_data";O:8:"stdClass":146: etc. (I'm not going to post the data here)

Find out which modules set session data by dumping these variables for anonymous requests:

var_dump(\Drupal::request()->getSession()->all());
var_dump($_SESSION);

You can ignore the symfony metadata starting with _symfony or _sf2.

Then search the code base for session set() commands setting this data. You can then either change this code or remove the session data in your own code with remove().

When all session data is removed the session will be destroyed automatically at the end of the request. The metadata doesn't count.

A special case is the symfony flash bag. Data stored here is normally only kept between two requests. Ideally the first one is a redirect so the second one happens immediately. Drupal uses the flash bag for system messages. The messages are displayed and removed by the status messages block, which is enabled by default. The messages block is uncacheable and re-built on each request, because of how the caching system handles requests containing a session.


Limit entity reference options base on taxonomy tag I have three content types. Building, Department and Person. I connect this contents whit entity reference base on Content types. The problem is that I have a lot of persons and a lot of departments and also multiple buildings. How can I limit selection in edit mode, that I can add persons in department only from particular building wher the department is placed? My first try was to add taxonomy term (building A) to person and department placed in building A and then try to filter this in view but without a success because for building B I will need to create new Content type and add different view for same content structure. I could create Content Type "Person building A" and then filter by content type but this does not seems like a good solution.

I did something like this recently myself.

Your Person content type should have two entity reference fields, one to a Building, and a second to a Department. A Department also has an entity reference to Building.

Use a hook_form_alter to target the Person form.
In that function get a list of the Departments and their Building references, and attach it to the form along with a reference to a custom Javascript library. (Note that you'll have to use the proper machine name for your content types and fields.)

$departments = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties(['type' => 'department']);

$department_data = array_map(function($department){
    return $department->field_ref_building->target_id;
}, $departments);

$form['#attached']['drupalSettings']['dept_bldg_info'] = $department_data;

$form['#attached']['library'][] = 'my_module/my_module.library_name';

The library file will look something like this:

Drupal.behaviors.chartInfoHierarchicalSelect = {
  attach: function (context, settings) {
    // Apply to the HTML page context & the person forms.
    if (context.location || context.id == 'node-person-edit-form'|| context.id == 'node-person-form') {
      let building_inputs = jQuery('[name$="[field_ref_building]"]'),
        department_inputs = jQuery('[name="[field_ref_department]"]');

      building_inputs.each(function () {
        // Ensure initial load has proper limits.
        updateDepartments(jQuery(this));
        // Update on change.
        jQuery(this).change(function () {
            updateDepartments(jQuery(this))
        });
      });

      function updateDepartments(building_input) {
        var selected_building = building_input.val();

        department_inputs.each(function () {
          var opt_val = jQuery(this).val();
          if (opt_val != '_none' && drupalSettings.dept_bldg_info[opt_val] == selected_building) {
            jQuery(this).prop('disabled', false);
          }
          else {
            jQuery(this).prop('disabled', true);
            jQuery(this).prop('selected', false);
          }
        });
      }
    }
  }
};

Then when you select a building, you should see the appropriate departments get enabled/disabled.


How to specify a background image in a view so that it doesn't get removed? I want to output an image as a background-image of a "section"-tag but it doesn't work.

First I added the Image URL Formatter module, so I do not output the image but the url of the file.

In my view I add the image which generated with the contextual filter of the url. In that field I rewrite the output:

When I check the site I only get this:

I tried several times and it seems to me that Drupal will not accept the "style="..."" tag, Drupal will always remove it! And I don't know why?

If I change the style to class, I get the normal output, as in this example:

Does anybody have an idea?

To understand why this (= the style being removed) is happening, refer to this comment in the views issue queue:

  Rewrite uses filter_xss_admin and allows only the tags listed there.

It also includes a possible solution for it, which is like so:

  If you need more than this, then you need to use a template where you have complete control. This ensures that data entered via the UI is safe.

For an alternative solution (instead of using a template), you may want to consider the Background Images Formatter module. Here is an excerpt from its project page:

  This module provides an image formatter who allows you to set an image in background of a div. The images are from a field of an entity and not from a configuration page or sth else, so it's very easy to setup and manage.


marinelli banner images not cycling drupal 7 marinelli banner images not cycling (no forward or back icons either) I had disabled banner for a while and on trying to re-enable, images load but don't cycle.  my back up site works but main site is too far changed to restore from months ago.
I have tried removing and re-installing theme.
where does the theme store settings?
What can I do?
Thanks
Mick

Given the error  'TypeError: $.browser is undefined' I would surmise that there is a discrepancy in the version of jquery running. If you have the module jQuery update installed and running on one or both, check to see if both sites are running the same version of jquery.


I'm unable to access variables in template from preprocess function I am using a preprocess function to get data from specific content types. I am able to print the data in the pre-process function but unable to view the same in the twig file.

This is the code I am using.

    function themename_preprocess_node__custom_content_type_name(&$variables) {
      $query = \Drupal::entityTypeManager()->getStorage('node')->getQuery();
      // Get all products node IDs.
      $nids = $query->condition('type', 'content_type_products')->execute();
      // Load all product nodes.
      $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
      // Pass them to node--custom-content-type-name.html.twig.
      $variables['products'] = $nodes;
     //echo "<pre>";
     //print_r($variables['products']); exit;
    }

print_r($variables['products']) shows the content of $variables['products'], but the node--custom-content-type-name.html.twig file doesn't print anything for {{products}}.

Why?

You need to apply EntityViewBuilderInterface::viewMultiple before you can render the nodes in a twig template:

$variables['products'] = \Drupal::entityTypeManager()
  ->getViewBuilder('node')
  ->viewMultiple($nodes);

Twig:

{{ products }}

You can add a view mode to viewMultiple() as second argument, for example teaser.


TreeView with checkboxes I need to create a Tree View Menu with checkboxes, showing values taken from the database. I want to use the Collapsible Checkbox Tree. A demo of the jQuery plugin is available here.

If this is a listing of taxonomy terms, you could giva a try to the Term Reference Tree module. At any rate you could just carefully theme a view, tossing out all markup that is unnecessary or even could mess up with jQuery plugin.


How do I remove the "submitted by" text on node display? In Drupal 6 the option to remove that text  was located in the theme settings; where is it in Drupal 7?

You can find the option by editing the content type settings.

Structure > Content Types > Type Name

Click Edit

Then uncheck the Display author and date information. option in Display Settings.


Ajax request return field without name attribute Instead of getting multiselect on making ajax request while I select content type, I got single select and this select hasn't any name (select tag hasn't attribute name). So here's problem and I don't know how to fix it. Can anybody help?

$form['export_what'] = array(
    '#type'  => 'select',
    '#multiple' => FALSE,
    '#title' => t('Select content type'),
    '#required' => TRUE,
    '#options' => $form['export_what1_options']['#value'],
    '#ajax'    => array(
        'callback' => 'insttance_ajax_fill_content',
        'wrapper' => 'replace_model_div',
        'effect' => 'fade',
        'event'  => 'change',
    ),
);

$form['export_data'] = array(
    '#type' => 'select',
    '#multiple' => TRUE,
    '#required' => TRUE,
    '#default_value' => '',
    '#prefix' => '
',
    '#suffix' => '
',
    '#options' => $content,
);

function insttance_ajax_fill_content($form, $form_state)
{
    $i = $form['count_field']['#value'];
    $content = getAllContentByType($form_state['values']['export_what']);

    $form['export_data'] = array(
        '#type' => 'select',
        '#multiple' => TRUE,
        '#required' => TRUE,
        '#default_value' => '',
        '#prefix' => '
',
        '#suffix' => '
',
        '#options' => $content,
    );

    return $form['export_data'];
}

The attribute name is missing because you have replaced the select element in ajax callback. You just need to update the #options

function insttance_ajax_fill_content($form, $form_state)
{
    $i = $form['count_field']['#value'];
    $content = getAllContentByType($form_state['values']['export_what']);

    $form['export_data']['#options'] = $content;

    return $form['export_data'];
}


Log out URL returns 503, redirects to path with double slash When users access /user/logout they receive a "Page Not Found" error, and the URL they are forwarded to looks like this:

https://wwws.site.com/dir/site_name//dir/site_name/

Why is this redirect happening and how do I change the logout path so that it wouldn't create the double slash?

You should use URL() to create logout url. For example,

url('user/logout')


Uncheck Generate automatic URL alias problem When I add new content I uncheck generate automatic url, but below, the Url Alias text field where I want to add custom url is still disabled. I'm not able to write my custom url there.

Check if "Path" module is enabled.  If not, enable it.  I think it is enabled by default.

And go to admin/people/permissions and check "Administer URL aliases" under "Path" section.


How to display node teaser in Display Suite custom field? I am trying to create custom Display Suite code field.

I would like to show truncated text of node body or teaser if exists (+ other stuff, like: (...) and link to current node)

I tried to use [node:teaser] but nothing was showed.
I tried to use [node:body:?] token too, but all options I have tried failed for me.

Field code:

[node:teaser] (...) <?php print t('read more'); ?>

Any suggestions?

It so basic thing but I have no idea what I am doing wrong here...

I did this by adding a preprocess field which then becomes available in DS.

<?php
      function MYTHEME_preprocess_node(&$variables) {
        // Get the summary as a discrete field.
        $body = array_pop(field_get_items('node', $variables['node'], 'body'));
        $variables['node_summary'] = $body['safe_summary'];
      }

Then in display suite add a preprocess field named node_summary.


Date/Time +1h in Node I have a module to import nodes with a date/time field. All times are correctly written into the database. But when I view a node or in node/edit I get the time +1 h.
In Drupal I have set the timezone to Berlin, which is GMT +1 h. When I change the timezone, the time in node/view/edit is not changing.

I don't know what to do to see the correct times in nodes.

Looks like a classic "off-by-one" error. You should make sure that you are storing all date stamps in the UTC format.

Read the section on "Converting to and from UTC" here:
https://www.drupal.org/node/291799

If the date/time field is storing the German time (UTC+1h) then it will end up adding another +1h when it localizes the time, and you'll end up one hour ahead.

"There are two hard things in computer science: cache invalidation, naming things, and off-by-one errors."

UPDATE: As you say in your comment below, you can get the desired result by simply subtracting 1h from each datestamp in order to convert from Berlin time to UTC.

However, this approach will only work if you are certain that the time field in the import file will always contain UTC+1 times.

If you ever need to import files that could be in different time zones, you'll need to follow the API.

To convert a local date back to UTC to store it in the database, do:

$date = // local date value
$local_zone = // the name of the local timezone, e.g., 'Europe/Berlin'
$type = // the type of date value, DATE_DATETIME, DATE_ISO, or DATE_UNIX

$date = date_make_date($date, $local_zone, $type);
date_timezone_set($date, timezone_open('UTC'));

// $date now contains the UTC value of the date.
// Output it like:

print date_format_date($date, 'custom', 'm/d/Y H:i');

In order to generalize your database import, you would also need to include a field for the $local_zone for each timestamp.

It sounds like you will always be importing Berlin timestamps, but I just wanted to make sure that you understood the drawbacks to simply subtracting 1h from each timestamp rather than following the API.

Even if simply subtracting 1h works for you in this case, there is value to doing this the right way, in case you ever need to import a file from another timezone, or one with mixed timezones -- either in your current project, or a future one.


Views of Grandchildren I need to create a view with contextual filters that displays all nodes below the specified term.

Examle:

Colors

Blue

Cerulean
Slate

Yellow

Bright

Hi-liter
Pastel Yellow

Not so bright
Mustard

(Bold represents nodes)

So "Colors" would list Cerulean, Slate, Hi-liter, Pastel Yellow, and Mustard.

"Yellow" would list Hi-liter, Pastel Yellow, and Mustard.

"Bright" would list Hi-liter and Pastel Yellow.

etc.

How can I create a contextually-filtered view of nodes by taxonomy term that takes the entire lineage into account?

You can do this in Views as you said with Contextual Filters.

In your view click "add" next to Contextual Filters and in the modal check "Content: Has taxonomy term ID (with depth)". Then click "Add and Configure" and you will see the "Depth" option.  In the case of your color example above your depth would be 2 and when passing "Colors" to the view it would return all the nodes you bolded.

If you want the whole depth if it has great grandchildren and so on you would need to set the depth higher to account for the number of levels of your taxonomy hierarchy.  For your example and passing "Colors" as the argument, a depth of 0 would return no nodes, 1 would return "Cerulean, Slate and Mustard", and 2 would return all of the nodes as mentioned above.

Passing the other Colors as arguments would behave in the way you desire.


How do I change the "Access Denied" message? I have a need to temporarily unpublish some pages on our website, but when anonymous users try to access an unpublished page, say they had it bookmarked, they get the message:

Access Denied

Which may sound too harsh. I thought about changing it to 'Page Not Found.'

However, I searched the entire site and I can't find any template that controls this particular message. Using Theme Developer, I can see that the Access Denied page is using the standard page.tpl.php, which I don't believe has anything pertaining to the Access Denied page.  What am I missing?

For Drupal 7 & 8, you can set your access denied page and your page not found page easily. Go to /admin/config/system/site-information and review the error page section.


Checking whether or not an unpublished comment exists on node for current user I'd like to be able to let a user know that their comment has been submitted and is awaiting approval on every view of that particular node, not just a notification printed in the message region immediately after a submission.  I assume there's a way to cross-check the current node's unpublished comments and print something in the comment area if the user shows up as an author of an unpublished comment.  I have a feeling I can write a simple function, something like below, but I'm missing something and I'm not sure where to run it (ie, in the .tpl or in an .inc):

function find_unpublished_comments_of_current_user(&$comment, &$user) {
    if ($comment->status == 0 && $user->id == $comment->uid){
      //something here
      }
}

Thanks for any help.

You can achieve this in either of the following way,

1) If you are writing custom function as described in question,
   a) Write your function in a block by selecting text format as PHP code, and display the   block in desired region.
   b) Otherwise define the function in your module and call it in your node template file node--type.tpl.php

2) Through view: Create a view to show un published comments of a node as follows,

View

Create a view:
Settings:
  Show: Comments
  Create block: select
  Click save & continue

Filter criteria
 Comment: Approved (No)
Advanced->Add
 Contextual filters

Content: Nid

Under When the filter value is NOT available

Provide default value : Content ID from URL
Comment: Author uid
  Provide default value ->choose user id from logged in user

Now assign your block to a region on the node display page, you will get unpublished comments of the particular user for that node,


Text pasted in CKEditor isn't clean On a Drupal 8 installation, with CKEditor enabled for Full HTML format, when I paste text from Word with cmd+V, the source code includes format that makes the code dirty.

Example:

Lorem ipsum dolor.

How can I force it to clean the code from Word?

For reference, there was a backwards-compatibility break in CKEditor v4.6 - it removed some of its own paste-from-Word button's cleaning. See this discussion on the Drupal side: https://www.drupal.org/project/drupal/issues/2871539

Note comment #6 there offers another workaround - responding to the
afterPasteFromWord CKEditor event in some custom Javascript and filtering exactly as desired.


How to add filter 'fq' in drupal 8 search api solr? I have 4 different content types, for those I have create 4 different search pages based on the page view I need to alter solr query.

In D7 we have addFilter('fq').

How can we do it in D8?

I have reached out to drupalsupport IRC got an answer from there. By the time I have got the reply from them debugged the code founded a createFilterQuery function in SearchApiSolrBackend.php file

$solarium_query->createFilterQuery('your_indexed_filedname')->setQuery('your_indexed_filedname:"string_to_be_searched"');

Here your_indexed_filedname would be something like ss_5f_test_5f_1

Don't forget to put double quotes for string to be searched, otherwise it won't fetch you the result.


Unable to use drush dl. No such file or directory filesystem.inc:267 I'm trying to download Drupal 7 using Drush 8.1.2, without success. It was working perfectly for months; now, I am getting the following error message on all modules and core downloads when I'm running:

drush dl drupal-7

  copy(/tmp/drush_tmp_1468772300_578bafccc15f2/tar: Failed to set default locale): failed to open stream: No such file or directory filesystem.inc:267
  Project drupal (7.50) could not be downloaded to /Applications/MAMP/htdocs/drupal-7.50

I haven't changed any tmp permissions. What can I do?

I am using PHP 5.6.10 and Drush temporary directory is /tmp.

The error:

  Failed to set default locale

sounds like tar command invoked by Drush has some problem detecting your system locale.

Try setting it to UTF-8 by the following command:

defaults write org.R-project.R force.LANG en_US.UTF-8

Source: How to fix 'tar: Failed to set default locale' error?


Programatically save node fields if fields is autocomplete? I have created a content type with 3 fields and my one field is node_refrence in this filed I am filling title of other node using node_refrence.

I am using this code.

> $node = new stdClass();
 $node->type = 'application';
> node_object_prepare($node);
> $node->title = "test title";
 $node->language = LANGUAGE_NONE;
> $node->field_application_school[$node->language][]['target_id']  =
> 1373;
> $node->field_application_school[$node->language][]['target_type'] =
"node";
 node_save($node);

I need to  fill the entry  for $node->field_application_school[$node->language][]['target_id'], its not working.

@jsh I'd suggest to create a test node through the admin menu (i.e. node/add/content_type) then dpm/debug the $node object in that content type template and finally view the node and look through the object's output and see where your code differs from the object constructed by Drupal.


How to change the page path being reported to Google Analytics as a pageview I would like a certain page path to be reported as a different page path, IF it has a hash on it.

/page-name#hash-name

should be reported as

/page-name/hash-name

Thing is that with the Google Analytics module I end up reporting two pageviews if I add this to custom js:

ga('send', 'pageview', '/pagename/' + window.location.hash.substr(1));

In the Google Analytics configuration (admin/config/system/google-analytics) under the collapsed fieldset "Advanced" > "Custom JavaScript code" there is a field "Code snippet (before)" where you can add javascript (pure, no jQuery).

In this case I added the following:

if(window.location.pathname === '/pagename') {
  if(window.location.hash) {
    ga('set', 'page', '/pagename/' + window.location.hash.substr(1));
  }
}

Essentially any Google Analytics variable can be pre-set or changed before the pageview fires.


Append parameter to URL accross all pages I am on Drupal 7. My website will have a country select form on the first page where users will pick one country from a list. All these countries speak the same language (Spanish), so they are basically under the same language pack. My idea is to create a Vocabulary with all the countries I need. Then, in order to guarantee consistency accross pages (allowing me to filter content when necessary), I want to append a parameter to the URL like this:

path/to/my/page?country=ur

I want this parameter to be added to all the links on the menu in my website. Drupal will read the parameter currently in the URL and will append that same parameter to all URLs on the menu.

My idea is to use Rules to catch the current country code and append that same parameter to all links on the menu, both on top of the page AND on the footer (yes, there are two menu bars). What would be the code to add those parameters to each menu link? Do I have to run the code twice in order to change URLs from both top and bottom menus, or is it possible to inject the querystring into a single resource that will be pulled to build both menus? For the menus, I am using Menu Block module.

If you have a better idea to tackle this, please, suggest. Thank you!

The best hook for this is hook_url_outbound_alter. This affects links generated by url(), which is used by most/all code generating urls and links in Drupal.

function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
  // If the param of interest is present and the url being generated is internal.
  if (!empty($_GET['country']) && !$options['external']) {
    $options['query']['country'] = $_GET['country'];
  }
}


Are db_update->condition() and db_update->where() the same? Are db_update->condition() and db_update->where() the same? If not, what are the differences?

condition() always involves a field/column name and a provided value (or an array of provided values). where() can contain arbitrary conditions (comparing fields against each other, can contain functions/expressions), it's just a string that is passed through.

condition() example, select everything where created is bigger than timestamp value.

$timestamp = 123465...;
$query->condition('created', $timestamp, '>');

where() example, select everything where changed is bigger than created.

$query->where('created < changed');

Everything that can be done with condition() can also be done with where(), but not the other way round. The following is the same as the condition() call.

$query->where('created > :timestamp', array(':timestamp' => $timestamp));

Works just fine, but is way more complicated. The basic rule is that condition() should be used whenever possible and if not, use where().


How to print the url and the filename from image field in views-view-unformatted.tpl.php in Drupal 7? I tried using this code, but it does not work.

<?php print $node->field_slider_image['und'][0]['filename']; ?>

The full file object isn't necessarily loaded into the node object, you could try loading it manually and grabbing the filename/URL that way:

$file = file_load($node->field_slider_image['und'][0]['fid']);

// Filename
print $file->filename;

// URI e.g. public://image.jpg
print $file->uri;

// URL e.g. /sites/default/files/image.jpg
print file_create_url($file->uri);


How do I shorten the length of all form input text fields? I'm using Drupal 7, for which the standard length of an input text field is 60. Is there any way to shorten this for ALL fields at once? I want all the forms on my site to be no wider than 40.

I know that hook_form_alter() can be used to do this one-by-one, but I have a rather large number of fields on my site, and I would like to edit their lengths all at once if possible.

There are a couple of things you can do depending on whether you want to do this on a theme level or site-wide level (i.e. independent of theme).

On the theme level you can override theme_textfield() and set the size there:

function MYTHEME_textfield($variables) {
  $new_size = 40;
  $variables['element']['#attributes']['size'] = $new_size;

  // EDITED per kiamlaluno's comment regarding infinite loops
  return theme_textfield(array('element' => $variables['element']));
}

On a site-wide level you can write a small module and implement hook_element_info_alter() to change the default that's provided by system_element_info():

function MYMODULE_element_info_alter(&$type) {
  $new_size = 40;
  $type['textfield']['#size'] = $new_size;
}

You'll want to clear Drupal's cache once you've implemented either of these methods to clear the relevant registry.

It's worth noting that if you use the first method any specific sizes for textfields set by other modules (e.g. size 10 for numeric fields) will be overwritten with your new size. If you use the second method that will become the default but other modules will still be able to provide a specific size for specific textfields.

EDIT

I've just had another thought on this, probably the best way is to do it is in your theme function and check the existing length. That would match your statement "I want all the forms on my site to be no wider than 40" a bit better:

function MYTHEME_textfield($variables) {
  $new_size = 40;
  if (isset($variables['element']['#attributes']['size']) && $variables['element']['#attributes']['size'] > $new_size) {
    $variables['element']['#attributes']['size'] = $new_size;
  }

  // EDITED per kiamlaluno's comment regarding infinite loops
  return theme_textfield(array('element' => $variables['element']));
}


Remove Value of dependent field I've one date field which is dependent on another field if it is checked then only date field will display and will be compulsory. Issue is that if I give value once on date field and saved that page, then I'll edit again same node and uncheck that dependent field value then it will be hide from page but the previous value of that date field is not removed from database. If anyone have an solution to remove this value on remove dependency then let me know.

Thanks in advance.

Try to use any of these modules.

Conditional Fields - This module definitely solve your issue. How to use.

  Conditional Fields allows you to manage sets of dependencies between
  fields. When a field is “dependent”, it will only be available for
  editing and displayed if the state of the “dependee” field matches the
  right condition. When editing a node (or any other entity type that
  supports fields, like users and categories), the dependent fields are
  dynamically modified with the States API.

Dependent Fields

  The Dependent Fields module (formerly AHAH Dependent Fields) allows
  cck based fields to specify another field as a controller field, and
  react to its changes on the form using AHAH/AJAX without the form
  re-loading.

Dynamic dependent fields

  Makes field value or options depend on other field values when editing
  entity.


Views to show nodes filtered by referenced user I am really confused about this. Tried with the Entity reference view but can not get the result working for me. It should be very easy to do it.
I have a node called Book. Book has a field field_author that is referenced to USER.
I am trying to show the related books by the same referenced user.
Book 1:
Title: Book 1
field_author: user50 //id of this user is 50

Book 2:
Title: Book 2
field_author: user15

Book 3:
Title: Book 3
field_author: user50

Book 4:
Title: Book 4
field_author: user50

My view should display Book 3 and Book 4 when viewing Book 1 (URL:: example.com/node/1) and display Book 1 and Book 4 when viewing Book 3 (URL:: ecample.com/node/3) and so forth.

What you want to do is often called displaying sibling items. In your case the connection is the ER user connection (not Taxonomy) but you can find examples with details about how to do it, search answers for it.
In short:

Create Views of type Book, you'll probably want Block Display, it doesn't have to be Entity reference Display type (that is for influencing choices in nodes in ER fields).
Add the Relationship for the User ER field. It should be the forwards Relationship. You can require it if you want to exclude all Books from your list that don't have the User ER filled in.
Add the second Relationship for that field, but the reverse one this time (it will be called different). Make it use the first Relationship. You can require it.
Add Contextual filter for Node ID, make it use the second Relationship (because this way you get the ID of sibling nodes) and configure it the usual way (default value ID from URL, validate Book node type) etc.
The current Book node will also be listed. To exclude it add another Contextual filter for node ID, don't make it use any Relationships, set to default value ID from URL and under "More" choose "Exclude".
Under Structure > Blocks set the Block to display in a theme region, and configure it to use Contextual options. Don't forget the Visibility settings too.

You should now see the block on Book nodes showing their siblings per shared user ER.
You can test Contextual filter when editing Views by entering values into the Preview field. If you have two Contextual filters you have to enter two values separated by "/" In your case enter a book node twice e.g. "12/12". "all/all" usually bypasses the Contextual filter results.
You still have to check that it works by placing the Block in a region at the end, to check your Contextual configuration is correct.


Ubercart Line item tax not displayed first time Im adding a line item to ubercart order at checkout validation. When at the review page I can see the line item but its not used in the tax calculation. But when i go to the review page for the second time it is.

Who can help me?

I added the line items at validate. However at that moment the tax is already calculated. What needs to happen is recalc the taxes. This can be done from a ajax call when a field changes value.

function My_Module_update_line_items($form, $form_state) {
  $commands = array();
  if (isset($form['panes']['payment']['line_items'])) {
    $commands[] = ajax_command_replace('#line-items-div', drupal_render($form['panes']['payment']['line_items']));
    $commands[] = ajax_command_prepend('#line-items-div', theme('status_messages'));
  }

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


Get user object within module I need the $user object within a module am creating. But am not able to get it. I have created a module that extends user object hold more data. Its working fine. I am also
able to use this values in theme files. But am not able to get it in any function within
a module.

The standard value $user->name; or my custom value $user->data['privacy']; nothing is available in module.

I tried using this

global $user;
$user = $user->name;

What is the mistake here? Is it that global is not the right way to get the user object?

You're currently referencing the global $user object, then in the very next line you're overwriting it with a string (the username). So your global $user object is destroyed, and you will probably be logged out of the site (as well as the code not working as expected).

You're referencing the global user object in the correct way, but by default it isn't fully loaded (i.e. with fields attached, etc). To get the extra data you should use the user_load() function like so:

global $user;

// Get the fully loaded user object
$account = user_load($user->uid);

// Get the username. Make sure you don't override the global $user object here!
$username = $account->user.

// Get a field value.
$field_items = field_get_items('user', $account, 'field_foo');


An alternative to jcarousel? Does someone know an alternative to the Jcarousel module?

I'm using it, but there is too much CSS to write. Is there some alternative more flexible to have a simple slider?

Here is the place http://drupal.org/node/418616, Provides the list of modules with similar functionality you can choose something better and as per your need,


views slideshow force al link to basic page instead of the slideshow's custom made url I am using Views Slideshow for my front page and I want the url output of the image to go to a basic page but there is a conflict because the slideshow creates a page with that image and it makes it a different page than the one it should point to.
Example: I have a slideshow image that should point to the about-us page but when creating the about us image slide it creates a new url...so I end up with one about-us page and the slideshow image points to /node/23.

I tried the image link formatter module, created the proper field in Slideshow (Content type) field_image_custom_link and linked the image to this field. And in views I set a rewrite result to output the field as a link and put [field_image_custom_link] and it will simply send the image to the url: /field_image_custom_link#overlay-context=!
Any help would be appreciated, I just want the slides to point to specific existing pages! :)

Add a field to the content type which you are using in your slideshow. Use this field to hold the URL it should point to. Then, add the field in your slideshow view and make it hidden. Now you can use that hidden field to rewrite the URL of the image in the view.


How can I know if a type of content is moderated? I'm trying to find out if a type of content (not a node) is being moderated. How can I determine it?

For example:

function MY_MODULE_form_node_type_form_alter(&$form, FormStateInterface $form_state, $form_id) {
   $content_type = $form_state->getFormObject()->getEntity(); // $content_type is a Drupal\node\Entity\NodeType
}

I can't find a way to find out if this type of content is being moderated by some type of workflow.

You should be able to get that from ModerationInformation:: shouldModerateEntitiesOfBundle(), via the content_moderation.moderation_information service:

$moderation_info = \Drupal::service('content_moderation.moderation_information');
$entity_type = \Drupal::entityTypeManager()->getDefinition('node');
if ($moderation_info->shouldModerateEntitiesOfBundle($entity_type, $content_type->id())) {
  // ...
}


How do I put a reset button on my view's exposed filters? This a really basic question, but it stumped me for a moment and there was little I could find on the net that answered this most basic need.

By default when you expose filters in a view, the only button that shows is 'Apply'.  I have seen reset buttons elsewhere on the site and on example sites but I don't know how to make it appear on my view.

How do I put a 'Reset' button on my view to reset the exposed filters?

In your view configuration go to Advanced -> EXPOSED FORM -> Exposed form style: Basic | settings.

Check 'Include reset button' and save.


What's overriding my local_settings.php? I'm using a local_settings.php file, that includes several $conf settings. All of the settings were working as expected until just recently when the mail_system setting started getting overridden somehow.

Now, if I run $ grep mail_system local_settings.php -A2, I get:

$conf['mail_system'] = array(
  'default-system' => 'DevelMailLog',
);

...yet, the output of $ drush vget mail_system is:

mail_system: Array
(
    [default-system] => DefaultMailSystem
)

I've always assumed that whatever was defined in the settings.php (or in this case the local_settings.php) would trump the same variable defined elsewhere. I've checked all the other variables I'm setting inside the $conf variable in the local_settings.php and they're set as they are in the file.

Where else might mail_system be getting set that would override the $conf definition?

Enabling the Devel module fixed the issue. Ultimately, I think the issue is specific to the Mail System module and the unusual way it handles settings and defaults.


Is there any replacement module for token actions and token starter modules in D7? I am using TokenActions and TokenStarter modules in my one of the project which is in D6.

Now, I have planned to upgrade it into D7.

I have found the D7 version of Tokens module but I didn't find Tokens Actions and Token Starter in that module.

Is that modules are removed are is it still existing in some other names?

I had googled a lot. But I didn't find anything really useful...

Coudl you guys help me out of this issue ?

From Dave..Mainter of token module... (As Received)

The Token Actions module has been replaced by the actions provided by core that support tokens. Use the follow button on http://drupal.org/node/1902294 to track progress for migrating those deprecated actions to system-provided ones automatically.

The Token starter is not an actual module that is intended to be used. It's just an example of how you make new tokens. It was deprecated by the token example module in http://drupal.org/project/examples. You should instead make a custom module with a good name for your custom tokens, rather than re-using the token starter module.


Order total field, transactions and balance In drupal commerce, using the commerce payment payment module,
I would like to display the amount paid and order balance in paid order like on the example below.

Subtotal ------------- 20
TAX --------------------- 3
Total ------------------ 23
Amount paid ----- 23
Order balance ---- 0

How could I achieve this ?
I'm close to get what I want. I created a module
I still have an issue : I don't know how to get the order_ID ?
<?php

/**
* @file
* Commerce Order Total and Balance Module.
*/

// implement hook_commerce_price_formatted_components_alter()
function commerce_order_total_and_balance_commerce_price_formatted_components_alter(&$component_types) {

// TO DO : retreive the order ID (or the order object)
$order_id = 142;

// load the order
$order = commerce_order_load($order_id);

// get the balance
$balance = commerce_payment_order_balance($order);

// rename and reorder component_type
$component_types['base_price']['title'] = 'Total HT';
$component_types['base_price']['weight'] = -90;

// rename and reorder component_type
$component_types['tax|20_vat']['weight'] = -80;

// rename and reorder component_type
$component_types['commerce_price_formatted_amount']['title'] = 'Total TTC';
$component_types['commerce_price_formatted_amount']['weight'] = -50;

if ($balance['amount'] <= 0) { // we display total payments and order balance only if order balance is zero or less
  // add component_type "total_paid"
  $component_types['total_paid']['title'] = 'Montant pay&#233;';
  $component_types['total_paid']['weight'] = -40;
  $component_types['total_paid']['price']['currency_code'] =      $component_types['commerce_price_formatted_amount']['price']['currency_code'];
  $component_types['total_paid']['price']['amount'] = $component_types['commerce_price_formatted_amount']['price']['amount']-$balance['amount'];

  // add component_type "order_balance"
  $component_types['order_balance']['title'] = 'Solde';
  $component_types['order_balance']['weight'] = -30;
  $component_types['order_balance']['price'] = $balance;
 }
}

There is no way via the user interface that I'm aware of to add lines to the order total display that lists out price components like this. However, via code you have the ability to alter the array of formatted price components however you want at the point of display.

Drupal Commerce 1.x includes hook_commerce_price_formatted_components_alter() for this, letting you alter existing rows in the components list or add some to it that wouldn't otherwise be included. You can add lines that check the payment transactions associated with an order to see how much has been paid and that use commerce_payment_order_balance() to show the balance.


Accessing product price in template.php So I am using hook_form_alter to alter the add-to-cart button for my Ubercart pages. See here:

function hook_form_alter(&$form, &$form_state, $form_id) {
  if ( !empty($form['nid']) ) {
    $node = $form['nid']['#value'];
  }
  else {
    $node = 0;
  }

  if (($form_id == 'uc_product_add_to_cart_form_'.$node) and ($form['node']['#value']->type =='product')){

    hide($form['actions']['submit']);

    $form['button'] = array(
      '#prefix' => '<button type="submit" id="edit-submit-'. $node .'" name="op" class="node-add-to-cart btn btn-cart">',
      '#suffix' => '</button>',
      '#markup' => 'Buy for: ',
      '#weight' => 1,
    );
  }
}

This works great. Except, in my form['button'] array, want to change the button markup to something like: 'Buy for: $10'.

How can I access the node's list and selling price so that I can use it in the markup of the button?

The node object is made available through the $form array in $form['node']['#value']. You can find list & sell price through the $form['node']['#value']->list_price & $form['node']['#value']->sell_price properties.


tb_blog main area left padding I'm using tb_blog theme for my website, demo site:
http://demo.themebrain.com/#blog

I want to remove the padding from left side of page without corrupting whole structure of website, I'm terrible with HTML and CSS stuff.
I want a full page expanded blog.

Also I'm open to suggestions, including totally changing my blog theme to something new which by default have a full page blog theme and it's easy to customize or tell me which CSS files to fix in tb_blog theme to make it full page blog.
Thanks

That theme is using a grid, looks like a base of 24. It's not the padding that's causing the blog to not display in the full page, but the grid (IE, the grid widths).

If your uncomfortable with updating the css of this theme, you may want to switch to a theme that's not grid based. Though it's not full page, business or something like it might be more suited to what you want to do.


Fixing a failed module install I am on Drupal 7. I was on a hosting company that would give me only 64MB of PHP Memory. That led to several issues when installing new modules. My website would run short of memory and would brake right after installing the module. But when reloading the modules page, the module would prove to be installed and working. I confess I kept on playing with fire until I finally broke the installation of one of my modules. It was Menu Blocks. The module would appear as installed, but clicking on the Configuration link on the Modules page would lead me to the wrong page. I couldn't reach the module configuration page. To make a long story short: the installation failed.

I swiched to a new host with more memory and now I am OK. But I still can't install Menu Blocks. I have tried disabling it and reenabling... Nothing. Still not working. Then I disabled AND uninstalled it. Then reinstalled. Nothing happens, still the wrong behavior for the module configuration page. What do I need to do to really and completely uninstall any problematic traces it could have left on my Drupal install? Completely delete Menu Block's tables on the database in case they still exist in there? If I completely remove those tables, do I risk breaking up my website? Completely deleting the Menu Block package, then restarting? I thought this wouldn't solve the problem... Any help appreciated, thank you!

Menu blocks doesn't alter the DB at all during the installation. It uses the 'block' and 'block_role' tables from drupal core and creates several entries in the 'variable' table to store some config.

So here's what I would do:

Check admin/reports/dblog
Install the website locally with wamp or Acquia DEV Desktop (using
the import tab and backup migrate module) if you're on windows to do
some debugging.
Check the 'menu_block_admin_settings_form' function in
menu_block.admin.inc which is called when going to
admin/config/user-interface/menu-block


How to display an add content form inside another content view page? Basically I'm looking to make a beefed-up comment system. I'd like to have a content-type B that acts as a comment like entity for content-type A.

Question: When content A is viewed, at the bottom of the page the node/add/content_type_B form should be there with a 'Save' button which will create a new piece of content. Is it possible to render the content type B add form inside the content A view page (no Panels/Display Suite please)?

With Advanced Form Block you can use a "Node add" form has a block, you could show it at the end of your node content using regions or node tpl file


How to show "New" if the node author is registered within 4 weeks. I would like to print "New" if the node author is registered within 4 weeks in a field of "node View" by using custom php with Views Custom Field. I tried the code below but didn't work. Am I missing something?

   <?php
      $four_weeks_ago = time() - (28 * 24 * 60 * 60);

      $user_created_time=$user->created;

    if ( $user_created_time >= $four_weeks_ago) {
        $this_user_is_new="new";
        print $this_user_is_new;
      }
    ?>

What if you edit Vikas code with:

$node_author = user_load($node->uid);
$author_created_time = $node_author->created;


How can I display search filters in a view? I'm working on a site in drupal 8 that uses commerce 2. I'm learning as I go with this and feel like I'm missing something on how everything fits together.

I made a view for products, and configured how products display, and used twig templates to add wrappers and classes etc. This seems to work fine, but when it comes to adding any functionality, Twig doesn't seem to be the place to do it. The config options in Drupal cover layouts and CSS classes but are very complex.

This is confusing when you need to make the markup a certain way. In my case I need to add the following in a horizontal row:

number of results found
Select dropdown to filter results by a taxonomy
Another select for different taxonomy
Free text search box

I need to then style these also so I'd really want to control the markup generated, to some degree. How would I go about implementing this in a view?

Below are some guidelines to setting up each of your requirements in a view. Worth noting, in order to display each in the same row, you'll need to customize the view template to combine the exposed filters and the results count from the view header.

Number of Results Found

In the Header section (middle column) of the View edit page, click ADD.
If your view has multiple displays, be sure to select whether to apply this to all displays in the view, or just the selected/current one in the FOR section.
Select "Result summary" and click the ADD AND CONFIGURE HEADER button.
Edit/customize your results text with the tokens. If you want to still expose the same text pattern if no results are found, check the checkbox "Display even if view has no result"
Click APPLY

Select dropdowns to filter results by a taxonomy

In the Filter Criteria section (near bottom of left column) of the View edit page, click ADD.
If your view has multiple displays, be sure to select whether to apply this to all displays in the view, or just the selected/current one in the FOR section.
Find your custom taxonomy field you wish to filter by. Note, if your field is configured to allow multiple term selection, you'll see two instances of the field listed (the field itself, and the field delta).  Pick the field itself.
Click APPLY.
If the field is setup to allow taxonomy terms from multiple taxonomies/vocabularies, select the one you wish to show/filter on. Choose the dropdown option to set the filter as a select element.
Check the checkbox to "Expose this filter to visitors, to allow them to change it"
Select the "single filter" format and update the field label to reflect the label you'd like the user to see. Keep the operator as "is one of". In the righ column, Leave the list of terms unselected to automatically show all terms in the filter.
scroll further down the form, and click the REDUCE DUPLICATES option; optionally- click the REMEMBER THE LAST SELECTION option so that users clicking a back button to return to the page will still see the previous selection.
Finally, click apply to save the filter settings.
If the Auto preview option is enabled, you should now see the select filter in the view preview below the view config section (even if there are no results).

Free text search box

To setup a free text search box, you'll need to use the "Combine fields filter"; but it can only be applied to search the fields configured in the view. (You can add fields and exclude from display).  If your view is setup to "Show Content", you'll need to click the "Settings" for the view Format and select "Force Using Fields" to add fields to the view for filtering/searching.
Add the fields for searching (title, body, etc)
In the Filter Criteria section (near bottom of left column) of the View edit page, click ADD.
If your view has multiple displays, be sure to select whether to apply this to all displays in the view, or just the selected/current one in the FOR section.
Find and select the "Combine Fields Filter" and click APPLY.
Check the checkbox to "Expose this filter to visitors, to allow them to change it"
Select the "single filter" format and update the field label to reflect the label you'd like the user to see. Change the operator to "Contains".
scroll further down the form, and click the REDUCE DUPLICATES option; optionally- click the REMEMBER THE LAST SELECTION option so that users clicking a back button to return to the page will still see the previous selection.
scroll even further down and multiselect the applicable search fields.
Finally, click apply to save the filter settings.
If the Auto preview option is enabled, you should now see the search box in the view preview below the view config section (even if there are no results).

Customizing the View Templates

Refer to the "Understanding Views Templates" and "Naming Views Templates" sections of this blog post for a high level rundown of Drupal 8 view templating.
This legacy Views Template listing for Drupal 6 & 7 gives a good rundown of all the various views component templates (view header, view footer, view exposed filters).  Most are still applicable in drupal 8, with the .tpl.php file ending swapped out as .html.twig


Drupal Multilanguage domain specific with PORT not working I have setting up drupal 7 with 2 languages:

English Default
Spanish

Also, Point 2 domains for each language from language configuration settings

www.drupal-experiment.local:90 (English)
es.drupal-experiment.local:90 (Spanish)

Setting.php
Base URL set in /sites/default/settings.php file.

  $base_url = "http://www.drupal-experiment.local:90";

Can anyone look at my configuration, where I have missed something so, Other/inner links are not getting PORT with given URL.

e.g. If I try to login it will submit data to URL without PORT number.

  http://www.drupal-experiment.local/

See attached screen-shots for configuration set for domain with PORT 90.

  Languages list

  English Language Configuration

  Spanish Language Configuration

I'm pretty confident that the reason for your issue / problem, is because Language detection by domain only works on port 80. That issue has 'some patches' attached to it', and status = Needs review.

Not sure if you want to try/consider experimenting with any of the patches in this issue though.

Something else you may want to check is your configuration at Configuration -> Languages -> detection and selection: the order specified there could be what explains the current behaviour in your site.

You'd have to experiment a bit with what the exact order in your case should be. In my experience, I often get these kind of issues to work by using an order like 'URL, Default, User', and not something like 'Default, URL, User'. So try to experiment a bit with the various combinations in this order to see if it helps.

Curious to hear if either of those options will somehow help ...


What is best way to combine multiple fields in template preprocess? I have 3 fields I want to join into one line to wrap inside some tags.  Is template.php in a preprocess function the best place to do this?  I won't need the fields after I join them, so I assume I call hide() on them as well?

I would do this using hook_node_view() or theme_preprocess_node(), but I'm not sure which is the best way.

function MYMODULE_node_view($node, $view_mode = 'full', $langcode = NULL) {
    if($view_mode == 'full'){
        if($node->type == 'your_content_type'){
            $field_1 = $node->content['your_field_1'];
            $field_2 = $node->content['your_field_2'];
            $field_3 = $node->content['your_field_3'];

            // remove individual fields
            unset($node->content['your_field_1']);
            unset($node->content['your_field_2']);
            unset($node->content['your_field_3']);

            // combine those fields in a tag
            $html = '
';
            $html .= ''.$field_1.'';
            $html .= ''.$field_2.'';
            $html .= ''.$field_3.'';
            $html .= '
';

            $node->content['combined_field'] array(
                '#markup' => $html,
                '#weight' => 1
            );
        }
    }
}

Another way is to alter these from THEME_preprocess_node() in the template.php.

function MYTHEME_preprocess_node(&$variables) {
  if ($variables['view_mode'] == 'full' && node_is_page($variables['node'])) {
    $field1 = strip_tags($variables['content']['field_1']['#markup']);
    $field2 = strip_tags($variables['content']['field_2']['#markup']);

    // remove individual fields
    unset($variables['content']['field_1']);
    unset($variables['content']['field_2']);

    // combine those fields in a tag
    $variables['content']['combined_fields'] = array(
        '#markup' => '
'.$field1.$field2.'
',
        '#weight' => 2
    );
  }
}