How to make different slogan for each content type? I have several content types, I want the slogan that shows up on the page to be different for each slogan. Is this possible?

You can use a preprocess function:

function mymodule_preprocess_page(&$variables) {
  if (isset($variables['node'])){
    switch ($variables['node']->type) {
      case 'my_content_type2':
        $slogan = "my super slogan 1";
        break;
      case 'my_content_type2':
        $slogan = "my super slogan 2";
        break;
      default:
        $slogan = "my super slogan 3";
    }
    $variables['site_slogan'] = $slogan;
  }
}

In this case, you preprocess the page before it is sended to the template engine.
More exactly, you change the 'site_slogan' variable according to the node type.

You can add this function in a module: in this case replace "mymodule" in the function's name by the name of your module

or you can add this function in the "template.php" file of your theme folder: in this case replace "mymodule" in the function's name by the name of your theme.


How to load nodes that are associated with the child of a taxonomy term This questions has some similarities with How to display list of nodes that share the same Parent taxonomy term as current node, but I've not managed to figure out how I can get to what I need to do given the answers there.

A have a set of nodes that are associated via term reference with a taxonomy, that is two levels deep.  I'll call the parent level area and the child level task.

This is a migration from another website that has pages for publications associated with each area but in my current data structure I only associate the publication nodes with the tasks (children of the areas).  The areas each have a legacy_area_id field populated with the area id that was used in the url on the old site.

What I want to do now is create a view that will listen on pub/by/area/% and take a legacy area id as a contextual filter, and show a list of all nodes associated with a child of the taxonomy term that has that value in its legacy id field.

An example:

With a data setup like this, a request to /pub/by/area/1

Should return a listing containing Nodes 1, 3, and 4

One option would be to go back and change my migration to associate the publications with areas too, but that seems likely to make the task of moving tasks between areas later quite a bit more complicated.

Another option would be to add the legacy area id to the tasks as well, but that provides similar challenges.

In reality, my end goal is to redirect these pub/by/area/# requests to a different view with the area name in the url similarly to what I've done for other old addresses in How to redirect based on matching a node field?.  So really I suppose all the view really needs to give me is the data required to redirect to another view.  I'll keep working on this, but help would be appreciated.

visabhishek answer gave me an idea.

Create a tax term page view:

Add Legacy ID as your contextual filter
In FIELDS add term ID (so you will get the term ID of Area 1. You can hide it using exclude from display.)

Then using the Views Field View module

  This module allows you to embed a view as a field in a view.

Add the view from visabhishek answer as a field. For Contextual filter you can pass the term ID as a token (using replacement patterns)

Problem solved :)


Custom field: process submitted before storing I've created custom field type and widget plugins in D8.

I am presenting an element in my widget as checkboxes, but I need to transform the resulting array into text delimited by pipes. i.e. a|b|c.

How would I approach this in the field widget?

messageFormValues in the widget class did the job.

class MyDefaultWidget extends WidgetBase {
  ...
  /**
   * {@inheritdoc}
   */
  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    // Change the format of $item['sections'] from array to pipe delimited string.
    foreach ($values as &$item) {
      $sections = [];
      if (is_array($item['sections'])) {
        foreach ($item['sections'] as $s) {
          if ($s !== 0) {
            $sections[] = $s;
          }
        }
      }
      $item['sections'] = implode('|', $sections);
    }
    return $values;
  }
  ...
}


View Field, Insert View, View Reference, Block Reference, Insert Block: which to choose to embed a view in a page I have a view I would like to embed in a page with some other content. The page is for logged-in users only. I could make a page or a block version of the view. I could make a new content type or not for the page- it's not a big deal. So I could use Viewfield, Insert View, View Reference, Block Reference, Insert Block, EVA, and maybe some others to embed the view. I could even code a page template up with views_embed_view(), though I would prefer to use an existing module for ease of future maintenance. Using the view's header and footer fields is inadequate in this case, because I want the surrounding content to be easily editable?

Are there technical reasons to choose one of these modules over the others? For instance, do any of them have issues with caching or permissions? Or, for instance, Is there a reason not to use the view as a block?

Option 1:

Just create a page for the view.

You can set which permission or role should have access to the page.

If you need to display content above or below the view use the header and footer.

Option 2

Use hook_node_view() and views_embed_view() to add the view as a field to the node you want to target:

function hook_node_view($node, $view_mode, $langcode) {

  // Add whatever logic you want here to only target the nodes you want
  if($some_check == TRUE) {
    // Add a new field to the content array
    $node->content['view_field'] = array(
      // Render you view
      "#markup"=> views_embed_view('view_name', 'view_display'),
    );
  }
}

You say it's better to not write PHP for maintenance reasons. I would argue the exact opposite - it's much easier to version control code than it is configuration stored in the DB.


Why isn't my controller returning AccessResult::forbidden()? I'm working on a node access module. I've set up my logic. I can't seem to get my code to return AccessResult::forbidden(). I can't even get \dpm to run in access method. What am I doing wrong? Below are my routing.yml and controller.

/* nodeaccess.routing.yml */
nodeaccess.people:
  path: '/user/{uid}/edit'
  defaults:
    _controller: '\Drupal\nodeaccess\Controller\NodeaccessController::content'
    _title: 'Dashboard'
  requirements:
    _custom_access: '\Drupal\nodeaccess\Controller\NodeaccessController::access'

/* src/Controller/NodeAccessController.php */

<?php

namespace Drupal\nodeaccess\Controller;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountInterface;

/**
 * Defines the Dashboard controller.
 */
class NodeaccessController extends ControllerBase {

 /**
  * Returns content for this controller.
  */
 public function content() {
   $today = date("l");
   if ($today == "Thursday") {
     // Return 403 Access Denied page.
     \dpm("You are not allowed.");
   }
 }

 /**
  * Checks access for this controller.
  */
 public function access(AccountInterface $account) {
  $current_user = User::load(Drupal::currentUser()->id());
  $user = User::load(explode("/", $_SERVER["REQUEST_URI"])[1]);
  if ($current_user->field_department->target_id != $user->field_department->target_id) {
    return AccessResult::forbidden();
  }
  return AccessResult::allowed();
  }
}

There is a syntax error here Drupal::currentUser()->id() should be \Drupal::currentUser()->id() and also explode("/", $_SERVER["REQUEST_URI"])[2] gives you only people not the user id, to use User::load.


How to make Drupal highlight the same menu item for 2 different nodes (URLs) When defining the menu item, I can only choose a unique URL for language. But I want that a bunch of pages, one of them the referenced by the menu item, highlight that menu item (Products) so I know I am in that section of the page. For example:

www.example.com/products
www.example.com/search-product
www.example.com/product-detail

all would have to highlight the menu-item := products, that which references the first URL above.

I have tried with the following code but I am not sure if there is a faster and more direct approach, it seems too convoluted to me to theme() nothing to keep the above desired effect

Code:

   print theme('links__system_main_menu', array(
        'links' => $main_menu,
        'attributes' => array(

        ),
        'heading' => array(
          'text' => t('Main menu'),
          'level' => 'h2',

        ),
      ));

function theme_links__system_main_menu($variables) {
  $html = "
";
  foreach ($variables['links'] as $link) {

  // HERE I would change $link['href'] to merge the 3 links
  //together and make that this item is hilited when I am in one of the 3
  //links. Of course, the href link will direct to the first one, but
  //the hilite will make the user to know that she is in this section.

    $html .= "
".l($link['title'], $link['href'], $link)."
";
  }
  $html .= "
";
  $html .= "";

   return $html;
}

Another coded approach:

 $a = menu_tree_output( menu_tree_page_data("main-menu") );
 print "
";
foreach($a as $key => $value){
 active = "";
   if($value["#href"] == current_path() || ( drupal_is_front_page() && $value["#href"] == "<front>" ) ){
     // HERE I would change $link['href'] to merge the 3 links
    //together and make that this item is hilited when I am in one of the 3
    //links. Of course, the href link will direct to the first one, but
    //the hilite will make the user to know that she is in this section.

    $active = 'class="active"';
   }
        if($value["#href"] == "<front>"){
            $url = "";
        }else{
            $url = drupal_get_path_alias($value["#href"]);
        } // if
        if($value["#title"] != "") print '
language . "/" . $url . '">' . $value["#title"] . "
";
    } // foreach
     print "
";

Recently I've the same needs in my site and the fastest and painless approach was doing in CSS instead create preprocess functions.

This was done in Drupal 8, but works independently of what you are using.

First make sure that you have a class or id named with your path in any place of your HTML, and then, just use it to style your link with same 'active' class. Something like this...

HTML:

Home

Products

Contact

  ...

CSS:

.main-menu .active,
.path-product-detail .main-menu a[href="/products"] {
  color: #fff;
  background-color: #c9093e;
}

Try in JSFiddle:
https://jsfiddle.net/t4vny2df/1/

Edit 1: Detailed explanation
First of all, in your html.tpl.php template make sure that the current path is printed as a class, this will be dynamically specified, all the magic is right here in this class (in Drupal 7, by default, seems the class is page-'currentPath' according docs).

Your HTML must print current path in body element.

...

Now, based in this class just use the right CSS selectors to highlight the menu item. I'm going to use the 'products' html code example.

.main-menu /*Note 1*/ .active /*Note 2*/,
.page-product-detail /*Note 3*/ .main-menu a[href="/products"] /*Note 4*/,
.page-search-product /*Note 5*/ .main-menu a[href="/products"] /*Note 4*/{
  color: #fff;
  background-color: #c9093e;
}

First, in CSS we can use a combination of selectors do get the right element and we can use 'comma' to specify another selector to the same style (a, p{color: #000} /*Element 'a' and element 'p' will be color black*/)

Note 1 - Considering your menu with a class 'main-menu'.
Note 2 - Considering that you are using a 'active' class for current path.
Note 3 - If body has a class 'page-product-detail' this selector will be considered.
Note 4 - This selector will get the menu item that you want highlight and doesn't have a 'active' class, because you are not in '/products' page.
Note 5 - If body has a class 'page-search-product' this selector will be considered.

For more pages just add another line with your 'page selector'. Any questions just leave a comment and I explain.


Reverse proxy causes issue with CSS links and HTTPS I have multiple Drupal instances behind a F5 load balancer. If I use it as http, that is OK. If I want to use http and https and ofload https on the LB, all CSS and JavaScript links in the https site comes as http and cannot be loaded because of the https security.

Do you have any css/js aggregation module installed. If so delete the caches under sites directory. You can even try uninstalling the module to debug if that is causing the issue.
Clear Drupal caches
Ensure you do not have global $base_url hard coded to http.


Disable Drush backend messages by default I am having a problem with drush backend message, how do I disable "--backend" by default ?

command:
$ drush make drupal-org.make drupal

result:
$ drush make drupal-org.make drupal
DRUSH_BACKEND:{"type":"notice","message":"Command dispatch complete","timestamp"
:1364518974.3749,"memory":6182608,"error":null,"packet":"log"}

 DRUSH_BACKEND:{"type":"memory","message":"Peak memory usage was 6.36 MB","times
tamp":1364518974.375,"memory":6183144,"error":null,"packet":"log"}drupal-7.21 do
wnloaded.    [ok]

everything is working properly but I do not want to see the "backend json" output on the console.

$ drush --version
drush version 5.0-dev

$ git --version
git version 1.8.0.msysgit.0

$ uname -a
MINGW32_NT-6.1 PC 1.0.12(0.46/3/2) 2011-07-20 17:52 i686 Win7

Uninstall cleanly that version of drush as 5.0 is very old now. Uninstall using pear if you installed that way, using Composer, or manually checking which drush and remove symlinks, drush folder, backup and then remove ~/.drush.

Look at the Drush install page to see what drush version you need for Drupal version you are working with. Then install drush using Composer which is the recommended way.

This message should be gone then. Good luck!


How can I display custom user information on a page that is not a profile page? I'm looking to display User information on an individual page, pulling custom fields to display the information.

For example, if a visitor of the site come across a user page, it would display:

Name (not username)
Pictures that they've uploaded
An about me paragraph

Maybe a few other custom fields in the future, but the main part is that I need to know how to call these from Drupal.

I'm new to Drupal, but I've worked with Wordpress and Joomla a lot in the past and I'm looking to move onto Drupal, so please, be patronising when you explain!

Probably you should create a panel with two views. One for a general user information and other for stuff like uploaded pictures.

Hope these tutorials will allow you to get started

http://nodeone.se/sv/node/20

http://mustardseedmedia.com/podcast/episode32


How to generate absolute URL for breadcrumbs? I am use Easy Breadcrumb module for a D8 site. I have everything I need with this module as it alters the existing Breadcrumb block, but it outputs relative URLs.

How can I change the relative URLs to absolute?

Current issue (Breadcrumb Output):

    level One

    level two

    level three

Current Level

Expected output:

    level One

    level two

    level three

Current Level

You can alter the breadcrumbs of other bread crumb builders (core or contrib) in a hook_system_breadcrumb_alter():

/**
 * Implements hook_system_breadcrumb_alter().
 */
function mymodule_system_breadcrumb_alter(\Drupal\Core\Breadcrumb\Breadcrumb &$breadcrumb, \Drupal\Core\Routing\RouteMatchInterface $route_match, array $context) {
  $links = $breadcrumb->getLinks();
  foreach ($links as $link) {
    $url = $link->getUrl();
    $url->setAbsolute();
  }
}


Enumerate content in custom view template I am very new in Drupal. I am using Drupal 7.
I would like to create a custom rendering for a view I have created.
Thanks to many posts found on the internet I have already done the following steps:

Created a content type with Title and URL (it simulate a link list)
Added 4 items of this content type
Created a view which return items of my content type unsorted
Thanks to the Theme Information link I have created a template named views-view--xxxx--page.tpl.php where xxxx is the name of my view.
I have added the following code to the TPL file

Sample Title

And this works perfectly because I am seeing the Sample Title text when navigating on the page. I want now to enumerate the list of content item produced by the view but I dont know how to enumerate them. I have tried with

<?php foreach ($rows as $id => $row): ?>

<?php print $view->render_field('field_url', $id);?>

<?php endforeach; ?>

Welcome to Drupal!

Use row level templating in template suggestion and follow exactly the same markup so your code should look like the following

<?php print $fields['title']->content; ?>

It will follow the same markup for each row.


Using getThirdPartySetting() to get node type configurations in other hooks In a Drupal 8 instance, getThirdPartySetting() function to save node type configurations using the NodeTypeInterface object like below

  $type = $form_state->getFormObject()->getEntity();
  $fields = $type->getThirdPartySetting('field_config', 'type_fields', array(''));

Now I need to use the configurations in a hook for validation, to be particular in hook_entity_bundle_field_info_alter()

function hook_entity_bundle_field_info_alter(&$fields
  , \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle)

It contains objects of EntityTypeInterface but not that of NodeTypeInterface. Now how can I access the configuration of the particular node type in the hook?

When I tried something like this in hook_entity_bundle_field_info_alter:

  $node_type = \Drupal\node\Entity\NodeType::load($bundle);
  $selected_fields = $node_type->getThirdPartySetting('field_config',
    'field_scope', '');

It throws an error as : Call to a member function getThirdPartySetting() on a non-object

$bundle is the node type (ID), so you can load the node type based on that.

$node_type = \Drupal\node\Entity\NodeType::load($bundle);


"Uncaught TypeError: Cannot read property 'getAttribute' of undefined" There are some posts about this error for Drupal 7, but I'm using Drupal 8.1 and those solutions don't work for D8.

I tried this patch (coded for D7) and doesn't work.

The effect of the error is that QuickEdit doesn't work: sometimes the quick edit link doesn't appears, sometimes it appears but when edit some fields I get error.

Can anybody help?

UPDATE for neograph:
I haven't changed anything about the loading of the javascript. The only thing I did is edit the my_theme.libraries.yml for adding JS plugins:

global-css:
  css:
    theme:
      #css/style.css: { }
      dist/css/style.css: { }

global-js:
  js:
    #js/script.js: { }
    bower_components/slick-carousel/slick/slick.min.js: { }
    bower_components/slicknav/dist/jquery.slicknav.min.js: { }
    bower_components/superfish/dist/js/superfish.min.js: { }
    dist/js/script.js: { }
  dependencies:
    - core/jquery

The problem is in panels module, upgrade to latest version to fix the issue.
For more details see https://www.drupal.org/node/2713123


Where should twitter embed javascript go in a ctools plugin I have a ctools plugin with the twitter embed javasacript in there, but where should the javascript go? Should it be in the template file, or should be be outputted into the block in the plugin file?

There's nothing "special" either about "Twitter embed" or "javascript and plugins".

The solution is the same as for other javascript includes, put the javascript in [module]/js/file_name.js, and call drupal_add_js() on it.


Date range field misses the minutes when they are the same [UPDATE: RESOLVED ON MY OWN! YAY!] I've got a date range (start and end date) which I'm using to display a start and end time of an event. However, when the minutes are the same for the start and end time (with differing hours), the first time's minute digits are omitted. See the pic:

I've looked through the settings and I cannot, for the life of me, figure out how to show minutes when the minutes are the same. When I change it to be different minutes, it looks good:

I'm sure it's some simple setting that I'm just missing, somewhere. But I've searched and googled and can't figure it out. Here's my configuration:

And here is that format:

Set to that date type:

Seems fine everywhere.

It's in military time--not sure how to get an AM/PM dropdown. Don't see any options for that, but I haven't really investigated that yet. But that's neither here nor there. I'm hiding the year, month, day in this Add Event form and just using a default value.

The only modules that affect this that I'm using are Date and Date API, as well as Panelizer to display it. I'm using a custom layout with panelizer, but that shouldn't matter.

I actually do have some code in the template.php file that alters a date range, but can't see, as of yet, why that'd be screwing things up:

// template.php

function times_square_date_display_range($variables) {
  $date1 = $variables['date1'];
  $date2 = $variables['date2'];

  //if the same month, omit first num's month
  if (substr($date1, 2, -1) == substr($date2, 2, -1)) {
    $date1 = substr($date1, 0, 2);
  }
  $timezone = $variables['timezone'];
  $attributes_start = $variables['attributes_start'];
  $attributes_end = $variables['attributes_end'];
  $show_remaining_days = $variables['show_remaining_days'];

  $start_date = '' . $date1 . '';
  $end_date = '' . $date2 . $timezone . '';

  // If microdata attributes for the start date property have been passed in,
  // add the microdata in meta tags.
  if (!empty($variables['add_microdata'])) {
    $start_date .= '<meta' . drupal_attributes($variables['microdata']['value']['#attributes']) . '/>';
    $end_date .= '<meta' . drupal_attributes($variables['microdata']['value2']['#attributes']) . '/>';
  }

  // Wrap the result with the attributes.
  $output = '
' . t('!start-date - !end-date', array(
    '!start-date' => $start_date,
    '!end-date' => $end_date,
  )) . '
';

  // Add remaining message and return.
  return $output . $show_remaining_days;
}

That's pretty much all the info I have about this.

[UPDATE: It is an error with the if statement at the top of the template.php code. I used this to alter the display of date ranges and had to qualify it more  to only affect date ranges, not time ranges. Here's the code for the fix ( skip date outputs with ':' character):

if ( (substr($date1, 2, -1) == substr($date2, 2, -1)) &&
   ( strpos($date1, ':') !== true ) ) {
  $date1 = substr($date1, 0, 2);
}

Can I give myself the bounty? :) ]

Hope you are using core date module with end date. If you are, here is my field configuration in content type:

Once have the field configured with custom date format, the display seems working as expected.

Let me know, if I missed configuration details here.


advagg drupal module breaking my js file I am using advagg module to improve my website performance and I also using date picker jquery UI function for date functionality.

I have datePicker  intialization $( "#datepicker" ).datepicker(); . It works perfectly, I can Even see the calender but when I am selecting the date, I don't see any alert.

for Some reason On datepicker function onSelect is not working when I have advagg enabled.

 jQuery('#datepicker').datepicker({
    onSelect: function(dateText, inst) {
        alert(dateText);
        glImgExpiry = dateText;
      }
});

If I disabled advagg, It works without any problem and I can see alert(dateText).
This is happening when I am configuraing advagg to my dev/test , In my local I am not able to configure correctly because I only see per file setting for jscompression and other settings in my dev/test.So sadly, I am not able to reproduce same issue in my local and it is breaking in my test/dev environment.

I know the information, I am giving is not sufficient to get the issue/ problem I am describing. I am just hoping some one might have faced same kind of issue and can help me resolve this problem.

EDIT

As suggested I have tried putting the datepicker onSelect function inside drupal.behavior

(function($) {
    //add drupal 7 code
    Drupal.behaviors.myfunction = {
        attach: function(context, settings) {
//end drupal calls

            jQuery(document).ready(function() {
                jQuery('#gl_img_datepicker').datepicker({
                    onSelect: function(dateText, inst) {
                        alert(dateText);
                     }
                });
//some jquery goodness here...
            });

        }};
})
        (jQuery);

But I still dont see the alert(dateText); in the page.

Thanks your help is really appreciated.

You do not need to add document.ready to a behavior.
Read about drupal behaviors HERE or at a good blog post HERE.
Basically I think Drupal adds a document.ready which calls all the behaviors. The behaviors are also called after an ajax call is returned (sending the new content returned by the ajax to the behaviors via the context variable). Which is why we use the context variable in the jquery selector.
Your javascript should probably look like this.

(function ($) {
  Drupal.behaviors.myfunction = {
    attach: function (context, settings) {
      $('#gl_img_datepicker', context).datepicker({
        onSelect: function(dateText, inst) {
          alert(dateText);
        }
      });
    }
  };
})(jQuery);


How can I add help tips on each page, like a sliding panel? Is there any module I can use to insert in every page info about the specific page. I could use something like a sliding panel, or a popup. I need the content of that, block or popup or whatever it is, to be translatable.
I found this link, but it needs much custom code, which I would like to avoid.

It sounds as if https://drupal.org/project/popup may be suitable for for your needs.

You could create a block with various contexts (your translations / page) and then use this module to display the block (using sub module 'Popup Block') on each page when the user requests it, by rollover or click or whatever you choose.

The module is mature, widely used, has a recent version and has documentation provided.


When does Views check node_access permissions? I'm using the book_access module (https://www.drupal.org/project/book_access) and I'm finding that it has a good deal of bugs in it.

One thing I've found is in views 3.x, when I'm using a relationship to add the data for the top-level book in a view, and grouping the view results by the top level book, every node that isn't currently in a book doesn't show up since it seems that views isn't getting access permissions for anonymous users.

Though, when book_access is disabled, or if node_access permissions are bypassed, these items nodes show up in the view for anonymous users without any issue.

I'm trying to troubleshoot this, and I'm wondering if anyone knows the exact point at which Views 3.x takes node_access permissions into account so I can muck with some debug statements, etc. Can any one help out?

Views adds the node_access tag to it's queries, which allows the implementation of hook_query_TAG_alter in the node module to intercept the query and the joins needed to respect node access grants.

The "Disable SQL re-writing" checkbox in the Query options under the advanced settings for the view can disable this behaviour.


How to add an item to the secondary menu in Drupal 7? So far I've got the two standard menus in Drupal 7: the "main" and the "secondary" links, which are mapped to Main menu and User menu in the menu settings, respectively.

Now, I'd like to add a simple link to a contact form in the secondary menu, but I can't figure out how. Simply adding a link to User menu works fine when I'm logged in, but it doesn't show up for an anonymous user. It seems that the secondary menu doesn't show up at all for anonymous users, even if it is mapped to a custom menu (instead of User menu). Is there a way that one can configure the permissions for menus? If possible, I'd still like to have the logged-in menu links (like 'My account' and 'Log out'), as well as having some simple links that are always shown.

Is this possible?

See www.domain.com/admin/structure/menu/settings

If you set both to "main menu", then the parent items will be in the main menu and child items will be in the second level menu. The menu system will respect the access system, so if a anonymous user does have access to content A. They will not see content A in the menu.

Hope it helps


How to access session variables in Twig template? In a custom module I specified in the hook_preprocess_page function the following session variable:

if (isset($blockNameState) && $blockNameState == 'open') {
   $tempstore->set($blockNameState, 'close');
}
else {
   $tempstore->set($blockNameState, 'open');
}

Let's assume the above code ran with $blockNameState = 'block1_state' and there is key/value pair 'block1_state/open' in the $tempstore.

How do I access the key/value pair in a Twig template?

Can't run the following PHP command in Twig:

$blockNameState = $tempstore->get($blockNameState);

You can inject new variables into templates by using the appropriate preprocess hook in your theme:

function mytheme_preprocess_page(&$variables) {
  // code to get value...
  $variables['myvariable'] = $value;
}

Then in the corresponding template:

{{ myvariable }}

You might have caching issues with this though.


Link directly to a file from a block I have a full-HTML block and I want to put a link to a file into it that varies with the sitepath. I saw somewhere something about putting public:// instead of http:// to route to sites/default/files, but it doesn't seem to work from block content at least (is that only in php?)

So I have a block with <img src="public://img/screenshot.png"/> in the content and nothing is happening. Any ideas how to make this work? I don't to use image module or anything like that yet.. just a link to a file.

You'll need to use file_create_url() and the 'PHP code' format (comes with the core 'PHP filter' module) for this to work:

<img src="<?php print file_create_url('public://img/screenshot.png'); ?>"/>

If possible I would suggest adding it inside the block's template file instead though.


How to sort autocomplete results by post date? I have a content type named "News" which contains a node reference field named "Related News" in autocomplete mode.
Does anyone knows how to sort the results when i write something? I need to get the most recent nodes.

Thank you!

You should use views entity reference widget.you can custom you result like want you want.

this link is good tutorial for you achieve your job.I hope learn it and use  it in future project and issues.


Dynamically fill field when adding a new node I have been trying to search for an answer to this but I am not entirely sure what to ask.  I am using drupal 7.  What I am trying to accomplish is being able to create a campaign, and then allowing users to order a product within that campaign.

So currently I have a content type of campaign and a content type of order.  I create a new campagin and then un-authenticated users should be able to create new Order nodes, but what I am not sure how to do, is link the orders to the campaign. So http://www.domain.com/campaign/name would have a form on it that generates a new order node.

It seems like I need to have entity reference in the order content type, but how to I populate that field because I don't want the user to select which campaign, it should be automatic.  Hopefully that makes sense, the only way I have thought to accomplish this would be to parse the uri and try to get the campaign name then lookup the campaign nid.  Seems kind of hackish though.  Thanks!

I don't know a clever way to link, so I would probably use the NID from campaign as a reference.

I'd create a integer field in order which would store the NID from the campaign on creation. i.e. The custom form would create a node of type order and automatically fill the value.

Then both objects have the same number which will function as a connection. You can use EntityFieldQuery to find the related objects whenever you have the campaign nid.

This is pretty crude though, hopefully there is a smarter way.

Here is some sample code (untested, probably will need a little debugging, paths are from memory).

function my_create_a_node_form() {
  //form stuff goes here.

}

function my_create_a_node_form_submit() {
  //menu_get_object retrieves the current objects that loaded. We're storing it
  // we're storing it in a variable.

  $currentcampaign = menu_get_object();

  //we collect the nid from the campaign.
  $currentnid = $currentcampaign->nid['value'];
  global $user;

  $values = array(
    'type' => 'order',
    'uid' => $user->uid,
    'status' => 1,
    'comment' => 1,
    'promote' => 0,
  );
  $entity = entity_create('node', $values);

  $ewrapper = entity_metadata_wrapper('node', $entity);
  $ewrapper->title->set('YOUR TITLE');

  //here we store the nid in our pre set-up order field.
  $ewrapper->field_my_order_ref->set('$currentnid');

  //the rest of this is just standard create a node stuff.
  $my_body_content = 'A bunch of text about things that interest me';
  $ewrapper->body->set(array('value' => $my_body_content));
  $ewrapper->body->summary->set('Things that interest me');

  $my_date = new DateTime('January 1, 2013');
  $entity->field_my_date[LANGUAGE_NONE][0] = array(
     'value' => date_format($my_date, 'Y-m-d'),
     'timezone' => 'UTC',
     'timezone_db' => 'UTC',
   );

  $ewrapper->save(true);
  entity_save('node', $entity);

}


How to set the access of a menu page for all? function onthisdate_menu() {
  $items = array();

  $items['blog'] = array(
    'title' => 'blogs',
    'description' => 'Listing of blogs.',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );

  return $items;
}

what access I need to set to let all the users see the page?, because I am looking that page as admin and I get an message "access denied"

If you set access callback to TRUE, all users will have access to the menu router item. That means ALL users.

 $items['blog'] = array(
    'title' => 'blogs',
    'description' => 'Listing of blogs.',
    'access callback' => TRUE,
    'type' => MENU_SUGGESTED_ITEM,
  );

However, setting 'access arguments' => array('access content'), and omitting 'access callback' => TRUE, is the best way - check your permissions settings. You should be getting an access denied error at example.com/node page as well.

If you don't set an access callback, it would be user_access and the access argument will be passed to that function.


How can I let a user select my Drupal Commerce product to either be shipped or downloaded? I am using the Drupal Commerce module. I want to download the digital file. I am using the Commerce License and Commerce File modules.

But now I need to add an option to let the user select between Shippable or Download. If the user selects Shippable, the product will be shipped, while if the user selects Download, the user will be able to download the file.

I want to do it like in the product page:

If the user selects Shippable, the user doesn't have a FILES tab in the User profile page.
If the user selects Download, the user has a FILES tab in the User profile page.

How can I implement this using Drupal Commerce?.

Any suggestions?

Required steps

Step 1

Create a taxonomy, let's say it's called "Delivery methods", with terms "Shipable" and "Download".

Step 2

For each product type, add a field like "Delivery method", which is a field "term reference" (and refer to the "Delivery methods" taxonomy).

Attentionn: make sure to check the option "attribute field settings" (enables this field to function as an attribute field on the add-to-cart-form).

Step 3

Use store / products / add product to add individual products, with a specific SKU, and for which you pick the right values for the Delivery methods taxonomy.

Video tutorials

For a more detailed video tutorial of the steps described above, refer to Drupal Commerce - Pruduct Attributes (16:13).

Before doing so, you may want to first view these related videos:

Drupal Commerce - Pruduct Types (9:11).
Drupal Commerce - Pruduct Displays (11:36).

By only reviewing/studying these 3 videos (total time = about 37 mins), you'll have a very good foundation to get started with the fundamentals of Drupal Commerce.

Commerce Backoffice

Managing products (and orders) can be confusing. However, the Commerce Backoffice module helps with that. For more details about that module, refer to my answer to the question about
Correct way for Attributes in Commerce.


How to add Properties to an Entity in code? With Drupal (v7.22) I'm using the Entity Construction Kit (ECK) module (v7.x-2.0-rc2) and want to extend the sub module called 'ECK Example' that comes with it. Currently the example module just creates an Entity using code but doesn't include any default properties like Title, Author, Changed etc. This is the current module code:

$entity_type = new EntityType();
$entity_type->name = "eck_employee";
$entity_type->label = "Employee";
$entity_type->addProperty('name', 'Name', 'text');
$entity_type->save();

How can I enable the default properties for the Entity?

I've been researching and playing around with the ECK module all day and have managed to answer my own question. Hopefully someone else will find this helpful.

To the example code listed just add these lines before the save() function is called:

$entity_type->addProperty('title', 'Title', 'text', 'title');
$entity_type->addProperty('uid', 'Author', 'integer', 'author');
$entity_type->addProperty('created', 'Created', 'integer', 'created');
$entity_type->addProperty('changed', 'Changed', 'integer', 'changed');


Does using Views Aggregation break title field as node link? I have a working View that uses aggregate to count members of Organic Groups that I modeled off of the View described here.

The title of the Groups is also included in the View; however, even though "Link this field to the original piece of content" is selected the View does not configure the Groups title as a link.

Does anyone know if this is because Aggregate is interfering with the link? Should the Aggregate settings on the title field be something specific? Or does it have something to do with the way the Organic Groups Views relationships are defined?

I can confirm this was fixed in a recent dev release of the Views module.


Imce file/image browser not showing any buttons tab I am using imce as image browser. I installed imce for filefield module to select files from imce repository and i have given all permissions as in below image

When it will go to imce repository those buttons are not showing, see the below image

I followed this link but that is not working for me.
Please help me regarding this.

Try changing the "administrative" theme - I observed this behavior with a custom theme, but it rendered the buttons if I changed themes to one of the standard themes.


Get submitted values of webform in hook_alter function how can i get the submitted field values of webform in hook_alter function.
One more question is how can i call to submit function from hook_alter function.

hook_alter_form() is only invoked during form array build time, not when the form is submitted, so it's not possible (as is trying to submit a form that isn't rendered to the browser yet). If you want to handle the submitted form values for your own custom processing, add a submit handler to the form array.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'webform_client_form_ID') {
    $form['#submit'][] = 'MYMODULE_webform_client_form_ID_submit';
  }
}

function MYMODULE_webform_client_form_ID_submit($form, &$form_state) {
  // @TODO: process $form_state['values'] as needed.
}


Redirect to a specific page in ajax callback How can I redirect to a specific page in an ajax callback using Drupal 7, I've already tested this method:

function my_ajax_callback($form, &$form_state) {
  if (!user_is_anonymous()) {
    return $form['my_fieldset'];
  }
  else {
    drupal_goto('login');
  }
}

but that code doesn't redirect to /login when current user is anonymous.

I had the same problem. You should try this:

ctools_include('ajax');
ctools_add_js('ajax-responder');
$commands[] = ctools_ajax_command_redirect('login');
return array('#type' => 'ajax', '#commands' => $commands);


How to filter a view by "Group administrators" ? In OG 7.x-2.x you can assign roles to group members and you can override roles for a specific group.
I am trying to create a view of all admin members. I am filtering the view with PHP.

Option #1: Use $roles = og_get_user_roles('node', $row->gid, $row->uid); and then check for role '3' (normally the admin role in OG).
-> the obvious problem is that if a group has overridden the default roles, its "admin" role has an other (undefined) id

Option #2: Check with the 'Administer group' permission: $administrator = og_user_access('node', $row->gid, 'Administer group ', $account);
-> However I will get all the site administrators that can administer all the group, while I am looking in this context only those explicitly accounted as group admin (that in some cases could be site admin too).

Any hint on how to filter for an user that has explicitly be granted administer group permission ?

You can add a relationship to "OG roles from membership" in your view and then filter on the OG role. No need for custom code.


How to redirect to frontpage when a node is deleted? In my client's site it is normal to delete some posts (or old posts), but I don't want a 404 error page. Instead I want the user/visitor to be redirected to the frontpage with a 301 error code.

I have installed the Redirect module, but I have not found any option for this.

I have the Rules module installed and I can create custom module rule if I need.

I found the module Save Redirect on Delete which looks like it addresses your problem. From the description:

  The Save Redirect On Delete module gives the functionality for saving redirects after deletion of entity(supported by pathauto module) having some url alias.

I haven't tried it myself but would be interested to know if it helps.


Why can't my user see the private groups they are members in? I just installed Drupal Commons 7.x-3.x. I configured two private groups, and added a normal user to them. That user can see content posted to those groups, but it cannot see the group itself, or post content to the group.

Why?

I've added the user as an administrator in the group.

I've cleared all the Drupal Caches on the performance page.

I've cleared my browsers cache.

I've logged the user in and out.

I've rebuilt node permissions.

I've run cron manually.

I've double checked the people/permissions to make sure the user had permission to create groups, just in case that mattered.

No matter what I do, if I try to go to commons/groups/privategroupname with my non-user1 user I get an "Access Denied" page.

If the user wasn't a member, it would not be able to see the content in the list on the /home page.

Public groups work fine.

When creating the private groups, I selected: "Joining requires an invitation. The group and content is hidden from non-members." in the Privacy Settings.

So, I'm at a loss. Help!

I think this has to do with publishing the content.

If I published a group that was marked as invite only, it would then show up in the list of groups as invite only, and content would only be viewable by members. Seems like an imperfect solution though, as to me, an invite only group should be hidden. But if you do use this solution, be sure to mark the content type to default to published.

There's problems with Drupal and unpublished content sometimes. In this case, the usual solution (Views won't display unpublished nodes when explicitly told to) didn't seem  to fix it.


How to add a second title to a view? I have a list ordered on a specific field. The value of this field contains yes/no.

So the list first displays all rows with yes. After that all rows with no are displayed.

I would like to display a second title before all rows with no. How to do this?

make 2 views, first view (main view) with "yes" filter. second with "no" filter, then in first view add a footer (Global: View area), place there your second view, on each view set your title as needed. you can also pass parameters in view settings.


Searching for a general approach for passing custom lists of node IDs as an argument to Views 3.x I need often to exclude (or limit to) a custom list of nodes from a view. I used to enter the PHP logic directly in the php argument code text area, but this is getting difficult to mantain. I would like to store the logic in a module or template.php.

What I need is a general approach for returning a list of nids (nid1+nid2+nid3...) in the php argument code of the view.
I have tried using the approach described here, but I can make it work only for block displays, not for page displays.

For example, I have a content type where nodes can arbitrarily be restricted to authenticated users using the Content Access module per-node settings. I need to display in a view only those nodes, excluding the ones that are visible to the anonymous users. Since there is no filter for this in views, I have built a simple function to retrieve the node IDs and store them in a variable (nid1+nid2+nid3...).

I am struggling to find out where to put this logic (theme_preprocess_views_view(), custom theme_preprocess_func(), mymodule_preprocess_func(), etc.) in order to be able to use this variable in any view PHP argument code.

TL;DR: I need a general approach for returning a list of nids (nid1+nid2+nid3...) in the PHP argument code of the view, saving the php logic in a module or theme.

What you really want is a an "argument default plugin".
There are some availible in views itself, one is the php one, which you use already.

It's really not that hard to write. You need the following hooks for it:

hook_views_api
hook_views_plugins

After this you have to create the plugin and most important write a function called get_argument() which returns the arguments.


Boost – Cache expiration does not clear cache in views pages When a node is edited and saved the Cache expiration module should clear the cache on that node, which it does. However if that same node is used in a View, I have discovered that the old content still shows. Unfortunately 90% of the main content is shown using Views.

So in the cache expiration configuration page I have ticked the "Custom pages" option and entered products|wildcard, because all sub pages after products/ contains views that need to be cleared. But this does not work.

I have tried to use drush cc views (success message), which does not work, drush cc all does not show the new content either. The only thing that actually works is to go to admin/config/performance and click the Clear all caches button.

What is the best way to sort this problem, so that the Cache expiration module also works on Views?

EDITED:

  I haven't found the solution for this problem yet. Any ideas would be
  really helpful. Anyone?
  I should probably also mention that I use the Boost module to chache my pages, along with the Cache Expiration module.

Finally the solution was simple. Apparently you cannot use aliases in the Custom pages settings in the Cache expiration module. By adding taxonomy/terms|wildcard in the custom pages box, and also setting the cache to None in each concerned View (in the Advanced section), the cache expiration worked as wanted.

Hope this helps, if anyone else has this problem.


Theme template.php functions after bootstrap I'm trying to print a drupal menu outside drupal. In order to achieve this I ran the bootstrap as follows:

drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

And I render my menu as follows:

public static function getDrupalMenu($menuName) {
        $menu_output = &drupal_static(__FUNCTION__, array());

        if (!isset($menu_output[$menuName])) {
        $tree = menu_tree_all_data($menuName);
        $menu_output[$menuName] = menu_tree_output($tree);
        }
        return render($menu_output[$menuName]);
    }

Which is basically just a copy of the menu_tree function AND with menu_tree_all_data instead of menu_tree_page_data so I get all links no matter what page I'm on.

Everything works fine so far, my menu is printed, everybody is happy... but unfortunately my links are incorrect somehow. To solve this I've used a solution for absolute links as described here:

How to force absolute links on a menu tree in Drupal 7

So I use:

function mythemename_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], array_merge($element['#localized_options'], array('absolute' => TRUE)));
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

This works fine on my drupal site, but where I call the getDrupalMenu() after initializing the bootstrap it does not work (empty result, not even the original one). I probably have to set the theme or something, but I can't find what or where to do so.

Just to be clear: when I change the code in core (menu.inc) is works fine on both sites... it just gives en empty result when I override it in the theme.

Any pointers or solutions ?

While what you are doing could work, this is not what you want to do. If you want to render your menus outside Drupal you should do it a more  robust way to implement this using Drupal best practice etc.

One way would be to

create a public URL that returns the menus. This could return just the data or markup.
Have you custom code consume the API, so you fetch the data via http instead of manually trying to bootstrap Drupal.

You also need to ask yourself why this custom code lives outside Drupal. If you can bootstrap Drupal etc, the code might as well be part of Drupal via a module.

Boostrapping Drupal yourself is possible but a lot of crazy bugs can show up. Drupal depend on a lot of various stuff like $_GET / $_POST and other stuff that you might forget to handle. Also if you update Drupal this code can easily break as you are using internal functions which can change in various ways.


Entity Reference: Filter by an entity reference view not working as expected I am attempting to get a taxonomy reference field select widget that shows a list of taxonomy terms, including some extra data from their fields. I have attempted to use the "Reference method" = "Views: Filter by an entity reference view" and then select an entity reference view I created, then in my entity reference view I have done the following:

However, this gives me only the taxonomy term name despite the settings indicating it might show all the fields inline ("Note: In 'Entity Reference' displays, all fields will be displayed inline unless an explicit selection of inline fields is made here.").

You can't at the moment.

See \Drupal\views\Plugin\EntityReferenceSelection\ViewsSelection::getReferenceableEntities(), it just uses the view to get the results and then calls $entity->label(). Which means you have no way to override that.

Which means that if you want this, you need to provide your own plugin. You can either subclass from ViewsSelection and still a view, or just extend from the default and override that method.

Might also be worth opening a feature request, I've already had this use case multiple times, and a new checkbox or option somewhere would be a nice, backwards compatible way to introduce this feature in a minor release.


Are conditional Flags possible? Say I have two Flags attached to content; for example a "mark public" flag & "mark private" flag or a "like" flag & "dislike" flag, basically opposites. Is it possible to have the first flag automatically unflag itself conditionally whenever the second flag is flagged? This is basically like using Flags as radio buttons; only one can be selected at once and the other is automatically turned off. Otherwise when using Rules to determine if particular content was flagged "Public" or Private", is difficult since users can flag the same content both "Public" and Private" at the same time.

This could be easily achieved with only one Flag. But this doesn't translate well to a "like", "dislike" flag scenario, since users can only choose to like something but not specifically to dislike. A voting module would be a good alternative for this case however the only one currently available for D7 is the Rate Module which provides ratings for only nodes and comments, not as flexible as Flag module. I have tried implementing Rules to check for if one flag is flagged make the other unflagged, but it does not work.

Any suggestions as to how to tackle this?

to do this you could use the Rules module. I tried to do a similar thing before, it works but is a little awkward. You only need an event and action, a condition isn't really needed here:

Event: "Name of flag" has been flagged,
Action: Unflag "Name of second flag"

For the second flag you would obviously do the opposite:

Event: "Name of second flag" has been flagged,
Action: Unflag "Name of flag"

Now if someone flags a node with "Like" the "Dislike" flag is almost automatically unflagged, and vice versa (I think you get the concept here). "Almost" is because while flagging works dynamically the unflagging via rules only works after page reload, in my experience at least. So to a user it will look like you can both "Like" and "Dislike" things, but after reload only the last flag will stay.


Drupal 7 default Forum styling for custom content type? Im using Drupal 7's forum module. Its working great but I need to also make a custom content type a forum.

I can allow comments on this custom content type, but can I make it have the same styling as the default forum content type?

UPDATE - The reason I need this is there are 2 user roles. Only registered users can see forums at all. Users with a special role can see private forums aswell.

By 'have the same styling', I'm assuming what you mean is have the same structure and functionality as the Drupal core forum (i.e. threaded discussions). You can always modify the content template to match the same layout and css styling of the core forum module but just enabling comments won't give you the same functionality as forums. The forums module uses comments but adds another layer of management on top which is where you get your threaded discussion. A comments-only content-type would also not integrate with forum add-ons like Advanced Forum.

You're best option is to create two distinct forums and then (as @frazras notes) use Forum Access module to control access based on your criteria.


Problem in displaying with Embedded Google Docs Viewer module I'm using Embedded Google Docs Viewer module,everything is ok except when viewing it's showing like this:

How can solve this problem?

Open the PPTX file and Save As a PPT file.  This worked for me to prevent the unexpected symbols in the google docs viewer when trying to embed a PPTX file.


Drupal 6 and Varnish Cache Is Pressflow really required for Varnish? I ask because I've set up Varnish on my server with drupal 6.30 standard, and installed the Varnish module, and it's sped up my website no end. Really amazing speed results here, and I'm getting plenty of cache hits.

So my question, what's different about the Pressflow install, and why is it required for Varnish?

Varnish and Pressflow are two different things.. Pressflow uses varnish to improve performance.. More details goes below..

Pressflow is “a derivative of Drupal core providing enhanced performance, scalability, and data integrity”. Basically, some really smart guys at Four Kitchens and elsewhere back-ported a bunch of Drupal 7 performance enhancements to the Drupal 6 (and even Drupal 5!) code base.

Pressflow adds the following features to Drupal.

Support for database replication
Support for Squid and Varnish reverse proxy caching
Optimization for MySQL
Optimization for PHP 5

What:
Varnish is an HTTP accelerator and caching reverse proxy. Varnish is all about speed. It stores as much content as it can in the fastest place possible – RAM in this case – and bypasses the expensive process of making a request to Apache.

Why:
Pressflow structures the Drupal content to be more cache-friendly, but we still need something to actually cache the content.

How:
Varnish sits in front of Apache, accepts incoming connections from browsers and, if possible, fulfills the requests from its cache. If it can’t, it passes the request on to the underlying Apache/PHP stack. It then takes the response from Apache and forwards it on to the requesting browser. If the response from Apache is cacheable, Varnish stores it in RAM for fulfilling future requests.


How to disable "all" option from contextual filter? While debugging some slow running queries I came across a "hidden feature"?  in views.
When I have a "uid" contextual filter and pass "all" as the value it will show all users.

Ok, found it. In the contextual filter there is an "Exception" option that you can expand. "all" seems to be added by default for all contextual filters.


How to sort product displays by price using search api sorts? Actually I want to do the same behaviour as in commerce kickstart 2 for sorting my products by price. I'm using search api, search api db, search api sorts, search api ranges, commerce search api modules. I have created indexed node view with views and it is working fine. I can range nodes by price... I indexed the field "field_tshirt_commerce_price_amount_decimal_asc" with my node (my product type is called tshirt). And I want to see it in my sorts, but it just writes "There are currently no fields for which sorts can be displayed." Am I missing something?

my solution is:

Fields Tab: in Related Fields section add Product-Price multi field
Field sTab: check field_product:commerce_price:amount_decimal for index (integer)
Filters Tab: enable aggregated fields.
Filters Tab: add aggregated field: name - your custom label, type of aggregation - first, Contained fields - Price > Amount (decimal)
Fields Tab: check your new aggregated field for index (integer)
Sorts Tab: now your custom aggregated field available for sort

Be sure you are using latest dev version of the Search API sorts because of the https://drupal.org/node/2202093 issue.


How to remove default form tag while rendering output in hook_theme I am customizing the login form. I have to put all the three forms(login, register, forgotpassword) into one page.
I don't want that unwanted root form tag, how can i remove that one? I am using drupal 7. This is my code.

template.php

function bartik_theme() {

$items = array();

$items['user_login'] = array(
    'render element' => 'div',
    'arguments' => array('form' => NULL),
    'variables' => array('form' => NULL),
    'path' => drupal_get_path('theme', 'bartik') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
          'bartik_preprocess_user_login'
    ),

);

return $items;

}

user-login.tpl.php

        <div id="signupbox">
            <?php
                $login_form = drupal_get_form ( 'user_login_block' );
                echo drupal_render ( $login_form );

                $forgot_password_form = drupal_get_form ( 'user_pass' );
                echo drupal_render ( $forgot_password_form );

                $register_form = drupal_get_form ( 'user_register_form' );
                echo drupal_render ( $register_form );
            ?>
        </div>

My problem is that all the 3 forms are rendering in one more form tag.

My Output:

<form action="/drupal728/user" method="post" id="user-login">

 <form>Login</form>
 <form>Password....</form>
 <form>Registration....</form>

</form>

I don't want that unwanted root form tag, how can i remove that one? I am using drupal 7.

You're attacking the problem at the wrong level - if you want to modify forms/functionality, the theme layer's too late. Specifically what's happening here is that by default forms have a theme wrapper of theme_form() which adds the form tag. The form template itself should only contain the form's children elements. (And shouldn't contain for example calls to drupal_get_function()).

Here are some ways of adding the forms:

Implement hook_menu_alter() and alter the page callback for the login page to be your own callback. This callback returns the three forms. Don't forget to check for whether the user's logged in like core does.
Create a couple of custom blocks for the other two forms and add them to the login page.
Implement hook_page_build() and add the forms there (quick and dirty!).


How to make translated taxonomy terms correctly be shown in a view? I wonder how to make a multilingual taxonomy term show up in view results.

I'm using Drupal 7. To get my terms translated, I'm using the setting Translate. Different terms will be allowed for each language and they can be translated. Next, I can edit the term, use the tab Translation, and add a translation for the name in Deutsch (and save it afterwards).

But when I then try to create a view to displays these terms(category), they get displayed for both the Deutsch and the English terms. How can I fix this?

Make use of i18nviews Modules

  Translate views using Internationalization. This is a work in progress
  and not all Views properties can be translated yet.


ckeditor.styles.js caching issue I have a new drupal install.  The only modules installed so far are devel and ckeditor.

I've added the 'styles' dropdown button and successfully directed it to the ckeditor.styles.js in my theme directory.  At the moment, I'm using a path without tokens.

Initially, I had it at the root of the theme:
/sites/mysite.org/themes/mytheme/ckeditor.styles.js

but, when I updated the file in that location, the styles dropdown did not change.  I tried resaving the ckeditor and I tried clearing all caches (from the performance section), I tried re-editing and saving the .js file (and I tried several permutations of the order); but, the dropdown would not update.  I have browsed directly to the .js file after changing to confirm that it has updated

Eventually, I discovered that the only way to get the styles dropdown to update was to place the ckeditor.styles.js file in a brand new location (each time I want it to update).

So, if I change it I need to move it to:
/sites/mysite.org/themes/mytheme/includes/ckeditor.styles.js

and if I change it again, I need to move it to:
/sites/mysite.org/themes/mytheme/includes/ck/ckeditor.styles.js
etcetera

This seems inefficient and I'm sure there must be another way.  Please let me know if you have insight into this issue.  Thanks

EDIT

I was originally experiencing this issue while using the 'ckeditor' module.  I've switched to the 'wysiwyg' module and I am not experiencing the problem any more.

I believe this is due to your browser cache, not drupal cache. If you clear your browser cache or go incognito in chrome you should see your changes.


Drupal Content Admins for specific Language For a new Project with Drupal 7 we have 4 different languages: IT, AT, EN, SP and for each language an Content Admin. We need a solution that the Content Admin see only Nodes of his language for editing. Is there a module or how to implement it?

In Drupal 8 its part of the core but for Drupal 7 try using Administration Language.


How to populate DB values in content type field, drupal 7 I have created a content type with 4 field in Drupal 7. One field is of list type, say for listing countries. I have tables in DB for saving country_id and country_name. Is there any way to connect the DB table and content type field? I want to list all these countries in the content type's country field.

You have to install Content Construction Kit (CCK) module. After installing this module you get a text field for Allowed value function in field setting of desired field. Put the function name here to get country list. Also put following function in a module.  You may have to modify query as per your requirement.  After doing all these thing you will able to get country list in that field.

function _get_country_list(){
    $country = array();
    $query = db_select('country', 'c');
    $query->fields('c', array('country_name','country_id'));
    $result = $query->execute();
    if ($result) {
        while ($row = $result->fetchObject()) {
            $country[$row->country_id] = t($row->country_name);
        }
    }
    return $country;
}


How to fix error 'This site can’t be reached' for a site installed on Amazon? I have just installed Drupal 8.1.3 on an Amazon instance using the instructions provided here.

I can connect via SSH (console) to my instance successfully.

However, when I try to browse my public DNS, I get:

This site can’t be reached

ec2-54-187-215-79.us-west-2.compute.amazonaws.com took too long to respond.

This is the first time I am performing this installation.

I have performed a DNS check and it says: Delegation not found at parent

I am wondering whether it is a Drupal related issue or not. How can I solve this?

It's because by default port 22 (SSH) comes open in your EC2 security group, but port 80 (HTTP) is not open.

You need to edit your security group. To get there, in your EC2 list, scroll all the way to the right and click on the blue security group name. You will be taken to your security group settings page, for inbound, add Custom TCP Rule of port 80

  PS: If you're going to use HTTPS might aswell open port 443 (HTTPS)


How to resolve error Font-awesome library could not be found? For some reason my Drupal 8 installation is issuing this error after I installed and enabled Fontawesome (via the commerce module).

I don't know

I think this is the dir it is asking me to check, but all seems fine

You need to download FontAwesome and move files into the /libraries directory. It is explain in the documentation of the module here

And you had a clear warning message explaining that. You could have read the README.txt


Drupal entity metadata wrapper no bundle property Using <?php
$wrapper = entity_metadata_wrapper('node', $nid);
?>

When I $wrapper->title->value(); I get error msg that property Title does not exist....

Using Entity 7.x 1-8 and D7.56. I am aware that $nid can be a node (from node_load) or a node id.

What am I missing?

I solved it applying this patch:
https://www.drupal.org/project/entity/issues/2819665

although I to be honest don't understand why...


Adding a view to node edit form How to attach programmatically a view to the edit node form in Drupal 8?

In D7 I could achieve this by using this code

/**
 * Implements of hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id){

  // target a single form only
  if ($form_id == "form_id") {

    $form['html_markup'] = [
      '#markup' => views_embed_view('name_of_view','default'),
      '#weight' => 1
    ];
  }
}

I'm looking for a way how can it implemented in D8.

Any tips will be appreciated!

I researched this for a while, then I found a sample implementation in modules/views/tests/modules/views_test_data/src/Form/ViewsTestDataElementEmbedForm.php:

$form['view'] = [
  '#type' => 'view',
  '#name' => 'test_view_embed',
  '#display_id' => 'embed_1',
  '#arguments' => [25],
  '#embed' => TRUE,
];

In that file it is used in FormBase::buildForm, but it works nicely also in hook_form_FORM_ID_alter(); I reported another example in this comment to a similar post.


Filter Images, Audio and video from Media in Views? I am using media selector module. I have a field collection item in my content type called media. I added a image field in field collection item. I created a view to display the images of a content. I uploaded 2 images and 1 youtube video. I dont want to show video in view result.

You may consider to use File: Mime type filter instead of File: Path.

For all video files the Mime type always has a pattern: video/[video source or format]

it might be for example:

video/youtube
video/vimeo
video/quicktime
video/mpeg
video/mp4

Applying the filter File: Mime type contains video will solve the problem for all video files, not only youtube.


How do i show/hide page content depending on the users role? I am creating a site that has several roles.  When some one who is logged in goes to a certain page I want the page to determine what content needs to be displayed depending on what roll they are.

Example.  If the user is attached to the "teacher" role then they will see "Hello teacher thank you for visiting our site" then it might have two buttons that leads them to certain pages.  If they are attached to the "student" role they will see "Hello student thank you for visiting our site" then the two buttons would be different and lead them some where else.

Is there a module that could help with this?

There are two good ways you could go about this.

Install Panels and
enable Page manager. Panels has a huge collection of what are called
'visibility rules' for individual panes. These allow you extremely
fine grained control over who sees what portion of the page. Panels
offers a lot of power, but brings a lot of complexity along with it.
Put your messages each in their own block. Blocks come with the ability to show and hide for certain roles.
This method is much simpler, but if you have a lot more content than just
the welcome message you want to show and hide panels
will end up being a more customizable solution.


Override form element twig template I want to override the twig template for specific fields on a form which I created via the Contact module in Drupal 8.

However, I can't find any documentation, and the suggestions in the HTML comments also doesn't show me anything useful.

Basically I want to override, a custom field (field_phone) and a standard field (Sender name) on a specific contact form the following values:

form-element.html.twig
form-element-label.html.twig
input.html.twig

Is that possible? And what are the file name suggestions?

The Drupal Themable Forms module adds some helpful theme suggestions for form elements that are missing from core.

The added theme suggestions for form elements are:

  form-element--[form-id]--[element-type].html.twig
  form-element--form-id--[form-id].html.twig
  form-element--type--[element-type].html.twig
  form-element.html.twig


Where do you set/change the SKU for a new/existing product? - Drupal 7 Commerce i can't seem to find where to change the sku for an existing product variation. is this even possible? Where do i set this?

You can change the product SKU on the product edit form.

e.g:

admin/commerce/products/1/edit

Because products are referenced on line-items etc.. by their ID value, it's actually OK to change SKU for existing products if needed.


Views view unformatted and outputting taxonomy custom field Original problem I had was I setup a taxonomy called Category.  I added some vocabulary to my Category taxonomy. Some of the terms I added have contain spaces.  The labels should have spaces so I want to keep them there. I want to remove the spaces from the Category name when they are output in the views view unformatted templated.

This would solve all of my problems if I can get those spaces out of the category names.  I setup a custom field on the taxonomy terms to handle this, but I don't know how to access the custom fields of the taxonomy term from the views-view-unformatted.html.twig template.  Is there a preprocesser function that can do this?  Something where I can convert the category and just remove the spaces or change the value output from label to field_nospace_category ?

More experimenting

I setup a view of type page to display the articles in my content type Articles.  I'm using using the unformatted list and I created a custom template called views-view-unformatted--my_view_id.html.twig.  I see that this is the template that is outputting on my page.

I'm trying to output the taxonomy terms custom field as a class on the div that has {{ row.attributes.addClass(row_classes) }}

The div should end up looking like this:

...

I've tried several variations to try to get to the values. Inside of the for row in rows loop, i put:

{{ node.category.entity.field_category.value }}
{{ row.content['#node'].field_category.getValue().0.target_id }}
{{field_category}}
{{row.content['#elements'].field_category.getValue().0.target_id}}

I have tried to debug using Kint, Dump but my install keeps either throwing errors (out of memory) or blank white page.

Please help. Thank you in advance.

Finally got it to work!  Here is how you do it.  Assuming your field is called field_category.  My template is called views-view-unformatted--my_view_id_name.html.twig.

{% set my_category_id = row.content['#row']._entity.field_category.0.target_id %}

It does seem pretty silly to me that it has to be that long.  It would be very cool if it was something more like this and that all values associated to a post (since that is what is being output) are available and exposed to the view.

row.content.field_category.id

And if all taxonomies that are added would follow the same path.  Seems unneccesary to have it in #row, then in _entity, then needing to add a 0 and use some oddly named thing called target_id.

I'm new to Drupal coming from Wordpress.  There are nice clean functions in wordpress for getting taxonomy ID and names.  Not too many hoops you need to jump through.


How do I separate the "Product" select list & "Add to cart" submit form in a node product display? I have a node product display which references 2 different products.

When I use the code below, it prints out both the "product select" form + the "add to cart" submit form. How do I print them out separately?

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

Alternatively, how do I change the HTML to print this 2 form out? I am looking for a way to theme my product display differently.

I realized that you can't, albeit after several hours of experimenting.

However, you can add a price field (and other fields) to your "add to cart" form by adding a "price" form item element. Follow the instructions here for more details: http://drupal.org/node/1300798#comment-5328550

Tell me if this helps.


How to fix a broken or missing block? On a Drupal 8 site, I see an error on a block which says:

  This block is broken or missing. You may be missing content or you might need to enable the original module.

How can I resolve this error?

You have created a Custom block and the custom block was placed in a region, then you lost the custom block maybe was deleted or you made a Config Export from one environment and a Config Import in other. So the custom block is no longer exists but in the Block layout page (admin/structure/block), the references exist.

So, remove the missing Block from the Block layout page (admin/structure/block) and create again the Custom block and place it again in the region.

There is a core issue open discussing this problem: https://drupal.org/project/drupal/issues/2756331

This can also be overcome by using this module: https://www.drupal.org/project/recreate_block_content


Setting the mime-type for files stored in the private directory How do I set the mime-type of files being served from the drupal private directory. I have a webm file in the private directory, and the I've added the <video> tag to the page using a tpl file.

I've tried adding

AddType video/webm .webm

to .htaccess. I've also tried installing the module "File Mime" to try to set the right mime type. I've tried adding

function mymodule_file_download($uri){
    return array('Content-type: '.'video/webm');
}

to my .module file. Nothing seems to work. Any help would be appreciated.

Editing includes/files.mimetypes.inc is a core hack, which you should strive to avoid.

Instead, use hook_file_mimetype_mapping_alter():

function mymodule_file_mimetype_mapping_alter(&$mapping) {
  // Add new MIME type 'video/webm'.
  $mapping['mimetypes']['webm'] = 'video/webm';
  // Add new extension '.webm' and map it to the 'video/webm' MIME type.
  $mapping['extensions']['webm'] = 'webm';
}


Best way to add fields to the output of a View I have a View which lists contents. I have a few fields which are composite and have a somehow convoluted logics. What I do is to add some "dummy" fields (for example, the nid of content, or the rf (reference) of product) to the View, and then in hook_views_prerender I modify the value by the logic. For example:

$brand = $view->result[$key]->taxonomy_term_data_field_data_field_brand_name;
if($brand == WHATEVER){
   $view->result[$key]->field_field_field_rf_product_3[0]["rendered"]["#markup"] = function_to_substitute_complicated_value($parameters);
 ...
 }

Now, is it good idea to have this dummy field, field_rf_product_3, or would it be better to create a new field programmaticaly, and if so, how could it be done to be added at the proper place (after a given rendered field) in the View output?

Basically you have two options to do this elegantly.

Use the computed field module (it also includes the storing of the results in the database to save on heavy SQL queries as mentioned in the comments). It comes with a lot of documentation and examples at the bottom of that page.

  Computed Field is a very powerful field module that lets you add a
  custom "computed fields" to your content types. These computed fields
  are populated with values that you define via PHP code. You may draw
  on anything available to Drupal, including other fields, the current
  user, database tables, you name it. (Feeling the power yet? :) ) You
  can also choose whether to store your computed field values in the
  database with other content fields, or have them "calculated" on the
  fly during node views. (Although you should note that Views use
  requires database stored values.) This field is literally the Swiss
  Army knife of fields. So start cooking up your PHP based values!

Write a custom views field handler (example is for Drupal 7 only!). In drupal 8 some functions like hook_views_api() have been removed and the info file has changed.

This is less flexible and will result in a specific field to choose when building a view. However sometimes less flexible can be desirable.

In order to do this you need to write a custom module. Consisting the following folder and files:

module_name

module_name.info
module_name.module
views

module_name.views.inc
module_name_handler_field_custom_field.inc

The .info file describes the module:

name = Custom Views field
description = Provides an additional field to Views
core = 7.x
package = Views
dependencies[] = views
files[] = views/module_name_handler_field_custom_field.inc

The .module file contains the module, which in this case is only a function to let Views know where to look for its files.

/**
 * Implements hook_views_api().
 */
function module_name_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'module_name') . '/views',
  );
}

The file module_name.views.inc performs the logic for Views. If you define a new entity, use hook_views_data(). If you alter an existing entity such as a user or a node, use hook_views_data_alter() but also look at the example code of hook_views_data().

In order to create a new field based on another field, you can do something like this:

/**
 * Implements hook_views_data_alter().
 *
 * Defines a new field with content built by the module_name_handler_field_custom_field class.
 * @see hook_views_data()
 */
function hook_views_data_alter(&$data) {
 // This example adds an example field to the users table.
  $data['node']['example_field'] = array(
    'title' => t('Example field'),
    'help' => t('Some example content'),
    'real field' => 'field_existing_base_field', // Enter the base fields system name here.
    'field' => array(
      'handler' => 'module_name_handler_field_custom_field',
    ),
  );
}

Finally the handler, which composes the field. Here we can alter the output of the field using the real field we defined above as input.

class module_name_handler_field_custom_field extends views_handler_field {
  /**
   * Render a computed field value (multiplied by 5).
   */
  function render($values) {
    // Load real field value.
    $real_value = $this->get_value($values);
    // Generate new value.
    $value = function_to_substitute_complicated_value($real_value);
    return $this->sanitize_value($value);
  }
}


Which is the correct "code/word" for Language Neutral? I read an article from Gábor Hojtsy where he says:

  Language neutral uses the language code 'und', which means undefined
  and is specified to be used for such cases by the ISO 639 standard.

But when you go to read the ISO 639 you can find:

  und, for "undetermined";

And you can find inside Drupal the "Language Neutral"

I ask the question because I'm writing a module where I need to have a word to identify the nodes that don't have a defined language. So, which is the word to use, Neutral, Undefined or Undetermined?

From Drupal constant LANGUAGE_NONE api documentation Und stands for undetermined and in Drupal 8 it is called LANGCODE_NOT_SPECIFIED


multisite multilingual over different directory I have multi-site over directories.

xx and yy are made symbolic links are linked to same Drupal directory

domain.tld/xx
domain.tld/yy

And on .htaccess it requires to have different Rewritebase

RewriteBase /xx

or

RewriteBase /yy

which is not possible.

Any other way to solve using someother  RewriteRule?

Note: It is also multilingual website

Update: It is Drupal 7.26

I was solved this problem . May be use to you for only Multisite

Solution:

Give Symbolic link form mulitsite to site1
Executed that command line
ln -s /var/www/multisite /var/www/site1

Rename example.sites.php to sites.php
// 192.168.1.99 local IP address
$sites['192.168.1.99.site1'] = 'site1';

put this line in sites.php

No need to use RewriteBase /xx

If you have any problem in symbolic link use this link https://superuser.com/questions/68685/chown-is-not-changing-symbolic-link

and also How do I setup multiple sites with one database in Drupal 7 (or) Multisite Apache configuration with Drupal


Taxonomy List in node/add Capitalize all letters in the parent only I have a strange customer request for a taxonomy list users select from while adding content.

The request from the customer is have the parent vid show up in ALL CAPS and the children to be left alone.

What's the best approach to this?
Thanks

You can use hook_form_alter to alter the node form. This way you don't alter the data in the vocabulary.

function modulename_form_alter(&$form, &$form_state, $form_id) {
  // For 'article' content type.
  if ($form_id === 'article_node_form') {
    $lang_code = $form['language']['#value'];
    foreach ($form['field_dd'][$lang_code]['#options'] as $key => $value) {
      // Check if option starts with '-' sign. Only child starts with '-' sign.
      // If yes, then continue.
      if (strpos($value, '-') === 0) {
        continue;
      }
      // Else capitalize all the characters.
      $form['field_dd'][$lang_code]['#options'][$key] = strtoupper($value);
      // $form['field_dd'][$lang_code]['#options'][$key]['#attributes'] = array('class' => array('option-blue'));
    }
  }
}

Note:

Refer this link for your new use case: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#attributes


add field to bundle through hook_entity_bundle_field_info I am trying to add two fields to one of the node bundles.

I define the fields in this function:

function concertbeheer_entity_bundle_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle, array $base_field_definitions){
    if($entity_type->id()=="node" && $bundle == "concert")
    {
        $concert_fields['laatste_uitvoering'] = \Drupal\Core\Field\BaseFieldDefinition::create('datetime')
                ->setLabel('Laatste uitvoering')
                ->setRequired(TRUE)
                ->setDisplayConfigurable('view', TRUE)
                ->setDisplayConfigurable('form', FALSE)
                ->setDisplayOptions('view', array(
                    'label'=>'inline',
                    'type' => 'datetime_plain',
                    'weight' => '999',
                ));
        $concert_fields['eerste_uitvoering'] = \Drupal\Core\Field\BaseFieldDefinition::create('datetime')
                ->setLabel('Eerste uitvoering')
                ->setRequired(TRUE)
                ->setDisplayConfigurable('view', TRUE)
                ->setDisplayConfigurable('form', FALSE)
                ->setDisplayOptions('view', array(
                    'label'=>'inline',
                    'type' => 'datetime_plain',
                    'weight' => '999',
                ));

        return $concert_fields;

    }

}

but the documentation on https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21entity.api.php/function/hook_entity_bundle_field_info/8.2.x says I also need to provide a fieldStorageDefinition through hook_entity_field_storage_info()

I can actually configure the visibility of the fields but when I save something to them it isn't saved in DB. Probably because of the lack of a FieldStorageDefinition

But I don't know how to get started on that and, as usual, there seems to be no documentation available on how to do it

This code example would set up a basic storage definition:

function mymodule_entity_field_storage_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'node') {
    $definitions['my_bundle_field'] = \Drupal\Core\Field\BaseFieldDefinition::create('string')
      ->setName('my_bundle_field')
      ->setLabel(t('My new bundle field'))
      ->setTargetEntityTypeId($entity_type->id());
    return $definitions;
  }
}

You can look up examples in field.storage.*.yml files from a config export.

If you don't find the right examples there, you can configure a field in UI and then export the storage of this field to get a blueprint for the storage definition you need in this hook.


How to display, search, and edit form submissions from a table with WebForm? I am very new to Drupal and I've been recently assigned a task to make a form for a single admin to register people and their info. It's basically a registration/contact form, except these people aren't users; the admin is just recording their info in a database.  The admin needs to be able to search for a person's name through a table for a previous person's registration, and be able to click an edit link for that person as well.

I have been messing around with the WebForm module, and it is great for making the form itself, not to mention it already has a 'Results page' with a table of past submissions. However I do not know of a way to add a search functionality to the 'Results page'.

I also heard that you can put a search bar in Views module, so I messed around with getting the WebForm submission data into a table in Views, thanks to the Data and WebForm SQL Views modules. However I do not know how to put the corresponding edit link next to each of the rows in the table.

Is there a better approach to solving this problem? It seems I have to either handle adding searching functionality for a field, or making it possible to point to the WebForm edit functionality from each row of the Views table.

At this point, I am also wondering if its better to just hand code everything in php.

No, it would not be better to hand-code everything in PHP.  However, if you need heavy customization of the display of data the Webform module is probably the wrong approach.  Webform is good at getting data in but the options for getting data out are somewhat limited.

Instead, I would make a custom content type and use Views to handle the display.  To do so, navigate to /admin/structure/types/add and call it something like "People."  Once you perform the basic configuration and click save, you will be taken to the Content types administration page; click manage fields for the content type you just created.

Here, you should be able to add the same kinds of fields that you added in Webform.  This interface is not quite as clean as Webform's but it will allow you full flexibility with Views.

Once you have configured the fields as you like, go to the permissions page (/admin/people/permissions/roles) and make sure only the admin role has access to create and edit content of that content type.

Then, configure your view(s).  Basically, you'll want a view of node content of the content type you just created.  Add the fields you want to display under Fields.  To get search filters, add Filters and check Expose this filter to users.  When you set up the view(s), make sure to set the permissions using the Views edit interface so that only the admin role can access the views.

This is a very rough overview but hopefully it can get you started in a productive direction.


PHP code in contextual filter (Views) I would like to get a value from the reference node of the node_id
I used this code for PHP code in Contextual filter...

$node = menu_get_object();
if ($node->type == 'trailer_videos'){
       $mynode = node_load($node->nid)->field_trailer_video_of[und][0][target_id];
return $mynode;
}

The result is CORRECT!! but the page itself throw 2 errors:

Notice: Use of undefined constant und - assumed 'und' in eval()
Notice: Use of undefined constant target_id - assumed 'target_id' in eval()

Whats wrong with my code above????

Why don't you use entity metadata wrapper?  your code will be:

$node = menu_get_object();
    if ($node->type == 'trailer_videos'){
           $wrapper = entity_matadata_wrapper('node',$node);
           $mynode = $wrapper->field_trailer_video_of->value();
           return $my_node;
     }

If you don't want to use entity module, use kpr of devel module to get the right syntax, as Ollie said quotes are needed.


How can I give a list_string BaseFieldDefinition in a content entity a default starting value? I have an entity with a list_string field in my content entity that outputs to the entity form as a list of checkboxes. IE:

$fields['colors'] = BaseFieldDefinition::create("list_string")
  ->setSettings([
    'allowed_values' => ['blue' => 'Blue', 'red' => 'Red', 'green' => 'Green']
  ])
  ->setLabel('Color')
  ->setDescription('Select color')
  ->setRequired(TRUE)
  ->setCardinality(-1)
  ->setDisplayOptions('form', array(
    'type' => 'options_buttons',
    'weight' => 2,
  ))
  ->setDisplayConfigurable('form', TRUE);

Is there a way for me to give this field a default starting value. IE, when the user creates a new entity, red and green start out selected on the form?

You can use setDefaultValue method:

BaseFieldDefinition::setDefaultValue([['value' => 'red'], ['value' => 'green']])

That will also work for entities not created in the UI.


How can I accomplish this using Views? I'm using Drupal 7.28 and Views 7.x-3.7.

I've created a vocabulary called Products and listed terms under this including Living, Dining, Storage, Office, Outdoor.

I've also created a content type called Products with an auto term reference for users adding content to select one of the terms.

What I want to do is create a view that will automatically create a page for each of the terms, so in the menu it will have for example Living, Dining, Storage, Office, Outdoor etc. I don't want to have to create a new view each time a term is added.

Then, if a term has been added but there is no content that has selected a term the page will just say 'No products' (which i know this bit can be done by setting a No Results behaviour.)

Thanks very much for reading.

For anyone else looking for help with this in the future, here's how I did it:

I used the default pages that are generated for each term - I didnt realse that all terms generate a page that displays all of the content associated with them.

I then enabled and used the default Taxonomy view to edit the output of the term pages.

I also used the Taxonomy Menu module to create a menu of each taxonomy,


How to add two fieldConditons in Entity field Query? Is this the correct way to add field Conditions

$query->entityCondition('entity_type', 'profile2')
   ->entityCondition('bundle', 'user_profile')
   ->fieldCondition('field_town_city', 'value', "%".$search_title."%", 'LIKE')
   ->fieldCondition('field_land_state', 'value', "%".$search_title."%", 'LIKE');

You can chain multiple field conditions, however I'd probably try something like this (haven't tested it):

->fieldCondition('field_town_city', 'value', $search_title, 'CONTAINS')

The EntityFieldQuery::fieldCondition() invokes the addFieldCondition() method, see the possible $op values on api.drupal.org:

https://api.drupal.org/api/drupal/includes!entity.inc/function/EntityFieldQuery%3A%3AaddFieldCondition/7


Views Bulk Operations skip confirmation I have defined a custom action for a VBO.

function expense_action_info() {
  return [
    'expense_finalize_action' => [
      'type' => 'node',
      'label' => t('Approve and finalize expense'),
      'behavior' => ['changes_property'],
      'configurable' => TRUE,
      'vbo_configurable' => FALSE,
      'aggregate' => FALSE,
    ],
  ];
}

I've also created a configuration form for this action and rendered it along with the view.

function expense_finalize_action_form($settings, &$form_state) {
  $form['kickback_note'] = [
    '#type' => 'textfield',
    '#default_value' => 'new'
  ];
  return $form;
}

function expense_finalize_action_submit($form, $form_state) {
  return ['kickback_note' => $form_state['values']['kickback_note']];
}

When I submit the VBO I've redirected to page of this custom form and I need to click on the Next button to proceed the action.
As I have provided required values in the form I need to skip this step. Is it possible?

In your view, under your field configuration, at "select bulk operation" section under the action there should be a "Skip confirmation step" option; uncheck it and you're ready to go


Manage Display Field Label not changing: inline does not work I have the same problem as question 212176 and discovered it has to do with CSS.
I have 2 (local) sites both with module ds enabled. I configured in both a field where I want the label and the value in one line: inline

With the classy-theme, this works fine.
With the IceMagic theme it does not.

I have "inspect element"-screenshots of both. As there is no float:left with IceMagic, I believe this is the reason the label stays above.

Where and how to fix this?

Solved!

I used Firefox Developer Edition tools to find the relevant css code in a working theme.
I copy/pasted this piece of code into the styles.css file of the theme of my choice and adjusted the class-names (single dash instead of double-dash and double-underscore).

To tidy up I should make a subtheme with my adjustments and leave the theme as it is.

I made even a little improvement to the original code: label will be aligned to left of the column and content to the right (I am using Display Suite to divide the content into a column view)

.field-label {
  font-weight: bold;
}
.field-label-inline .field-label {
  float: left; /* LTR */
}
.field-label-inline .field-items {
  float: right; /* LTR */
}
.field-label-inline .field-label,
.field-label-inline > .field-item,
.field-label-inline .field-items {
  padding-right: 0.5em;
}
[dir="rtl"] .field-label-inline .field-label,
[dir="rtl"] .field-label-inline .field-items {
  padding-left: 0.5em;
  padding-right: 0;
}
.field-label-inline .field-label::after {
  content: ':';
}


Display Suite - code field retrieve the first value in a multivalue field? I've created a view mode to display a value multivalue image field. The rendered entity utilizes display suite to display the images. There are 12 images in this field for this all of the nodes of this content type.

Is it possible to just display one image instead of the 12 as a code field in display suite? If so how does one do that.

When you have a multivalue field, you have also a # on the format column. It represents all images. If you want to show only one or two images, you must write 1 or 2 in the box.

Good luck


Call a custom form in node template Following the Form generation example from DrupalAPI (https://api.drupal.org/api/drupal/core!core.api.php/group/form_api/8.1.x), I have an error when I call the form in my template_preprocess_node.

Here's my code.

mymodule/src/Form/ExampleForm.php

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class ExampleForm extends FormBase {
  public function getFormId() {
    // Unique ID of the form.
    return 'example_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    // Create a $form API array.
    $form['phone_number'] = array(
      '#type' => 'tel',
      '#title' => $this->t('Your phone number')
    );
    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
    // Validate submitted form data.
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Handle submitted form data.
  }
}

mytheme/mytheme.theme

function cmimmo_preprocess_node(&$variables) {
  $variables['simulator_form'] = \Drupal::formBuilder()->getForm(\Drupal\mymodule\Form\ExampleForm::class);
}

I get the following error:

  InvalidArgumentException: The form argument Drupal\mymodule\Form\ExampleForm is not a valid form. in Drupal\Core\Form\FormBuilder->getFormId() (line 190 of core\lib\Drupal\Core\Form\FormBuilder.php).

Why am I getting that error message? What is wrong with my code?

My Form folder in my module was named "Forms". Be carefull with your file structure. Too bad the error is not very explicit. It should be "not exist" instead of "not valid".


How do I make a Views jump menu to anchor links? I would like to make a jump menu in Views that is displayed as an attachment to the same Views page, which displays a list of documents.  I would like the jump menu to display the titles of all the documents, and have the destination for each link be an anchor tag on the same page, adjacent to the actual document.

I have applied output rewriting (in the Page display) to each document title, like this: [title]. In my jump menu display, attached to the top of the page display, I can rewrite the output of the title field to be mypage#[title], and that works, but the items in the jump menu are ugly.

What do I need to do in order to make the items in the jump menu display simply as [title], but jump to mypage#[title]?

Thanks!

Add another title field for the document, which will have no rewriting at all and hide it from the output (checkbox "Exclude from display"). Then use this second title field when for displaying in jump menu.