How can we uninstall a module directly from the database? I am trying to find a way to uninstall a Drupal 8 module directly from database.

How can I achieve this?

You can use

drush pm-uninstall.
If you have entities in your module, write a query in your module to first delete all entities of your particular entity type. Once deleted, remove that file where you have written annotation for your entity, create a backup for use later. Except .info.yml file and .install file, remove all files.

Now you can easily un-install that module. Once un-installed, put all your backed up files into your module folder again, install your module and go!


8 How to configure add-on products in Commerce 2.x What is the best way in Commerce 2.x to allow the shopper to check boxes to add optional accessories to a product before he adds the product to the cart. In addition, the product price should be updated.

Sounds like this module would do it in D7: Commerce Product Add-on.

This question asks the same question, but it's tagged with 7. Can a VBO form be integrated with the Commerce Add-to-Cart form to allow adding optional add-on products with checkboxes?

Commerce Product Add-on now has a beta release for D8.


Altering ImageField Widget with FUpload enabled I need to alter the ImageField Widget so that I can add some fields other than the Description, Alt and Title fields. I'm able to do this when I select the file field widget type as Image Uplaod, but when I select the FUpload widget type, the changes don't take effect. Here's the code I'm using:

function bridge_widgets_imagefield_extended_widget($element, $extra_values) {
  // If you need the field or widget to conditionally add a FAPI field, use these.
  $field = content_fields($element['#field_name'], $element['#type_name']);
  $widget = $field['widget'];

   if( $element['#type_name'] == 'property_gallery'  ){
  global $user;
  user_load($user);
  return array(
    //This will Replace the Textfield with dropdown select for the description
    'revise' => array(
      '#type' => 'checkbox',
      '#title' => t('Revise This Description'),
       '#default_value' => isset($extra_values['revise']) ? $extra_values['revise'] : 0,
         '#attributes'=>array('class' => 'revise-check')
       ),
    'revisedby' => array(
      '#type' => 'textfield',
      '#maxlength' => 64,
      '#title' => t('Revsied By'),
     '#default_value' => ($extra_values['revise']==0) ?  NULL : $extra_values['revisedby'] ,
       ),
       'revisedon' => array(
      '#type' => 'date',
      '#title' => t('Date'),
     '#default_value' => ($extra_values['revise']==0) ?  NULL : $extra_values['revisedon'] ,

       ),

  );
  }
}

I guess it is the line

$element['#type_name'] == 'property_gallery'

that makes your changes have/not have effect.

I would actually suggest writing a new widget alltogether, instead of altering the existing one(s). It isn't that difficult, but I don't know of any good tutorial for it online – there is a good chapter about it in the book "Drupal 7 Module Development" though, which helped me a lot.

If you find a good online tutorial, please post the link!


Where I can find examples of Drupal bootstrap levels? I recently came through some Drupal apps that I needed to send some silent Ajax requests that performs a database update, and nothing else. Every such requests bootstraps Drupal to its full level which, as far as I can see, is a waste of resources.

Where I can find examples that someone would bootstrap Drupal, but not to its full level?

One example is the statistics module in core. ./modules/statistics/statistics.php. Do you know any others?

Please note this question is not about "how to bootstrap". Rather, in trying to see some examples of applications of it.

Thanks, and hats off everyone in advance.

The JS module is specifically for this. It allows you to create ajax callback that only bootstrap to a level you specify via a hook_js().

So you could either use this module or take a look at its code to see how it works.

Good blog post about it HERE


Difference in form when first loaded and submitted When debugging commerce checkout panes, which are basically forms I see that form is loaded on page load(obviously). It is again loaded when I click submit and debugger goes through same lines of form, thing is I am not sure which marker to use to differentiate code when this occurs, I would need to do something different in this case, but only thing I see different is superglobals at this point, which I could use, but somehow I would be more comfortable using drupal local vars?

If all you want to know is whether the form is being loaded before or after a submit while debugging, then look at the array in $form_state['input']. If it is an empty array, then it is being loaded for the first time (before a submit). If it has elements then the form is being loaded after a submit.

If you want to see if field values have been changed in a submit, then how you do it depends on where or why you need to check. If debugging, then compare $form_state['input'][FIELD] with $form[FIELD]['#default_value']

You can also add your own functions as submit or validate handlers to the form. After the form is submitted, your function will be called, and you can compare the changed values in $form_state['values'][FIELD] (note: use values here, not input) to the original values in $form[FIELD]['#default_value'].

You add your submit/validate handler by implementing hook_form_FORMID_alter()for the form you are debugging, and adding the names of your functions to the end of the $form['#submit'] and $form['#validate'] arrays respectively. Remember to clear caches.

function my_module_form_other_module_form_alter(&$form, &$form_state) {
  $form['#submit'][] = 'my_module_custom_submit';
  $form['#validate'][] = 'my_module_custom_validate';
}

function my_module_custom_submit($form, &$form_state) {
  $original_field_x_value = $form['field_x']['#default_value'];
  $submitted_field_x_value = $form_state['values']['field_x'];
  if ($submitted_field_x_value != $original_field_x_value) {
    do_something();
  }
}

function my_module_custom_validate($form, &$form_state) {
  do_something();
}


Show number of pages views I am new to Drupal, so I want to know how do I echo number of views of a page ? or of a category ?

If you go your modules admin screen (/admin/modules), you'll see there's a module called Statistics that actually comes with core Drupal.  Make sure you enable it on this screen if it isn't enabled already.

This will print out page views at the bottom of your pages, but you have to make sure you visit the permissions screen to give anonymous users (if that's what you're trying to do) the ability to see that.  After the module has been enabled, you'll see the following set of permissions for your site(/admin/people/permissions):

Administer statistics
View content access statistics
View content hits

You'd just need to check the last one for whomever you want to be able to see the page views!

You can find additional information about this module on your own site's help pages: /admin/help/statistics


Meta tags on taxonomy term pages not showing(using views 3) I have installed Meta tags module, configured it, working well, but on taxonomy term pages: meta description, and meta keywords not showing. I am using Views to override taxonomy term pages. I tried to set some random words for test purproses(not even tokens), but it's still not working. Anyone encountered this problem?

I can offer next solutions:

Support of taxonomy term pages generated by views is already included in the
Metatag module since 7.x-1.0-beta2.
If you are using the Metatag module with version lower than 7.x-1.0-beta2 you can use module Meta tags term view.
Try Meta tags quick.


Drupal 8 - Use the current node ID (on node edit form) to filter an entity-reference view as a contextual filter I've got this view I just created, which lists all the events && publications related to a program (field_program, an entity-reference field) on my website (Drupal 8). Call it "view_program_related_contents".

I've got this content type (program), with a entity-reference field (field_promoted_contents). About this field, I want to use a view, because I don't want the webmaster to be able to promote events|publications related to any program but the one he's editing, so I have to filter the results based on the field_program field.

I did set a contextual filter (field_program) on my view. When this filter is not available, I fill it whith a default value : "Content ID from URL".

I can't manage to get my field_promoted_contents field populated with the well-related contents. If I set a static value (node id 1) in the contextual filter, it works, I only have the contents related to this first program. But when I set this "Content ID from URL".. I get no results :(

Do I have to pass a token (such as [node:nid]) as an argument to the view in the entity-reference field configuration ? Is there a module for that ?

This might not be THE answer.
But for my specific need, and because we already are late on this project.
I found a "quick-fix" solution.. waiting for a more drupalistic one.

Assuming that this entity-reference-1 view display is always called from a node/:nid/edit page, I should always have a HTTP_REFERER on each request to the view (I guess ^^). Well, I check that for insurance.

Inside a hook_views_pre_view hook, I pass the node-id from the HTTP_REFERER to the view, like this :

<?php

use \Drupal\node\Entity\Node;

/**
 * Implements hook_views_pre_view()
 *
 * Alter the contextual filters for my view :
 *
 * When the HTTP_REFERER is a node/:nid/edit pattern and the view-display is an entity-reference
 *  then I fetch the node ID from the URL, I load the node to check the node type
 *  and I pass this nid to the view as an arg
 */
function MYMODULE_program_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() == 'view_program_related_contents' && $display_id == 'entity_reference_1') {
    if (isset($_SERVER['HTTP_REFERER'])) {
      $referer_url = parse_url($_SERVER['HTTP_REFERER']);
      $path = htmlspecialchars($referer_url['path']);
      if (preg_match('/node\/(\d+)\/edit/', $path, $matches)) {
        $node = Node::load($matches[1]);
        if ($node instanceof Node) {
          if ($node->getType() == 'program') {
            $args[] = $node->id();
          }
        }
      }
    }
  }
}

Again, I think I'm missing something in my entity-reference field definition, or my view configuration.. but I don't have enough time to spend on this.

I hope this helps..


Showing different nodes for same taxonomy terms on different URLs I'm facing this design issue regularly.

For example I've Jobs and Company node types. Both have one common taxonomy term reference field City.

Now when we go to a City term it will show both Jobs and Companies(I don't want this mixing).

I want that it show only Jobs or Companies(in different URL's)

One solution is to duplicate City vocabulary as City Jobs and second as City Companies.  Now I get what I want. But in programming it'll complicate as same city in both Vocabularies will have different term id's.

What is the best way to achieve this?

You can use the Views module to create two different pages:

"Jobs in City %1" at /jobs/%
"Companies in City %1" /companies/%

Your Views will need a filter for content type, and a contextual filter for taxonomy term.  Next, use the Rabbit hole module to make the /taxonomy/term/NNN pages disappear.


How to avoid duplicate pages? Assume the following. We have a taxonomic vocabulary called product. Which contains two terms: tables and chairs. This taxonomy creates the following URL's:

http://www.mydomain.me/product/tables
http://www.mydomain.me/product/chairs

Taxonomy Menu module to create a menu that taxonomy. If we click the Tables menu item leads to http://www.mydomain.me/product/tables. Which shows a list of all published tables. Same with the chairs.

All right. But we want to customize this list, so we to use Views. Views creates the following two pages:

http://www.mydomain.me/product-2/tables
http://www.mydomain.me/product-2/chairs

Here is my problem. How do we make the taxonomic menu leads us to pages created with Views?

Currently I get this by changing the URL's menu with jQuery. But this may not be the best way.

Does anyone know how to deal with this duplicity of pages (taxonomy page, and Views page)?

Greetings!

Here is what I would do:

1) Create a view BLOCK instead of page.

2) Go to manage display of your taxonomy page and disable all fields (you should have an empty page now).

3) In blocks, grab your view name block and put it under content area.

Select Display Only In.

In the text box, put: product/*  (so it will display the view in all /product pages).


Prevent form regeneration when a callback function is called through ajax Here is the code for the custom form with a field(field_B) that calls an  function through ajax.

The issue is that I want the function (MY_MODULE_XYZ_function()) to be executed only once, when the page loads for the first time. But the function(MY_MODULE_XYZ_function()) is being executed for each ajax call through field_B because the whole form is being regenerated.

How can I prevent whole form regeneration(so that the function won't be called more than once) for each ajax call? Thanks in advance.

function MY_MODULE_menu(){
    $items['abcd/xyz'] = array(
        'title' => 'ABCD',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('xyz_custom_form'),
        'access arguments' => array('access content'),
        'type' => MENU_CALLBACK,
    );
    return $items;
}

function xyz_custom_form($form, &$form_state){

    MY_MODULE_XYZ_function($arg1, $arg2);

    $form['field_A'] = array(  .... );

    $form['field_B'] = array(
        '#type' => 'radios',
        '#options' => array("a"=>"A", "b"=>"B", "c"=>"C"),
        '#prefix' => "
",
        '#suffix' => "
",
        '#ajax' => array(
        'callback' => 'MY_MODULE_custom_ajax_callback',
            'wrapper' => 'customDiv',
            'progress' => array( 'type' => 'throbber', 'message' => NULL),
            'effect' => 'fade',
        ),
    );
}

function MY_MODULE_XYZ_function($arg1, $arg2){
    //Some Query Execution
}

function MY_MODULE_custom_ajax_callback($form, &$form_state){
    //Some Callback code
}

If you need a entity (which could be a node) to be created whenever the form is loaded, can create the enitiy, and pass it to your form, rather than creating it within your form. Then you can also use the same form for editing the entity.

For example, in a module called nodeform:

function nodeform_menu() {
  $menu['nodeform/add'] = [
    'title' => 'Nodeform add',
    'page callback' => 'nodeform_add_page',
    'access arguments' => ['some_create_permission'],
  ];

  // Note: using %node will call node_load(), passing it
  // the value given in that index of the path. If no node
  // is loaded, or the user does not have access, a page
  // not found error is returned (or maybe access denied)
  $menu['nodeform/%node'] = [
    'title' => 'Nodeform add',
    'page callback' => 'nodeform_edit_page',
    // The page argument is the 1st index of the path
    // which is %node. So the page argument will be a
    // node object.
    'page arguments' => [1],
    'access arguments' => ['some_edit_permission'],
  ];

  return $menu;
}

function nodeform_add_page() {
  global $user;

  $node = (object) array(
    'uid' => $user->uid,
    'name' => isset($user->name) ? $user->name : '',
    'title' => t('Default title'),
    'type' => 'some_node_type',
    'language' => LANGUAGE_NONE,
  );

  return [
    '#prefix' => '
',
    '#suffix' => '
',
    'form' => drupal_get_form('nodeform_default_form', $node),
  ];
}

// The edit page receives a loaded node as its argument:
function nodeform_edit_page(array $node) {
  return [
    '#prefix' => '
',
    '#suffix' => '
',
    'form' => drupal_get_form('nodeform_default_form', $node),
  ];
}

// The form then receives a node:
function nodeform_default_form($form, $form_state, $node) {
  // Get the node from the form state if it exists, or use
  // the node passed to the form if it does not.
  $node = isset($form_state['nodeform_node']) ? $form_state['nodeform_node'] : $node;
  // Save the nodeform to the node
  $form_state['nodeform_node'] = $node;

  // Add your form elements:
  $form['title'] = [
    '#title' => t('Title'),
    '#type' => 'textfield',
    '#default_value' => $node->title,
  ];

  return $form;
}

function nodeform_default_form_submit($form, $form_state) {
  $node = &$form_state['nodeform_node'];
  $node->title = $form_state['values']['title'];
  node_save($node);
}

You may not need all of the above example, but if you look at the nodeform/add menu path, it shows how you can always create a node when the form is called, and it will only happen once, rather than every time the form is built. If you don't need to use it in the form, then call node_save() on the node in node_add_page().


Is it possible to display more than one node in a page? I am trying to display two nodes in Drupalgap.

//page_callback
function tung_intro_page() {
  var display_page = '' + '

';
  display_page += '

' + '';
  return display_page;
}

function tung_intro_pageshow() {
//  drupalgap_alert('My pageshow event has been called!');
 try{
        var nid = 13;
        node_load(nid, {
        success:function(node){
         var title = node.title;
         var content = node.content;
         //var whole = html(title) + html(content);
         $('#' + 'my_node_' + nid).html(content).trigger('create');
          }
        });
        nid = 3;
        node_load(nid, {
        success:function(node){
         var title = node.title;
         var content = node.content;
         $('#' + 'my_node_' + nid).html(content).trigger('create');
          }
        });
  }
  catch (error) { console.log('tung_intro_pageshow - ' + error); }
}

This only shows the content of the last node. How can I show both the nodes?

From our comment conversation...

Try this in your pageshow handler:

function tung_intro_pageshow() {

  // Load the fist node and inject it.
  var nid = 13;
  node_load(nid, {
    success:function(node) {

      var title = node.title;
      var content = node.content;
      $('#' + 'my_node_' + nid).html(content).trigger('create');

      // Load the second node node and inject it.
      nid = 3;
      node_load(nid, {
          success:function(node){

            var title = node.title;
            var content = node.content;
            $('#' + 'my_node_' + nid).html(content).trigger('create');

          }
      });

    }
  });
}

Not the most elegant solution, but a workaround nonetheless. A more ideal solution is dependent on the outcome of this: https://www.drupal.org/node/2601764


Users can import youtube video In my website project, users can import youtube video via youtube url into their profile.

But I've no idea which module can do this.

Thanks for your help !

Install media_youtube. Add a field to user profiles of this type.


how i create panels with custom tag like header, section footer etc..? My designs contain custom tags like ,
 and ,
how can I create panels with these tags and put in it many of panels nested?

I am not sure it will be the correct answer. However my opinion is the following.
From the code you have specified it looks that you want to make your entire website with panels. (Remember with Panels you design only the node section of the website).

So you may want to consider  Panels Everywhere Module.
After Quick research I've just discovered that there is a new Theme AT Panels Everywhere.
It is a Subtheme of Adaptive Themes - the best Drupal responsive theme (it is my opinion and I use it on every project).

I think you should invest some time learning Panels, Panels Everywhere and Adaptive theme, it will certainly pay for the efforts!

Best regards!


Content type with buttons such as "I'm going here" and "I have been here" Is there a way to have a content type for a location (I've already set up the map part) so users can click a link and say whether they've been there or not and it will show on their profile as 'places visited' and 'places planning on going'.

Thanks

I would take a look at the Flag module for this.  We have used this module for similar purposes with good results.

You should be able to set up “I'm going here” and “I have been here” as different "flags", and then enable these flags on the content types you need.  This particular module integrates nicely with Views, Actions, and other Drupal mechanisms.


Making content and functions maintainable in the long run I've been playing around with drupal for a couple of weeks now and one subsisting doubt remains in my mind: what is the correct, 'Drupal' way to add your custom content? For basic text and links, a WYSIWYG editor that I've downloaded seems to be only about adequate (as it is a bit sluggish).

Because I want to extend website functionalities, like user input, I've been using .tpl.php files to modify content on specific nodes/blocks. For example, in some arbitrary file along the lines ofmytheme/templates/page--block--5.tpl.php there is code that prints to that page, like so

<?php print render($page['content']); ?>
<div>
<?php my code here... ?>
</div>

But this isn't great for the future of this project as it's essentially hard-coding. Given that I will probably one day have several people uploading content or pass it on to a different admin, what's the right way to add more advanced features for maintainability?

I'm not quite sure what you mean.

Block content can be held in the DB. .tpl.php files are as the name suggests used for templates. E.g. block.tpl.php is the template for all blocks.

If you have 2 distinct type of template for blocks then you could certainly create a block-alternate.tpl.php but there is certainly no need to create specific templates per block.

If you want to alter user input then add fields to your custom content types, or maybe look at the Webform module.


How to create template file for specific node? As I asked above is it possible to create template file for specific node id.
I now we can create template file for content type, but not clear for node id.

E.g. Suppose there are 10 Articles in website, each has node id from 1-10.
Now question is I want to create template file for node id 3. When user visit article node id 4, then user will see different page.

In Drupal 7, you can use node--[node-id].tpl.php for theming specific nodes. In your case, you can use node--3.tpl.php.


Parent node does not update when updating referenced entity child node I have a node type called page which references a node type called slider. I am using the Drupal 8 rest module to make updates to content.

I make a PATCH request to update the slider content and it says the content had been updated. When I view the slider content I can see the updated version all good but when I view the page (which renders the reference entity) it is still showing the older revision of the slider.

When I update the page by saving it to sending a PATCH to update the page then it shows the most recent version.

Is there a way to update a entity reference field (slider in this case) and also have the parent (page) also auto update with the changes?

When the referenced child node is updated in the database this triggers automatically a cache invalidation.

In this case there are three theming levels, page, parent node and child node. They all need to be invalidated when an entity involved gets updated.

But this only works when they are tagged properly. You only need to have the children tagged, because tags bubble up to the parent.

For debugging check the response header X-Drupal-Cache-Tags. To enable this header copy sites/default/default.services.yml to services.ymland set:

  # Cacheability debugging:
  #
  # Responses with cacheability metadata (CacheableResponseInterface instances)
  # get X-Drupal-Cache-Tags and X-Drupal-Cache-Contexts headers.
  #
  # For more information about debugging cacheable responses, see
  # https://www.drupal.org/developing/api/8/response/cacheable-response-interface
  #
  # Not recommended in production environments
  # @default false
  http.response.debug_cacheability_headers: true

Now you can check the response headers in the browser debugging tools and see which cache tags are missing in the page.


How to perform a webform_submission query with a conditional based on a custom field in the submission data I'm attempting to query all webforms with a specific id, and sorted by a boolean field that was added to a webform by me in the webform configuration manager.
Below is my attempt

    $submission_ids = \Drupal::entityQuery('webform_submission')
        ->condition('webform_id', $webform_id)
        ->exists('paid')
        ->sort('paid', 'desc')
        ->sort('created', 'desc')
        ->pager(50)
        ->execute();

However when I perform this query I get

  Drupal\Core\Entity\Query\QueryException: 'paid' not found in
  Drupal\Core\Entity\Query\Sql\Tables->ensureEntityTable() (line 316 of
  core/lib/Drupal/Core/Entity/Query/Sql/Tables.php).

If I omit the ->sort('paid','desc'), but keep the ->sort('created', 'desc') the query works fine. I'm assuming this is because created is one of the base fields defined in the webform entity.

I also tried using 'field.paid', and 'data.paid' as a guess but I ended up with

  Call to a member function getColumns() on boolean in /var/www/aaep.org/http/web/core/lib/Drupal/Core/Entity/Query/Sql/Tables.php
  on line 228

Is there a way to sort webform submissions by user defined fields in an entity query?

You first need to select the Submission IDs (SIDs) from the table webform_submission_data:

$select = \Drupal::service('database')
  ->select('webform_submission_data', 'wsd')
  ->fields('wsd', array('sid'))
  ->orderBy('wsd.sid', 'DESC')
  ->condition('wsd.webform_id', $webform_id, '=')
  ->condition('wsd.name', 'paid', '=')
  ->condition('wsd.value', 1, '=')// Not sure how your BOOL value is saved
  ->execute();

// Get all the results.
$results = $select->fetchAll(\PDO::FETCH_COLUMN);

Then you need to use entity_load_multiple() or similar to load the entities:

if (count($results) >= 1) {
  $submissions = \Drupal::entityTypeManager()
    ->getStorage('webform_submission')
    ->loadMultiple($results);

  foreach ($submissions as $submission) {
    // Do something
  }
}

Drupal.org thread Reference for basis of my answer.


How to output variables from a multi-value field into html on a node tpl overrride I have overridden my node tpl page and want to output variables from a field into html. The field is called: "Features Ticked"

I understand that this php code will output the information:

<?php print render($content['field_features_ticked']) ?>

I see the variables are all visible with css tags around them.

Is this the only way I can outpout this information as I want to strip the html tags, how do I do that?

I want to just output row by row then use html within the tpl file.

At the moment I get all these classes:

Features/Ticked:&nbsp;

Text 1

Text 2

Text 3

What I want to do it output just:

Text 1
Text 2
Text 3

Then wrap my own html around it.. I think I can override the field.tpl.php file to remove the classes, but I don't know how to output each line of text using php in 3 separate lines of code.

I thought i was something like:

<?php print render($content['field_features_ticked'][1]) ?>
<?php print render($content['field_features_ticked'][2]) ?>
<?php print render($content['field_features_ticked'][3]) ?>

But my knowledge of php kind of end there!

What you can do is to overwrite the field template.

To do that go and copy the field.tpl.php from core and rename it to field--features-ticked.tpl.php, and put it in your theme.

Then you can remove all the useless div's and classes.

EDIT : How to output the list items individually.

Let's say you have the array $content['field_features_ticked'], you can do like this.

  <?php foreach($content['field_features_ticked'] as $item) ?>

<?php print $item; ?>

  <?php endforeach; ?>

This will create an unordered list, then loop through all the list items and print them out one by one.

NOTE: If you can't print out $item, you might do like this.

<?php print $item[LANGUAGE_NONE][0]['value']; ?>

Hope that is helps you out.


Image style doesn't rebuild after image style flushed I have practically the same problem as here : https://drupal.org/node/2187443

I've flushed my image style because I edited this image style. Now when I reload the page where the image style should be shown they are missing (404).

What did I missed? shouldn't it be recreated automatically when styles are removed ?

Edit :

I found that images couldn't regenerate if 404 error isn't managed by Drupal. I think its very possible, then I made a change in to my .htaccess file to make Drupal manage 404 errors.

I am now getting the 403 error upon all my files, that are still not loading. :(

Failed to load resource: the server responded with a status of 403 (Forbidden)

Then I add +w on my files directory recursively to make sure the writing permission available for all to avoid 403 but nothing happens.

Problem solved!!!

After checking that Drupal manages itself 404 errors by checking .htaccess file :

# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php

I had to put this line into my settings.php... This is in the Drupal 7.20 release notes :

$conf['image_allow_insecure_derivatives'] = TRUE;

This thread saved my day.

Wish helps others.


How do I get a list of all taxonomy terms assigned to a node (or any entity)? What's the best way to get all taxonomy terms assigned to a node?

Should one use the taxonomy_index table?

Should one iterate through the fields on the node object?

I saw some answers for Drupal 7, but not for Drupal 8.

One way to do it is to iterate through each field and check if it's an entity_reference field with target type taxonomy_term, then extract the data you need.

$terms = [];

foreach ($node->getFields() as $key => $field) {
  if ($field->getFieldDefinition()->getType() == 'entity_reference') {
    $targetType = $field->getFieldDefinition()
      ->getItemDefinition()
      ->getSetting('target_type');
    if ($targetType == 'taxonomy_term') {
      $new_terms = array_map(function (\Drupal\taxonomy\TermInterface $term) {
        return $term->label();
      }, $field->referencedEntities());
      $terms = array_merge($terms, $new_terms);
    }
  }
}

One advantage to this approach is it will work with any fieldable entity type.


Allow user to pick a number with each taxonomy term Example:
I have several vocabularies each one representing animals:
First vocab: Dogs (child terms are breeds)
Second vocab: Cats (child terms are breeds)

So user for example has 6 golden retrievers, and he picks the term "Golden retriever". Now he should be able to pick how many he has, so i need a number to pick next to each term.

Is this possible ?

Typical Field Collection case.

Have fun !


Drupal Add Javascript type=text/javascript I am trying to add javascript to my page and use type="text/javascript" however when I include the following it just encloses it in script tags. How can I fix this? Also, how can I add the type="text/javascript to external files (see the second example)

drupal_add_js("$(document).ready(function() {
    // Infinite Ajax Scroll configuration
    jQuery.ias({
        container : '#itemcontainer',
        item: '.dealstable',
        pagination: '.nav',
        next: '.nav a',
    });
    });",'inline');

Here is the second example:

drupal_add_js('http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js','external');

UPDATE:
As suggested by the comments I tried the following:

$js = "(function($) {
    jQuery.ias({
        container : '#itemcontainer',
        item: '.dealstable',
        pagination: '.nav',
        next: '.nav a',
    });
    };
})
(jQuery)";
drupal_add_js($js, array('type' => 'inline','scope'=>'footer'));

But that resulted in the following HTML:

<script>(function($) {
    jQuery.ias({
        container : '#itemcontainer',
        item: '.dealstable',
        pagination: '.nav',
        next: '.nav a',
    });
    };
})
(jQuery)</script>

you can use

$js = "(function($) {

    };
})
(jQuery)";
drupal_add_js($js, array('type' => 'inline','scope'=>'footer'));

OR

drupal_add_js("(function($) {
$(document).ready(function(){
    $('.mobile-navigation').click(function(){

     });
    });
})
(jQuery)","inline");

OR

drupal_add_js('sites/all/themes/dawn/js/skrollr.js', array('scope'=>'footer'));
drupal_add_js(drupal_get_path('module', 'module name') . '/js/name.js');


Commerce- How to add a product image on a product display to the shopping cart summary view I have two products on my site that are named similarly but easily distinguished by their images.  Users sometimes buy the wrong one by mistake, so I want to put the product image on the Shopping cart summary view.  By default, this view can be used to add fields of products.

My product images, however, are on the Product display content type.  Though the Product display has a product reference to Products, there seems to be no way to get the reverse of that relationship (in other words, to get the Product Display from the Product).

There aren't too many products, so I thought about just adding an image field to Product as well and duplicating all the data, but that is definitely a maintenance problem down the line.  Is there a way to get the image on the Product Display with just the Product in Views without duplicating data?

You should be able to do it by adding two relationships. First add Commerce Line item: Referenced products

and then that allows you to add Commerce Product: Referencing Node.

From there you should be able to add and reference fields from your display node.


Can I prepopulate an exposed filter text field? I want to get some value from session and put it into one of the exposed filter text fields of my view as default. Later the user can change the value and filter again.

Is there any way to do it? My session variable will be taken with:

<?php return $_SESSION['ip_geoloc']['location']['city']; ?>

You can use hook_form_alter and can give your session value as the default value of the exposed text field

The following code will help you

function MODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "views_exposed_form" && $form['#id'] == "views-exposed-form-XXXXXXXX") {

    $form['#after_build'][] = 'some_function';

 }
}

function some_function($form, &$form_state) {

 $default_value=$_SESSION['ip_geoloc']['location']['city'];
 $form['xxxxxx']['#default_value']=$default_value;

  return $form;
}


How to use preprocess function for custom templates defined in hook_theme? I have a custom module that i've created and I have set the theme template like this:

/**
 * Implemtnation of hook_theme()
 */
function custom_slider_theme($existing, $type, $theme, $path) {
    return array(
        'custom_slider' => array(
            'variables' => array('nodes' => NULL),
            'template' => 'custom_slider',
        ),
    );
}

This is all working fine.

What I can't find is how to load a css file for that template so when custom_slider.tpl.php is loaded the relevent css file is loaded. I don't need that css loaded on every page. I would rather call drupal_add_css() only when it's needed.

I used below approach, but it's not working.

function ModuleName_preprocess_TemplateName(&$vars) {
      drupal_add_css(drupal_get_path('module', 'custom_slider') . '/file.css');
    }

Also I added

'preprocess functions' =>array('ModuleName_preprocess_TemplateName'),

in hook_theme, where I defined my templates, kindly suggest the right way to do it.

Any help with this is very much appreciated.

Drupal will automatically call hook_preprocess_[template] for each template defined in hook_theme.

e.g:

MODULE_preprocess_custom_slider(&$variables){}

Should be called by default. If not, then clear your cache to be sure the preprocess function is registered.

Fun fact is preprocess functions are called for theme functions as well, e.g theme_item_list calls hook_preprocess_item_list prior to rendering.


Access callback infinite loop in specific case I need to limit node creation to one item for a specific content_type (photography contest), and to redirect the user to its photography if he already posted one. The snippet below is almost working as expected.

function mymodule_menu_alter(&$items) {
  $items['node/add/slide']['access callback'] = '_mymodule_limit_slide';
}

function _mymodule_limit_slide () {
  global $user;
  if(user_access("create slide content")) {
    $allowed_limit = variable_get('allowed_limit', 1);
    $slides = db_query("SELECT nid, count(*) ct FROM {node} WHERE type = :type AND uid = :uid", array(':type' => 'slide' ,':uid' => $user->uid))->fetchAssoc();
    if ($slides['ct'] < $allowed_limit || in_array('administrator', $user->roles)) {
      return TRUE;
    }
    else {
      drupal_set_message('You cannot post more than one photography. But you can edit the one you posted below if yo wish to.');
      drupal_goto(drupal_get_path_alias('node/'.$slides['nid']));
    }
  }
  return FALSE;
}

If I dpm(slides), it returns the correct array and data.

But, as far as I could debug, if I try to connect a user who :

already posted at least one node of other content type
whether he posted or not a slide

Drupal tries to go to node/'.$slides['nid'] and that creates an infinite loop.

Summary : I don't understand why my function _mymodule_limit_slide () would be called out of node/add/slide url, or what else is wrong ?

I think if you add the access login in the form_alter, the user should be redirected properly. IOW something like this:

function yourmodule_form_alter(&$form, $form_state, $form_id) {  if($form_id == 'CONTENT-TYPE_node_form') {  global $user;
  if(user_access("create slide content")) {
    $allowed_limit = variable_get('allowed_limit', 1);
    $slides = db_query("SELECT nid, count(*) ct FROM {node} WHERE type = :type AND uid = :uid", array(':type' => 'slide' ,':uid' => $user->uid))->fetchAssoc();
    if ($slides['ct'] < $allowed_limit || in_array('administrator', $user->roles)) {
      return TRUE;
    }
    else {
      drupal_set_message('You cannot post more than one photography. But you can edit the one you posted below if yo wish to.');
      drupal_goto(drupal_get_path_alias('node/'.$slides['nid']));
    }
  }
}


How to programmatically set node alias on node save I need to set a special path alias for nodes created by users in the template.php file of my theme. the pathauto module is enabled.
I already tried the solutions that are given in the following links

Create path alias programatically when node is created
How To Set Node Path/Alias Programatically
Programmatically set path alias

But none of them worked. Here is a few codes I tried but I failed.

function THEME_nodeapi(&$node, $op, $a3=NULL, $a4=NULL){
    if($node->type == "image"){
        switch ($op){
            case "insert":
                $default_node_path = 'node/'.$node->nid;
                $alternate_url = "SOME SPECIAL PATH";
                path_set_alias($default_node_path, $alternate_url, 0, '');
                break;
        }
    }
}

or this one

function THEME_insert($node){
    $path = "SOME SPECIAL PATH";
    $node->path = array('alias' => $path, 'pathauto' => FALSE);
}

function THEME_node_insert($node){
    $path = "SOME SPECIAL PATH";
    $node->path = array('alias' => $path, 'pathauto' => FALSE);
}

or

function THEME_nodeapi(&$node, $op, $a3=NULL, $a4=NULL){
    if($node->type == "image"){
        switch ($op){
            case "insert":
                $node->path = t("SOME SPECIAL PATH");
                break;
        }
    }
}

How can I do set path alias programmatically ?

UPDATE

I tried this code that recommended by @Ajit S and it didn't work again

<?php
    function THEME_node_insert($node){
        $alias = "arar/".$node->nid;
        $lang_code = "en";
        $path = array(
          'source' => "node/{$node->nid}",
          'alias' => $alias,  // Any alias that you want to set.
          'language' => $lang_code,  // Optional, if you are working on a multilingual site.
        );
        path_save($path);
    }

Path alias could be set using the path module in the core. Just call path_save the following from a function (or hook) of your choice. In your case I'd recommend you to implement the following code in hook_node_insert, because it is called after a node has been saved, and the node will have a valid nid.

// Assuming you have a $node object already.
$path = array(
  'source' => "node/{$node->nid}",
  'alias' => $alias,  // Any alias that you want to set.
  'language' => $lang_code,  // Optional, if you are working on a multilingual site.
);
path_save($path);

If you have global redirect set, the node page will be redirected to the alias.


Wrong caching of embedded views block I am having trouble with the Cache API in Drupal 8.
I embedded a views block with pagination through a field preprocess function into a node. When caching is off, I can normally use the pager and will always get the right results, but once caching is one, every block page (e.g. /node/1?page=2) shows the same block content rendering the pager useless.

I assume my hacky method is preventing the node cache to let the view in the field handle it's own caching, hence I always get the content from the page I visited first after clearing cache.

This is how the view is embedded:

function foo_preprocess_field(&$variables) {
  $field_name = $variables['field_name'];

  if($field_name === 'bar'){
      foreach ($variables['items'] as &$item) {
        $item['content'] = views_embed_view($item['content']['#markup']);
      }
   }
}

I think you need to add the pager context to item #cache


Verify a field is not empty What is the best method to check if a field is empty in a node template.

In node--example.html.twig we can use "content" variable.

I can't use check like checking a block

{% if content.field_example  %}

I can use something like this:

{% if content.field_example['#object'] is defined  %}

But what is the best method?

Like I also wrote in How can you render fields from an entity reference in node templates? [Drupal 8], content is a render array that contains data prepared for displaying.

If you want to check or compare something, use the values instead, which are available on the node object.

{% if node.field_example.value %}.

Note that the property depends on the field type. If it's a reference field, you need to use target_id instead. The referenced question links to a entity field API cheat sheet that lists common field types and their properties.


how to show node title when mouseover on image in the node by drupal views? I have a content type in which there is a cck image field and now I have listed the images with the node title as a block by views.

Now I want to show the node title when user mouseovers the image. I think I can implement it by views itself but I don't know how to do it?.

Can anyone help?

I don't think you can do that using views. However you can "hack" a way to add title element to a div, for instance.

go to your view config page

add a node: title field.

edit the node: title field.

tick "Exclude from display" and "strip HTML tags"

click save

move the title node to top of the fields.

edit your image field and tick "Rewrite the output of this field"

a textarea appears. write this code in the textarea

[image]

Note: the [fields] are tokens. If you already have a title field, you don't need to exlude it, you can re-use it.

if the image displays another title its because the module automatically sets a title tag to the image. You can either change this tag with javascript:

document.getElementById("idElement").setAttribute("Title", "title");

or edit your image module and set the page title to be your title tag.


Template override doesn't work I am trying to develop a Drupal 8 module in which I have to override the html.html.twig template. The idea is that I do not want any of the default html.html.twig template returned instead I only want the custom template returned. I have been spending hours Google hunting and trying to make sense of the many examples and I have gotten myself totally confused.

What is happening is the content of my custom template are being displayed in the default html template so I am seeing the custom content inside the default html template rather than overriding the default content.

For the sake of getting this template override working I have simplified the module as much as possible and simply want to return the contents of a variable into a placeholder in the twig template. Once this override is working I can go back and add the code that will create the correct content to be output into a number of variables in the template.

What I do not understand is exactly how to I override the html.html.twig template.

My module is called unsw_blocks and in the unsw_blocks.module I have the following

function unsw_blocks_theme() {

$theme = [
'unsw_blocks' => [
     'variables' => ['test_var' => NULL],
    ],
];

return $theme;
}

In the Unsw_blocksController.php have the following

class Unsw_blocksController extends ControllerBase {

  public function unsw_blocks($name) {
  return [
    '#theme' => 'unsw_blocks',
    '#test_var' => $this->t('The variable called test_var simply passes this text itself to the theme template'),
  ];
  }
}

In the custom modules templates directory I have unsw-blocks.html.twig which simply contains

Testing Template

test_var: {{ test_var }}

HI please follow the below steps.

Step 1: create routing
docroot\modules\custom\product\product.routing.yml

product.custom_form:
  path: '/product/details/{product}'
  defaults:
    _controller: '\Drupal\product\Controller\ProductDetailsController::details'
    _title: 'Product Details'
  requirements:
    _permission: 'access content'
  options:
    parameters:
      product:
        type: entity:node

Step 2: create controller ProductDetailsController.php

docroot\modules\custom\product\src\Controller\ProductDetailsController.php

/**
   * Callback for route product.custom_form.
   */
  public function details($product)

return [
  '#theme' => 'product-details',
  '#content' => [
    '#contextual_links' => [
      'node' => [
        'route_parameters' => ['node' => $product->id()],
      ],
    ],
  ],
  '#product' => $product,

];

}

Step 3:

In theme
create file product-details.html.twig

docroot\themes\custom\mytheme\templates\product-details.html.twig

Sample code of above twig file:

        {{ product.title.value }}
        {{ title_suffix }}

            {% if product.field_title_description %}
                {{ product.field_title_description.value }}
            {% endif %}


Drupal change the number of items in view PHP I have a view page that show 10 elements. The idea is to make three buttons for the user to select if he wants to display 10 elements, 20 elements or 30 elements in the view page. Is there any way to do in PHP? I have search in Google but I can't find anything.

I know I can change in the View config -> Pager:

insert HTML markup on the View header and make three buttons with HTML markup and then link each of the button like

10 elements

20 elements

30 elements

After this you can style the button however you want.


How to use custom tables in Views I have multisite DRUPAL6.26 website using VIEWS 3.0 module in it.

Both sites are install in single DB.
The first/parent site has no prefix for its tables.EX: node,block,role etc..
The second/childsite has prefix of child. EX: child_node,child_block,child_role etc..

I have a VIEW showing all pictures uploaded by user in there PARENT site account.
And the same VIEW for CHILD site showing pictures that they upload on CHILD site.

What I want is to show all pictures in PARENT site account of user whether they upload on PARENT site OR CHILD site.
[users are shared between the 2 sites.]

Any help of 'views master' required :)

There's a hook for exposing custom fields to Views: hook_views_data()

  Describe table structure to Views.

  This hook should be placed in MODULENAME.views.inc and it will be auto-loaded. This must either be in the same directory as the .module file or in a subdirectory named 'includes'.

  The full documentation for this hook is in the advanced help.

The link also includes example code.


Detect if its first time that user accesses the page How can I detect if users access a page for the first time? I want to redirect them to their language using GeoIP.

For authenticated users you can use a table where you write a record for each user who visits a page; in the case there isn't a record for the currently logged-in user, you create the record, and then redirect the user.

For the anonymous users, you can register the IP from which they connect, and remove the record after X hours, as the same IP can be used from different users, especially from users with a dynamic IP.


Rules: How to check one field against same field on all other nodes of that contenttype? Using Rules I would like to check the values of some fields.

I have a content type 'A' which has a custom field called 'address'. All nodes of content type 'A' are imported through Feeds.

I would like to create a rule where each node that is imported is checked, to verify if the value of field 'address' is equal to the value of field 'address' on any of my other nodes of type A.

I have read about 'Entity has field' as a Rules Condition. However I understand that this only checks several fields in the same node, while I want to check one field against all other nodes.

How can I accomplish this with Rules or any other method?

You can make this work by using Rules in combination with the Views Bulk Operations module, as further detailed below.

In what follows, I'm assuming that the machine name of your field is field_address (change to whatever fits).

Step 1 - Create a VBO view

Use the Views Bulk Operations (VBO) module to create a view of all relevant nodes, in which you should:

Add a VBO field to it.
Add a contextual filter for the field_address field for which you want to check that its value is unique. Make sure to correctly configure this contextual filter, similar to what is mentioned in this answer to "How to have a field that counts the nodes submitted by the current user?" (credits to Niall Murphy, merci!).

Include a field like nid for each node (no need for any other fields). Just make sure you get exactly 1 row for each node you want to take into consideration.

Here is an export of such VBO view:

$view = new view();
$view->name = 'relevant_nodes';
$view->description = 'Produce a list of node ids that satisfy a specific filter';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Relevant nodes';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Relevant nodes';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Field: Content: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Address */
$handler->display->display_options['fields']['field_address']['id'] = 'field_address';
$handler->display->display_options['fields']['field_address']['table'] = 'field_data_field_address';
$handler->display->display_options['fields']['field_address']['field'] = 'field_address';
/* Field: Bulk operations: Content */
$handler->display->display_options['fields']['views_bulk_operations']['id'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['table'] = 'node';
$handler->display->display_options['fields']['views_bulk_operations']['field'] = 'views_bulk_operations';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['display_type'] = '0';
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['enable_select_all_pages'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['row_clickable'] = 1;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['force_single'] = 0;
$handler->display->display_options['fields']['views_bulk_operations']['vbo_settings']['entity_load_capacity'] = '10';
/* Contextual filter: Content: Address (field_address) */
$handler->display->display_options['arguments']['field_address_value']['id'] = 'field_address_value';
$handler->display->display_options['arguments']['field_address_value']['table'] = 'field_data_field_address';
$handler->display->display_options['arguments']['field_address_value']['field'] = 'field_address_value';
$handler->display->display_options['arguments']['field_address_value']['default_action'] = 'default';
$handler->display->display_options['arguments']['field_address_value']['default_argument_type'] = 'raw';
$handler->display->display_options['arguments']['field_address_value']['default_argument_options']['index'] = '0';
$handler->display->display_options['arguments']['field_address_value']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['field_address_value']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['field_address_value']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['field_address_value']['limit'] = '0';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

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

Step 2 - Create a Rule

Create a rule like so:

Rules Event: something like "Before saving content of type Article" seems most appropriate, though you can use any variation that fits.
Rules Condition: "Check number of results returned by a VBO view". And select the VBO view created in the previous step. In doing so, you will be asked to "specify arguments to pass to the view, one per line. You may use token replacement patterns.". The token to be entered there is node:field-address. If the number of results is 1 or more, then you know the value already exists. So within Minimum number of results you should enter the value 1.
Rules Action: this is pretty much up to your own imagination (your question doesn't specify what should happen ...). For example if the Rules Condition is TRUE, you could use "Set a data value", to set the value of that field to whatever fits. Maybe also display an appropriate message, such as (when trying to set the value to HomeIsWhereMyStellaIs):

  The value "HomeIsWhereMyStellaIs" has already been used in at least 1 other node ...

Here is an export of a Rule that does (without such "Set a value" though) what is described above (if you have the Rules UI enabled, and a field with the machine name field_address, you should be able to just import this rule):

{ "rules_prevent_multiple_nodes_with_same_field_value" : {
    "LABEL" : "Prevent multiple nodes with same field value",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "views_bulk_operations", "rules" ],
    "ON" : { "node_presave--article" : { "bundle" : "article" } },
    "IF" : [
      { "views_bulk_operations_condition_result_count" : {
          "view" : "relevant_nodes|page",
          "args" : [ "node:field-address" ],
          "minimum" : "1"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "The value \u0022[node:field-address]\u0022 has already been used in at least 1 other node ...",
          "type" : "error"
        }
      }
    ]
  }
}

Note that my Rules Event is limited to "Article" (change to whatever fits), and replace (prior to trying to import this rule) the machine name of field_address to whatever other machine name your field.

Done!

PS: I'm assuming this is about D7.


How can I set-up a custom formatter that uses target="_blank"? I've installed the Custom Formatters module, as I could not figure out why my View setting was not working for "Rewrite output" -> "Target" -> "_blank"

I need to recreate either the "Generic File" format or the "Rendered File" -> "Link" format.

This is what I've tried but I suppose 'attributes' is not something I can add for the $variables array in theme() -

$output = '';
foreach ($variables['#items'] as $item) {
  $output .= theme('file_link', array(
    'file' => (object) $item,
    'attrs' => '_blank',
    ));
}
return $output;

That formatter code above was found on the CustomFormatters.com site for Generic Image

OK, found an answer that works for implementing the hook_file_link() function in the theme's template.php file:

Answer at https://drupal.org/node/301234#comment-4764468 - copied here:

function THEMENAME_file_link($variables) {
  $file = $variables['file'];
  $icon_directory = $variables['icon_directory'];

  $url = file_create_url($file->uri);
  $icon = theme('file_icon', array('file' => $file, 'icon_directory' => $icon_directory));

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  $options = array(
    'attributes' => array(
      'type' => $file->filemime . '; length=' . $file->filesize,
    ),
  );

  // Use the description as the link text if available.
  if (empty($file->description)) {
    $link_text = $file->filename;
  }
  else {
    $link_text = $file->description;
    $options['attributes']['title'] = check_plain($file->filename);
  }

  //open files of particular mime types in new window
  $new_window_mimetypes = array('application/pdf','text/plain');
  if (in_array($file->filemime, $new_window_mimetypes)) {
    $options['attributes']['target'] = '_blank';
  }

  return '' . $icon . ' ' . l($link_text, $url, $options) . '';
}

Simply change THEMENAME to your theme name and place the code in the template file. I suppose I could extract this out into a custom formatter too.


Filtering part of a multi-value field in a specific view I have an entity with fields that allow an unlimited number of values.

In a view, I would like to display a subset of those values that match a particular condition (eg. numbers less than n, dates in the past, etc.)

From investigation, it seems that a field formatter plugin is not a good way to solve this. Sure, I can extend DateTimeFormatterBase and override ::viewElements(FieldItemListInterface $items) to apply my condition, but at the price of being able to choose an actual field formatter. The custom plugin would have to take over the rendering too.

On the other hand, the Field plugin in views has some very limited options for limiting multiple values (by picking an offset and a count), but that doesn't seem extendable with a custom plugin.

Am I going to have to hook into the view after query execution to strip out the values that don't match the condition, or is there a cleaner way using the plugin API?

Edit: I suppose I could create a field formatter plugin that contains an option for selecting an actual formatter, and then passes the values that should be displayed on to it. This seems very roundabout, though. And this logic would have to be reimplemented for each field type!

In order to have full power over the filtering and sort order of the field inside each item, the best solution appears to be a sub-view using the views_field_view module.

https://drupal.org/project/views_field_view

Create a view that only shows the desired field (without a page display)
Add a contextual filter for the entity ID to be displayed
Add this to the parent view, setting the contextual filter to the entity ID of the current item.


Having issues saving altered value in a view pre render I am trying to remove image tags in the view prerender. I've looked through articles and StackExchange and I have set it up correctly. But when I refresh the page containing the view, all the HTML tags are now present as a string.

Here's my code.

function mytheme_views_pre_render(Drupal\views\ViewExecutable $view) {
  if ($view->id() == "news" && $view->current_display == 'block_1') {
    foreach ($view->result as $row) {
      $body = $row->_entity->body->value;
      $stripped_img = preg_replace('/<img[^>]+\>/i', '', $body);
      if ($stripped_img != $body) {
        $row->_entity->body->setValue($stripped_img);
      }
    }
  }
}

You should set the format of body to full_html try with:

function mytheme_views_pre_render(Drupal\views\ViewExecutable $view) {
  if ($view->id() == "news" && $view->current_display == 'block_1') {
    foreach ($view->result as $key => $row) {
      $body = $row->_entity->body->value;
      $stripped_img = preg_replace('/<img[^>]+\>/i', '', $body);
      if ($stripped_img != $body) {
        $row->_entity->body->setValue($stripped_img);
        // Here set the format of body to full_html
        $row->_entity->body->format='full_html';
      }
    }
  }
}


How to prevent users (except for admin / editors) from viewing canonical page for content type? For a certain content type, if you want most users to be able to view the content type (node bundle) when it's loaded on landing pages or on other node pages, but you don't want them to be able to access the route entity.node.canonical for the content type, unless they have an explicit permissions (which would be given to admin role and editor role), what is the best way to do this in Drupal 8?

As an example, let's say a site has a "video" content type, when it's loaded in a block, such as a related videos block, you want everyone to be able to view it, but if a user tries to go to that video's canonical page, they get a 404, unless they have the role with the permission to view it.

This would be for certain bundles of content or media entities that I want to only allow access to in a block, but the canonical page should 404 if the user doesn't have the correct permission.

What is the best strategy to set this up in Drupal 8?

In Drupal 7, I believe you could do this with Rules. The Rules module is technically available for Drupal 8, but I couldn't figure out how to use it, so I'll show you how to wire up a custom module that redirects manually based on whatever your criteria is.

The basic idea is, in order to do custom redirects, you have to register an EventSubscriber service, subscribe to REQUEST KernelEvent, and then you have access to the entire request object.

In my company's case, I wrote a custom module called "redirect", so that's what this example will use.

First, create a redirect.services.yml file.

services:
  redirect.subscriber:
    class: Drupal\redirect\EventSubscriber\RedirectSubscriber
    tags:
      - { name: event_subscriber}

Then, create the class referenced above (Drupal\redirect\EventSubscriber\RedirectSubscriber) in src/EventSubscriber/RedirectSubscriber.php.

<?php

namespace Drupal\redirect\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Drupal\node\Entity\Node;

class RedirectSubscriber implements EventSubscriberInterface {

  public function redirect(GetResponseEvent $event) {
    $request = $event->getRequest();
    $baseUrl = $request->getBaseUrl();
    $attr = $request->attributes;
    $roles = \Drupal::currentUser()->getRoles();

    if ($attr !== null) {
      $node = $attr->get('node');
      if ($node !== null && $node instanceof Node) {
        $type = $node->get('type')->getString();
        if ($type == 'seel_lesson_plan' && !in_array('administrator', $roles)) {
          $event->setResponse(
            new RedirectResponse("$baseUrl/url-to-404-page")
          );
        }
      }
    }
  }

  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['redirect'];
    return $events;
  }

}

To get a better idea of how this works, read an explanation of registering event subscribers, the official Events API page, and this other Drupal SE question about redirecting content pages.


Impossible to get my pager I need to show in the same page a form and a table which shows all results from a webservice response.

function collectivite_search_user_form($form, &$form_state) {
    $form['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
      '#required'   => True,
    );
    $form['firstname'] = array(
      '#type' => 'textfield',
      '#title' => t('Firstname'),
      //'#required'   => True,
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
    );
    if (isset($form_state['table'])) {
        $form['table'] = $form_state['table'];
    }
    return $form;
}

function collectivite_search_user_form_submit($form, &$form_state) {
    module_load_include('inc', 'collectivite', 'collectivite.api');
    $results = collectivite_ws_get_users($form_state['values']['name'], $form_state['values']['firstname']);
    if(is_object($results->Dossier)){
            $rows[] = array(
                'id'       => $results->Dossier->id,
                'nom'       => $results->Dossier->nom,
                'prenom'    => $results->Dossier->prenom,
            );
    }else{
        foreach($results->Dossier as $dossier) {
            $rows[] = array(
                'id'       => $dossier->id,
                'nom'       => $dossier->nom,
                'prenom'    => $dossier->prenom,
            );
        }

    }

    $paging = pager_array_splice($rows, 5);
    $header = array(t('id'), t('name'), t('firstname'));

    $form_state['table'] = array(
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $paging,
      '#empty' => t('Aucun résultat.')
    );
    $form_state['rebuild'] = True;
}

function pager_array_splice($data, $limit = 9, $element = 0) {
  global $pager_page_array, $pager_total, $pager_total_items;
  $page = isset($_GET['page']) ? $_GET['page'] : '';

  // Convert comma-separated $page to an array, used by other functions.
  $pager_page_array = explode(',', $page);

  // We calculate the total of pages as ceil(items / limit).
  $pager_total_items[$element] = count($data);
  $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
  $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));
  return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}

It works fine except I cannot see the pagination. Can you see where is the problem ?

Thanks

function pager_array_splice($data, $limit = 9, $element = 0) {
      global $pager_page_array, $pager_total, $pager_total_items;
      $page = isset($_GET['page']) ? $_GET['page'] : '';

      // Convert comma-separated $page to an array, used by other functions.
      $pager_page_array = explode(',', $page);

      // We calculate the total of pages as ceil(items / limit).
      $pager_total_items[$element] = count($data);
      $pager_total[$element] = ceil($pager_total_items[$element] / $limit);
      $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));
      return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
    }

    $output = pager_array_splice($yourarray, 5);

$output = '';
  $your_array = some_method_to_get_array();
  $tree = pager_array_splice($your_array, 5);
  // Do something with the 5 terms
  $output .= theme('pager', array('quantity' => 5));


Is there a function to get the system path for the current language? If I'm using multiple languages on the site with path prefixing, is there a quick way to get a system path for the current language?

For example, if the current language is English, and I'm interested getting the English path for 'user/password', what function call (or small number of lines) will return 'en/user/password'?

The following doesn't seem to work; it returns nothing:

drupal_lookup_path('alias', 'user/password', $language->language);

The internal path is same for all languages,though you can set different alias for different languages. From your question it seems that you want to get the path with language prefix not the alias, if so then I don't think there is any function that will return the path with language prefix.

Since you can get the language using $language->language you can write a custom function as follows.

function custom_lookup_path($action, $path = '', $path_language = NULL){
   global $language;
   if(empty($path_language)){
      $path_language=$language->language;
   }
   if(!empty($language->prefix)){
      $path = $language->prefix.'/'.drupal_lookup_path($action, $path , $path_language);
   }
   else{
      $path = drupal_lookup_path($action, $path , $path_language);
   }
   return $path
}


Where should I place hook_block_view_alter? this may be a trivial question, but I have no clue to how to get this working. I have this theme 'nexus'. When try the hook

function nexus_preprocess_block(&$variables)

in the file nexus.theme, it works,

but function nexus_block_view_alter(&$data, $block)
doesn't.

Should I put it in a module? I tried creating a module using hello_world example, and put in the the module's controller but no avail.

Any hint would be much helpful.

In drupal 8 the declaration of hook_block_view_alter changed from hook_block_view_alter(&$data, $block) (Drupal7) to  hook_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) (Drupal 8).
For more info check hook_block_view_alter Documentation page.

hook_block_view_alter be better in custom module not theme, see guide to building basic Drupal 8 module, and flush all caches.


How do I show the size of an Image file in media2 after selecting the image? After selecting an Image field using the media browser, in the edit form the selected shows image, an edit button, a delete button, and an "include file in display" checkbox.

How Do I add the size of the image in the same display?

Q2:
In a colourbox popup display, which seems to only pick the "title" , I cant get this to read html. Is there a way of enable html as I need some text in Italics, and in Bold?

Thanks.

I found the solution. Somehow undocumented is the fact that this uses the "Preview" view mode. Editing that and ensuring its the one selected in image view changed everything to working normally.

Thanks.


GMaps page with a marker pin on your location based on address we supply i want to add marker directly on Gmaps on location based on address we supply. Or else i want the location based on name, longitude and latitude what we supply. FYI: i am  using gmap and locatin modules for druapl 7. Please help on the same. Thank you in adavance

To make a marker for a corporate contact page, I think it will be good to put just HTML code provided by Google Map in the template file.

Or else you can create a block and put script in block body and render it using Full HTML.

To generate HTML code create marker on Google map, Click on the Button right to Print and it will give you the code for iframe


LDAP Role Mapping - Working, but not Assigning I have setup the ldap module for Drupal 7 - everything is working as it should, apart from when a user logs into the site the role defined for that person isn't been assigned to their profile, they remain just an authenticated user.

When I run a test on their username it shows that the user should be part of the correct role.

In the error log I can see it is failing when granting a single authorisation with the following error:

LdapAuthorizationConsumerDrupalRole.grantSingleAuthorization() failed to grant xxx the role Delegate because role does not exist

However the Delegate role is setup and present.

Has anyone else come across this problem?

--

Just to note that I found the solution - don't use capitals in your roles.  Changing Delegate to delegate fixed it.  I will put this as the answer when my 8 hour self answer delay lapses.

Ok so I found the solution - which made me kick myself :p

In order to get the role mapping working the role names have to start with a lower case letter - so in my example I changed the role name from Delegate to delegate and it is all working now.


Add attributes like id to block level elements in CKEditor? In Drupal 8, is there a way/module to add attributes like "id" to h1-h6, p, span and so forth?

I am trying to find a way to support anchors, which Drupal does not seem to support anymore.

edit: Yes, I can instruct to edit with the Source button, but I am looking for a more user friendly way with a dialog and I am not seeing it.

If you just need to add ID to a link you can use the D8 Editor Advanced link module https://www.drupal.org/project/editor_advanced_link

It basically allows you to put attributes on anchor tags without touching the source code.


Use form-submit to display results table on page I’m struggling with how to get a form-submit to return the results of a database select-query.   I can build the form and the submit-function does the select-query to collect the results and builds a render-array:

$table = array(
    '#theme' => 'table',
    '#header' => array(t($field_1), t($field_2)),
    '#rows' => $tableRowS,
);

However I can’t figure out how to get drupal to render this table instead of just rebuilding and showing the empty form again. I’ve examined the concept of redirect but don’t see a way of passing the table to the redirected page.

Any help would be appreciated.

I don't think you can return a themed table on form submit. Instead, what I suggest is to use $_SESSION variable to store the form field values to query the database and redirect to a URL. In the callback function of the URL query the database and return the themed page.

Example:

function mymodule_myform_submit($form, $form_state){
   $_SESSION['somevar'] = $form_state['values']['somefield'];
   drupal_goto('someurl');
}

And in the URL callback function get the value of the session variable $somevar = $_SESSION['somevar'];


Is there a module that changes "node" links to "alias" links? I use global redirect, pathauto and redirect modules.

Everything is fine, except one situation:
I couldn't find the anwser, maybe it is very easy problem..
I can give links to nodes by using "link" "redirection" modules.
I creating new field with the type of Link.
When i select links from the lists, i can link to any node by using "fields".

But i want to give links to nodes in "body" of "node".
When i write

click here

In node content, the links is written with "node" word.
But i want to see this link in page with its alias, like this:

click here

Is it possible?
Thank you for help.

Other than using a process to rewrite the URLs, I don't know how to fix this after the fact.

In the future, though, the Linkit module integrates with WYSIWYGs and use filters to add URLs, which then get properly updated to the alias.


How to get the referenced entity name instead of target_id in Normalizers? I am working on exposing the article type content via REST in JSON format. I am using Normalizers to generate the required data format.

Normalizer:

use Drupal\serialization\Normalizer\ContentEntityNormalizer;

/**
 * StdClass normalizer.
 */
class NewsFeedNormalizer extends ContentEntityNormalizer {

  /**
   * @inheritDoc
   */
  public function normalize($entity, $format = NULL, array $context = []) {
    $node_detail = parent::normalize($entity, $format, $context);
    // $news_data = [];
    $news_data['id'] = $node_detail['nid'][0]['value'];
    $news_data['type'] = $node_detail['field_story_type'][0]['target_id'];
    $news_data['title'] = $node_detail['title'][0]['value'];
    $news_data['summary'] = $node_detail['body'][0]['summary'];

    return $news_data;
  }

}

Tha above code will return target_id in $news_data['type']. But I need to pass label of the term which is referred. I tried with another Normalizer called EntityReferenceFieldItemNormalizer But there also i didn't get the required result.  Can anyone help me in this regard? Any suggestions will be apprceiated.

you have the target id so just load the term and send the label instead of target id, something like :

$tid = $node_detail['field_story_type'][0]['target_id'];
$term  =  \Drupal\taxonomy\Entity\Term::load($tid);
$news_data['type'] = $term->label();

Note: you are in class it's better to inject entity.manager service and change the line \Drupal\taxonomy\Entity\Term::load($tid); with something like:

$this->entityManager->getStorage('taxonomy_term')->load($tid);


Help needed for adding and edit & delete link in a column in a view table I need to implement views with a table format to display fields for selected content.  I would like one of the columns to have edit/delete links that will request perform the desired task for the row selected.  I have seen it done on sites, but have not found an example In which to review the view configuration.

Clarification:  Each row in a table represents a content node and each column would display a field in the content type.  I want to put an edit link that will call up the specific node in that row in the editing form.

Could you just add a field with the node ID and rewrite it to reconstruct the url, inserting the node id where applicable (different structures for different entity types)?


How to setup a development server on Linux? I am developing a new web site for a client who is already on the web with an old site.

I need to develop the site under a different name (dns) and when it's ready, move it safely to a right name.

I am developing and hosting on AWS under Ubuntu using multi-site setup.

When I am ready I will pointing the DNS to my development server and by doing so I will be on air with the real site.
My question is: While developing I will be directing another domain to the development server say something like deveopment.com by the time I am ready to go live, I will be pointing the real domain to it, say real.com
Other than the dns' what else will I have to change on the server?
Will I have to change anything in the DB? Remember it’s on the same server and I can use the same DB.

Am I likely to run into any trouble?

It should work with no or limited changes. However, some modules include fully qualified paths in database tables or variables, so it is worth checking.

Some areas to look at are:

settings.php, particularly the database array, $cookie_domain, and $base_url
The sites directory: are you using the default directory or one tied to your development environment? If your material is in sites/my.dev.com then you'll have my.dev.com in the files table
URL related modules like securepages, xmlsitemap, and so on

When I am moving from dev to production, I also use drush to double-check that I missed nothing. Running drush vget dumps the content of the variables table, so I can grep that for URLs. For example to see all the variables that have www.indiemade.com hardcoded:

$ drush vget | grep indiemade
securepages_basepath: 'http://www.indiemade.com'
securepages_basepath_ssl: 'https://www.indiemade.com'
seotools_base_url: 'https://www.indiemade.com'
xmlsitemap_base_url: 'http://www.indiemade.com'
...

One other tool you might want to look into is drush migrate, well explained here.


Upgrading a site from Drupal 6 to 7 using Drush I am attempting to upgrade one of my sites from Drupal 6 to Drupal 7. I have downloaded and made Drush executable. I've also install the Drush site-upgrade command. The problem I'm having is understanding the steps or the process of aliases. I really need someone to explain it to me in layman's terms as I am just learning all of this. I've tried several different configurations and still can't seem to get it to work. So after some digging around within Drush I have also noticed when I do the drush st command I get this (posted below)

PHP configuration     :  /home/user/drush/php.ini /home/user/drush/php.ini
 Drush version         :  5.9
 Drush configuration   :
 Drush alias files     :  /home/user/.drush/cm.aliases.drushrc.php

Which I'm thinking is wrong, I shouldn't have 2 php.ini files show up for my PHP configuration should I?
I should mention I have a multi domain site.
I'm guessing I need to fix this first before I figure out the aliases issue, but I have posted what I put in the .drush folder as my cm.aliaes.drushrc.php file

$aliases['test'] = array(
  'root' => '/public_html/folder-of-domain-to-update',
  'uri' => 'localhost',
);

If I go to the /home folder and run the command drush sa, I get:

@cm
@cm.test
@none

If I go to the /home/user/public_html/folder-of-domain-to-update and run the command drush sa, I get:

@cm
@cm.test
@none
@self
default

When I run the command drush sup at the /home/user/public_html/folder-of-domain-to-update level I get this:

  No target argument specified. To perform the site upgrade, define an alias record for the target site.

If someone could give me some direction or help I would greatly appreciate it.

You could use the Migrate module for this purpose.

  The migrate module provides a flexible framework for migrating content into Drupal from other sources (e.g., when converting a web site from another CMS to Drupal). Out-of-the-box, support for creating core Drupal objects such as nodes, users, files, terms, and comments are included - it can easily be extended for migrating other kinds of content. Content is imported and rolled back using a bundled web interface (Migrate UI module) or included Drush commands (strongly recommended).

For more details you could go through the README.txt of this module.


How to avoid no-wrapper tags on regions? How do I make sure ALL regions are wrapped according region.tpl.php?

In a subtheme of Zen I have created my own regions and modified the page.tpl.php file to something like the following:

<div #page>
    <?php print render($page['header']); ?>
    <?php print render($page['content']); ?>
    <?php print render($page['footer']); ?>
</div>

Some of the regions get a region wrapper from region.tpl.php, others get the code from no-wrapper.tpl.php (no wrapper). How can have all regions receive a wrapper?

From the code it looks like Zen adds that template suggestion in zen_preprocess_region(), but only to the content region:

elseif ($variables['region'] == 'content') {
  // Allow a region-specific template to override Zen's region--no-wrapper.
  array_unshift($variables['theme_hook_suggestions'], 'region__no_wrapper');
}

If you're editing the Zen theme directly (which you shouldn't be :P) just remove those 4 lines; if you're creating a sub-theme, implement your own region preprocess function, copy the code from Zen's, and leave those lines out:

function MYTHEME_preprocess_region(&$variables, $hook) {
  // Sidebar regions get some extra classes and a common template suggestion.
  if (strpos($variables['region'], 'sidebar_') === 0) {
    $variables['classes_array'][] = 'column';
    $variables['classes_array'][] = 'sidebar';
    // Allow a region-specific template to override Zen's region--sidebar.
    array_unshift($variables['theme_hook_suggestions'], 'region__sidebar');
  }
}


Views row style plugin override not saving in Views UI In my ongoing journey to create a customized RSS feed in my D8 site, I've finally gotten closest to what I need by using a Feed display in Views. The basic feed is working, but I need to add a couple custom elements for each item. So based on the fact that the rss fields are rendered in the RSSFields class (\Drupal\views\Plugin\views\row)

namespace Drupal\video_export\Plugin\views\row;

use Drupal\views\Plugin\views\row;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * Renders an RSS item based on fields.
 *
 * @ViewsRow(
 *   id = "mycustom_rss_fields",
 *   title = @Translation("My Custom Fields"),
 *   help = @Translation("Display fields as RSS items."),
 *   theme = "views_view_row_rss",
 *   display_types = {"feed"}
 * )
 */
class MyCustomRssFields extends RssFields {

  public function render($row) {
    parent::render();

  }
}

So when I place this in /modules/custom/video_export/src/Plugin/views/row, if I go to select the style, I see my new plugin, but when I click Apply, nothing happens. Is there anything else I need to add to my override to get it to save?

The issue was an incomplete namespace in the use statement for the RssFields class. I had

use Drupal\views\Plugin\views\row;

so it was looking for that class in my module. Changing it to

use Drupal\views\Plugin\views\row\RssFields;

made everything work.


How to set the permission for particular role user to access the user profiles of users with a particular role? I have two user roles:

business_users
company_users

I want to set the permission for all users to see the user profile of users in "business_users" role only.

User with the "company_user" role should not to see user profile of user in their role but they can see user profile of user in "business_users" role.
User with the "business_users" role can see user profile of users with their role but they should not see the user profile of users with the "company_user" role.
Anonymous users should see user profile of user in "business_users" role only.

Can you tell how can I implement it?

You can make a template file for your profile content type, probably called something like node_profile.tpl.

At the top of this file, write some code that will get the user object of the node owner, and check this against user's roles in $user->roles.

It's easier if you do this with the roleID numbers (you can see these by going to user>role and hovering your mouse over the various links for the roles - the roleID appears as a number somewhere in the link).

Your code in the template then may look something like this.  You'll need to know php to understand how it executes.

$userRoles = $GLOBALS['user']->roles;
$account = user_load($node->nid);
if(!empty($userRoles[2])) {
  // user is a company user
  if(!empty($account->roles[2])) {
    // profile belongs to a company user
    print 'Company users are only allowed to see business user profiles';
    return; // this will stop execution of the template file, and return to the page template
  } elseif(!empty($account->roles[1])) {
    // profile belongs to a business user
    // do nothing - just continue code execution of this template
  }
}

For your listings of users, you'll want to make three different views, with views filters in each to determine which users you want displayed.  For this, you can create a page which chooses the name of the view based on the user's role(s) - either a "page" with the php code in the body (if you have php code as one of your input types), or else a page you create with a small custom module using hook_menu().


How to show the number of user points within the user who posted a comment? I use the User Points module. Despite of my searches, I didn't find answer to this question:

  In the user profile of a comment, how to show the number of user points?

For example to show the number of points below the picture of the user who posted a comment.

Any suggestions?

User Points

  Services integration: allowing retrieving and updating points on your    site using web services.
  Rules integration
  Views integration
  A block displaying the number of points a user has gained
  A block displays the top users who earned points
  A status message telling the user how many points were earned/lost    and their total points
  A detailed point total report for each individual user
  A point total report for all users

Profile2

  The module is aimed to provide a simple, but extensible solution    providing a similar end user interface like the core profile module
  by default.
  Multiple profile types may be created via the UI (e.g. a general    profile + a customer profile), whereas the module provides separated
  permissions for those.
  Optionally, profile forms are shown during user account registration.
  Similar to the deprecated core profile module, fields may be    configured to be private - thus visible only to the profile owner and
  administrators.
  By default the UI behaves similar to the deprecated core profile    module, thus showing each profile type in each own tab below
  user//edit. Via the included "Profile pages" module profiles can
  be viewed and edited at their own page and get their own menu link,
  e.g. "My profile".
  Thanks to the foundational entity API the module integrates well with    Rules as well as Features - thus profile types and the
  associated    fields can be exported into feature modules. Once the
  Entity tokens    module (part of the Entity API) is turned on, there
  are also token    replacements available.
  You may use Views and/or the Search API to provide listings or    searches for profiles


How can I tidy up an auto increment field in a table from within a module? How can I tidy up an auto increment field in a table from within a module, so that a table like this (the 'id' field being auto incrementing):

id title
1  foo
3  bar
7  fee

becomes:

id title
1  foo
2  bar
3  fee

Is there a function, like serial_field_tidy or something?

You should never do that since the IDs are important for addressing to that specific row in other tables. You would never know which modules are also indexed this row with its id. So if you change the ID of a row, you will encounter unexpected things in your installation.


Drupal 7 - Anyway to make Facebook Picture take place of User Picture if not available I am creating a view of users that displays a list of Users with Picture and Name. This drupal install allows facebook users to sign in and automatically have an account created. Their account is also added to this jCarousel view.

The problem I am facing is that when a user signs up from Facebook, but does not upload an image directly to drupal, their facebook picture does not show on the list. Anywhere else on the site, however, their facebook pictures shows with the profile.

On the views field, I have:

User:Picture
User:Name

Is there anyway to have a logic in the view where I can request the Facebook Picture if User:Picture is not available?

Thank you in advance,

You can use the Views PHP module and use PHP to create whatever logic you want for this image output.

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

  This is the successor of Views Custom Field for both D6 and D7. The D6
  version supports both Views 2 and Views 3.

  Note

  While this module allows you to directly use PHP inside views
  which may be useful for quick and easy solutions, it is highly
  advisable to use regular handlers and plugins when available (or even
  to create one yourself). Take note that filtering and sorting a view
  using PHP always has a considerable perfomance impact.

So in your view you can have:

3 fields, user profile picture, facebook picture and the php field used to display a picture.
for the user profile picture, make it a default image display and exclude it from the output.
for the facebook picture make it a default image display and exclude it from render output.
in the php field you simply want to check if a file exists for user profile picture and then drupal_render() or return the profile or facebook picture Views will have already formatted for you using the other 2 fields.
be sure the 2 image fields are higher up in the field list of the View than the PHP field, so the PHP field can make use of those values in code.

EDIT

An alternative that is slightly less magical and tied to Views is to use Display Suite and add a Custom Field in display suite for a User. This custom field does basically all the logic between the 2 fields and it's literally a pseudo-field for Users. Views can then use the view_mode for Users that you've provided by DS.


How to speed up Drupal 8 when pages are not cached yet (1st time visit after clearing cache)? D8 has awesome core caching and opens pages very quickly in second-third and so on visits.

But when I clear caches (making design improvements) the response is too long. Very long response during first time page visit in my shared hosting.

I want to move on VPS, so please what to do with my server to speed up drupal 8?

You'll want a crawler (e.g. a cron script running wget) to trigger a local cache rebuilding or some proxy caching solution (e.g. Varnish, CloudFlare) to prevent your server from being hammered on every request upon Drupal page cache flush. Use a crawler if you have a relatively small/fixed amount content and a proxy cache for large/dynamic amount of content.

There really isn't a Drupal-centric solution here. The closest thing might would be the Boost project which has a proxy (local file)/crawler solution, but that's for D7.


How do I get the list of nodes of a specific content type and their titles? A call to field_attach_load should be loading node titles, but they are not being loaded.  Perhaps I am missing something simple, since this my first Drupal hook.

This is the code I am using to query all the published Event nodes and their associated fields.

$query = new EntityFieldQuery();
$results = $query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'event')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->execute();

  // Attach the field values to the nodes.
  $nodes = $results['node'];

  field_attach_load('node', $nodes, FIELD_LOAD_CURRENT);
  var_dump($nodes);

Unfortunately, this code doesn't work for me.

How do I get the list of nodes of a specific content type and their titles?

PLease try this-
This will load all published nodes of type event.

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'event')
->propertyCondition('status', 1);

$result = $query->execute();

if (!empty($result['node'])) {
$nids = array_keys($result['node']);

foreach ($nids as $nid) {
$node = node_load($nid, NULL, TRUE);
// do something awesome
 }
}


How to make Posts/Blogs mentioning a user appear in the user's profile? I'm using Drupal 7 and I created a simple page where users are able to create challenges and tag people in their posts. For tagging I used the Mentions module and it works fine, I'm able to visit tagged person's profile.

Now I'm trying to add all the posts/blog entries that are associated with that user to the user's profile. So that every time the user is mentioned, that post would appear on the user's profile.

Is that possible to do? If yes, what would be a possible approach?

Step 1

Use the Message module to create "Messages" each of those mentions, similar to what is detailed in the answer to "How to get notifications in a new window when using the Mentions module?".

Step 2

Perform the steps explained in "How to allow users to manage their own Message Stack messages?", which can be summarized like so:

Create a flag (using the the Flag module).
Create a view 'Messages by user'.
Use Rules to flag/unflag messages.
Trigger the Rules Component to mark messages (using the VBO module).
Create notifications about Unread Messages (using the "Menu Badges" module).

Notes:

Consider Step 5 as a bonus: whenever a new message gets created, the user gets a shiny notification in the format of an iOS-like (red) badge with the number of unread mesages.
No custom coding involved, only using some of the commonly used contributed modules (and "Menu Badges", a hidden gem ...).


Hide Title for Rendered Entity views In display modes I set to hidden all Title fields, but Views still gives h2 title.

Views renders the node entity using the default view mode (machine name 'full'). Drupal uses the node.tpl.php template to output the node. That template contains a condition to check for the $page variable. If that is false than it prints the title of the node as a link.

The are various solutions (such as using a different view mode or tinkering with node.tpl.php) but you can also clear the title using hook_node_view.

You can check if the node is the same as the one returned by menu_get_object. If that is not the case than the node is somehow embedded in another node or in a view (as is your case).

function MYMODULE_node_view($node, $view_mode, $langcode) {
  $page_node = menu_get_object();
  if ($node->nid != $page_node->nid) {
    $node->title = NULL;
  }
}

I havent experienced any bad side effects, yet.

See drupal.org for more info.