How to access backbone model from custom javascript outside of view I was wondering if there is a way to access backbone model variable outside the scope of the backbone model/view.This is the backbone model:
function (Backbone, Drupal) {
  Drupal.addToCart.AddToCartModel = Backbone.Model.extend({
    defaults: {
      defaultVariation: '',
      selectedVariation: '',
      attributes: {},
      renderedAttributes: {},
      injectedFields: {},
      variations: {},
      variationCount: 0,
      quantity: 1,
      unit_box: 1,
      type: 'commerce_product_variation_attributes'
    },
    initialize: function initialize() {
      this.set('variationCount', Object.keys(this.get('variations')).length);
      this.set('selectedVariation', this.getVariation(this.get('defaultVariation')));
    },
    // ... some getter and setter
  });
})(Backbone, Drupal);

And this is the view:
(function ($, Backbone, _, Drupal) {
  Drupal.addToCart.AddToCartView = Backbone.View.extend({
    initialize: function initialize() {
      var _this = this;

      var defaultVariation = this.model.getVariation(this.model.getDefaultVariation());
      _.each(this.model.getAttributes(), function (attribute, i) {
        var attributeFieldName = 'attribute_' + attribute.id;
        if (defaultVariation.hasOwnProperty(attributeFieldName)) {
          _this.selectedAttributes[attributeFieldName] = defaultVariation[attributeFieldName];
        }
      });
      this.render();
    },

    events: {
      'click .form-submit': 'addToCart',
      'change .attribute-widgets input[type="radio"]': 'onAttributeChange',
      'change .attribute-widgets select': 'onAttributeChange',
      'change .variations-select select': 'onVariationTitleChange',
    },
    // ... events on...
    onAttributeChange: function onAttributeChange(event) {
      Drupal.detachBehaviors();
      this.selectedAttributes[event.target.name] = event.target.value;
      var selectedVariation = this.model.getResolvedVariation(this.selectedAttributes);
      this.model.setSelectedVariation(selectedVariation.uuid);
      var injectedFields = this.model.getInjectedFieldsForVariation(selectedVariation.uuid);
      Object.values(injectedFields).map(function (injectedField) {
        $('.' + injectedField.class).html(injectedField.output);
      });
      Drupal.attachBehaviors();

      $('.banner.wishlist').click(function () {
        $.ajax({
          url: Drupal.url('wishlistupdate'),

          method: 'POST',
          data: JSON.stringify([{
              'variation': $(this).attr('data-variation')
            }]),
          contentType: 'application/json;',
          dataType: 'json'
        }).done(function (data) {
          // <--- HERE IS WHERE I WANT TO ACCESS BACKBONE MODEL TO ALTER SOME PROPERTIES
      });
     });
    },
// ... some other events subscribers
});
  Drupal.addToCart.AddToCartView.prototype.selectedAttributes = {};
})(jQuery, Backbone, _, Drupal);

And this is the theme settings:
(function ($, _, Drupal, drupalSettings) {
  Drupal.theme.addToCartButton = function () {
    return drupalSettings.theme.commerce_cart_flyout_add_to_cart_button;
  };
  //... some other themes functions
  Drupal.theme.addToCartVariationSelect = function (_) {
    return function (args) {
      var template = _.template(drupalSettings.theme.commerce_cart_flyout_add_to_cart_variation_select);
      return template(args);
    };
  }(_);

  Drupal.addToCart = {};
  Drupal.behaviors.addToCart = {
    attach: function attach(context) {
      $(context).find('[data-product]').once('flyout-add-to-cart').each(function (k, el) {
        var model = new Drupal.addToCart.AddToCartModel(drupalSettings.addToCart[el.dataset.product]);
        new Drupal.addToCart.AddToCartView({ el: el, model: model });
      });
    }
  };
})(jQuery, _, Drupal, drupalSettings);

What I want is to access backbone model variables on ajax done method, but I didn't find a way to do it.

After some debugging I have found I can access drupalSettings object and It has a property addToCart with all the data I need.


multiple login destinations I need to send users to the user/me/edit page to change their password when they log in the first time and also in cases of password reset.  The rest of the time they need to go to an internal dashboard page.

What is the best combination or single module to accomplish this?  I've tried numerous combinations of login destination and login toboggan as well as each on it's own but can't get it right.

Both my register and login forms are on my homepage.

I think the first code snippet on this post is what you are looking for:

<?php

function mymodule_user($op,&$edit,&$account,$category = NULL){
    if($op == 'login'){
        if($account->login == 0){ // check the last login
        //do stuff here
        }
    }
}

?>

It uses hook_user() to check the user's last login time. If it's 0, meaning she haven't logged in before, you can redirect the user with a function like drupal_goto.

You'll have to create a simple custom module and place your code in mymodule.module file.

If you are not comfortable writing a module for this, you can try creating a rule with the Rules module, I haven't been able to test this approach, but here are the basics:

Create a new rule:

Event: 'User has logged in'
Condition: 'Data comparison' - check the data called
'site:current-user:last-login' or 'account:last-login' for last login information.
Action:'Page redirect'


Concatenate url() in Twig I tried to do something that I thought was fairly simple, but it's giving an error:

Notice: Array to string conversion in __TwigTemplate_dd3a187031be000574aa6b2149e8b2daacd4f1d086638752b5928811c46b8adf->doDisplay() (line 132 of vendor/twig/twig/lib/Twig/Environment.php(462) : eval()'d code).

What caused it:
{% set support_url = url('<front>') ~ 'support' %}

So I tried something:
{{ url('<front>') }}

{% set support_url = url('<front>') %}
{{ support_url }}

{% set support_url = url('<front>') ~ 'support' %}
{{ support_url }}

The result of the above is:

http://www.example.com/
http://www.example.com/
Arraysupport

What is going on?

The url function returns a render array, so you can't concatenate it with a string.  You must first convert it to a string.

try render_var():

{% set support_url = render_var(url('<front>')) ~ 'support' %}

<h1>{{ support_url }}</h1>

This will convert the render array created by the url function to a string.


Styling first results from a View differently from the rest We have a page that needs to render an unspecified number of nodes, newest one first. The first result needs to be displayed as a very large "hero unit", the next 4 results as a group of four large results and the rest in a more compact form.

#########################
#                       #
#       Result 1        #
#                       #
#########################

############ ############
#          # #          #
# Result 2 # # Result 3 #
#          # #          #
############ ############

############ ############
#          # #          #
# Result 4 # # Result 5 #
#          # #          #
############ ############

Result 6      Result 7
Result 8      Result 9
Result 10     Result 11

I've been trying to style this by displaying the View as unformatted fields, but the nodes are still rendered separately from the structure, making it hard (or impossible?) to specify how we need them rendered.

Is there some module that will help us style the View with more precision or is there some feature in Views that I have overlooked?

You can do this in views with the pager offset option. Based on your example above, create a view like normal as a page or block then under the Pager set "Display a specified number of items" and set to 4 and then under the pager's options set offset to 1. This will skip the first item. Then add an attachment display to the view and attach it to your page or block before and set pager to "Display a specified number of items" and 1. Next add another attachment display and attach after and set "Display a specified number of items" to 6 and then under the pager's options set offset to 5. Now you override each display and output only the fields you need for each one.


EntityQuery condition on translation status Im currently using Drupal::entityQuery() to build a list of node.

I need to be able to query only contentEntities that have a specific translation not published. I struggle because I don't know how to make a condition on an entity translated field/property.

to sum up:
How to query all nodes that have 'de' translation AND which their 'de' translation are not published?

Is there a way to do it with Drupal::entityQuery() or should I directly go with altering the query with QueryInterface::addTag() where I would be able to customize the query?

This should do what you want.  Note that the id's will load the default language, you will need to use getTranslation(langCode) to get the translated node.

$query = \Drupal::entityQuery('node');
$query->condition('status', 0);
$query->condition('type', YOUR_TYPE);
$query->condition('langcode', 'de');
$ids = $query->execute();


How can I handle the user access to specific taxonomy terms? There is a node form with a term reference field which's terms list I want to filter based on users/ permissions.

I've tried several modules in which I can grant access either user- or role-based for individual terms. Unfortunately, these settings are ignored by "Views: Filter by an entity reference view" when the views list is built.

So, whats the right way? How do I globally set per-term permissions that are also respected by views listings?

I've thought about changing the term controller but I don't see an access function there. Do I have to use a query alteration? Is there a hook?

You may want to try to add your own access checking in your view. A possible way to do so, is to use the Views Access Callback module, which you can yuse in a custom module to make your view perform whatever access check you want. Some more details about this Views Access Callback module (from its project page):

Provides callback-based access control for Views.
Available callback functions are defined by modules using hook_views_access_callbacks() function (in the same way as in hook_perm()), then could be set in in view's "Access restrictions" configuration.

The Community documentation for this module provides some extra details to get you going with this module.


What is the best tagging widget? I was using the tagging module as my tagging widget until its status changed to Maintenance status: Unsupported. Now I'm looking for a replacement. After searching drupal.org I figured out there is not stable tagging widget module for D7:

nice_tags only D6
tag_editor only D6
active_tags dev version and not works as expected
community_tags tagging content in view mode not in add/edit
form

Is there any other tagging widget which I overlooked?

Finally, I decided to use the Autocomplete Deluxe module as tagging widget.

  This is an enhanced autocomplete element, that uses the JQuery UI autocomplete. It will also implement a widget for taxonomy and lists.
  There is also an implementation for the References module: Autocomplete Deluxe for References.


Add an input[type="file"] label i need to style the input[type="file"], the only way to really style them is to add a <label> which has the same for value as the input's id. Drupal does not provide a correct label in single input[type="file"] upload and even no label in multiples input[type="file"] uploads. Is there any way to solve this issue?

Thanks

The markup in Drupal is always overridable.  In this case, you may either need to use a hook_form_alter() in a custom module to modify the label html, override the theme_file() theme function (which is responsible for producing the markup for the file input element), or theme the form specifically.  Any of these three methods should be able to meet your needs (although I'm partial to the theme_file() approach).


How to use $contexts in Page Manager Im trying to make a selection rule for variants in Page manger and it includes some data comparison so it has to be in php. My field data is inside the context, so the $contexts variable can be used, but I cant get the proper way to use it. In my case it is a field value of the node, that is specified by the argument in URL "node/%nid".

Can some body please give an example code to extract the field value from context in php?

First of all, I want to point out that since this issue got closed in December, ctools got much better support for handling fields in access rules.

With that said, $contexts, have a data value, which is either an object, or an array of objects, depending on whether your plugin requires one or more contexts.

To make the code easier to read, I usually do something like this: $node = $context->data;

Brief example code:

function contact_info_pane_content_type_render($subtype, $conf, $args, $context = NULL) {
  $block = new stdClass;
  $block->content = '';
  $node = $context->data;
  $block->content .= count($node->field_email) > 0) ? $node->field_event_mail['und'][0]['email'] : '';
  $block->content .= count($node->field_phonenumber) > 0) ? $node->field_event_phonenumber['und'][0]['safe_value'] : '';

  return $block;
}


Drupal 7 Commerce Price field not available to views I am using Drupal 7.14, Commerce 7.x 1.3 and Views 7.x 3.3
I have created several products and also the corresponding content. Fields in the product type are the default fields - Product SKU, Title, Price and Status. The content type upon which the related content is based contains some extra fields - image, product reference, author and type.
The products display singly perfectly with all the fields (image, Body, price, author, add to cart button and type).
If I create a view to display this content the available fields do not contain the price field. All the others, however, display correctly.
Why is the price field missing?
Would be most grateful for anyone's help.

You should add Content: Product as a relation to this view. Then you'll have all the fields from the product available in the view.


Navigation buttons move around in responsive design This is kinda strange, I'm using flexslider module in which my navigation (previous & next) buttons on 1320.css, 960.css are centered fine on the slider. When I get to the 720.css and mobile.css versions, that is when the navigation buttons start moving around. Ether they are above or below the slider in which it's pointless to even display on :hover by ~50px. Lastly, I noticed that I cannot replicate on a desktop/laptop browser, it only gets introduced when using a mobile browser of any type of phone.

Below is a snippet from the Flexslider.css that pertains to the navigation:

.flex-direction-nav a {width: 30px; height: 30px; margin: -20px 0 0; display: block; background: url(images/bg_direction_nav.png) no-repeat 0 0; position: absolute; top: 50%; z-index: 10; cursor: pointer; text-indent: -9999px; opacity: 0; -webkit-transition: all .3s ease;}

Any ideas?  I noticed that 'top: 50%;' moves them  but again a can't figure out a way to get them to always be centered. Also I should mention that I'm running alpha 2 but it occurs in both alpha 3 and alpha 2 versions of Flexslider.

To resolve the problem I used @media queries to distinguish a different setting per responsive size. So I copied and deleted line 58 (.flex-direction-nav a) from the flexslider.css. I then added this code below at the bottom for the CSS file. *This is also good as you can control the nav in all variations of size. for instance in the mobile @media below I dropped the buttons down (removed top: 50%; from mobile) some to help users see the flexslider on a small screen better.

/* LANDSCAPE PHONE TO DOWN MOBILECSS */
@media all and (max-width: 480px) {
  .flex-direction-nav a {width: 30px; height: 30px; margin: -20px 0 0; display: block; background: url(images/bg_direction_nav.png) no-repeat 0 0; position: absolute;  z-index: 10; cursor: pointer; text-indent: -9999px; opacity: 0; -webkit-transition: all .3s ease;}
}

/* LANDSCAPE PHONE TO PORTRAIT TABLET MOBILECSS */
@media all and (max-width: 759px) {
  .flex-direction-nav a {width: 30px; height: 30px; margin: -20px 0 0; display: block; background: url(images/bg_direction_nav.png) no-repeat 0 0; position: absolute;  z-index: 10; cursor: pointer; text-indent: -9999px; opacity: 0; -webkit-transition: all .3s ease;}
}

/* LANDSCAPE DESKTOP TO DOWN 720CSS */
@media all and (min-width: 481px) (max-width: 760px) {
  .flex-direction-nav a {width: 30px; height: 30px; margin: -20px 0 0; display: block; background: url(images/bg_direction_nav.png) no-repeat 0 0; position: absolute; top: 50%;  z-index: 10; cursor: pointer; text-indent: -9999px; opacity: 0; -webkit-transition: all .3s ease;}
}

/* PORTRAIT TABLET TO LANDSCAPE AND DESKTOP 720CSS */
@media all and (min-width: 761px) and (max-width: 980px) {
  .flex-direction-nav a {width: 30px; height: 30px; margin: -20px 0 0; display: block; background: url(images/bg_direction_nav.png) no-repeat 0 0; position: absolute; top: 50%;  z-index: 10; cursor: pointer; text-indent: -9999px; opacity: 0; -webkit-transition: all .3s ease;}
}

/* LAGACY DESKTOPS 960CSS */
@media all and (min-width: 981px) and (max-width: 1289px) {
  .flex-direction-nav a {width: 30px; height: 30px; margin: -20px 0 0; display: block; background: url(images/bg_direction_nav.png) no-repeat 0 0; position: absolute; top: 50%; z-index: 10; cursor: pointer; text-indent: -9999px; opacity: 0; -webkit-transition: all .3s ease;}
}


Relation: add button to create node related to current node I have 2 Content types called Schools and School News and i want to add a add News Button to those School pages, so editors can create a new post for this specific school. I thought about using relation module as i am using it already for other things.

Would it be possible to create such a button that adds a hidden field with the ID of the specific school into the news form? That way i could add this relation while saving the node. Is there any other way to get this kind of functionality with relation?

The Node Reference URL module works with the References module to accomplish this feature. When you add a node reference field, you can specify Reference From URL widget which will auto fill the field from a value in the URL. You can also specify (in the field settings) to display a link on the referenceable node.

In your case, you would create a node reference field on School News that references Shools. Just select the Reference From URL widget and configure as necessary.

There's an older lullabot video about creating image galleries in Drupal 6 that demonstrates how it works. The Drupal 7 version has the same features and works the same way.


In which file should I write db_add_field function I am writing a module for which I have to add a field to my database. So I need to use  db_add_filed function, So in which file I should use this function? I mean should it be in .module file or .inc file?

I think you should write your code for adding new field in DB in your .module file.
Here is the code for you :

function xyz_schema_alter(&$schema) {
  // Add field to existing schema.
  $schema['node']['fields']['show_in_inbox'] = array(
    'type' => 'int',
    'length' => '4',
    'default' => '1',
    'not null' => TRUE,
    'unsigned' => TRUE,
    'description' => 'Field added by xyz module',
  );
}

function xyz_enable(){
    if (!db_field_exists('node', 'show_in_inbox')) {
        $schema = drupal_get_schema('node');
        db_add_field('node', 'show_in_inbox', $schema['fields']['show_in_inbox']);
    }
}

The new field will be added in your existing database on enabling this module.


How to display unanswered questions when using the Answers module? I am using the Answers module 7.x-4.0-rc2. I would like to have links to different displays of the questions view so that one link goes to only unanswered questions and the other link shows all. When I go to filter options, I'm not sure how to filter the content by if there is an answer or not.

This is done on the demo site but out of the box, the 7.x-4.0-rc2 version of the module doesn't have any special views. See screenshot of the demo site below.

Edit:
When attempting to import views from https://www.drupal.org/node/2783513#comment-11516603 as suggested, I get the following errors for rankings.txt, repeated:

  Style plugin datatables is not available.
  Field handler userpoints_total.points is not available.
  Field handler userpoints_total.last_update is not available.
  Sort criterion handler userpoints_total.points is not available.
  Unable to import view.

When importing questions.txt, I get:

  Style plugin datatables is not available.
  Field handler userpoints_total.points is not available.
  Field handler field_data_field_tags.field_tags is not available.
  Relationship handler userpoints_total.uid is not available.
  Unable to import view.

I attempted installing answers_userpoints (which is uninstalled) but could not do so because it depends on userpoints_rules, which couldn't be found or downloaded.

Edit 2: I took a look at the code for the exported view for unanswered questions, and believe that section I need to replicate is the following portion; this issue I am having is that COUNT(Flags: Flagged) doesn't seem to be available as a filter but I do have flag enabled.

/* Filter criterion: COUNT(Flags: Flagged) */
$handler->display->display_options['filters']['flagged']['id'] = 'flagged';
$handler->display->display_options['filters']['flagged']['table'] = 'flagging';
$handler->display->display_options['filters']['flagged']['field'] = 'flagged';
$handler->display->display_options['filters']['flagged']['relationship'] = 'flag_content_rel';
$handler->display->display_options['filters']['flagged']['group_type'] = 'count';
$handler->display->display_options['filters']['flagged']['operator'] = '!=';
$handler->display->display_options['filters']['flagged']['value']['value'] = '1';

The demo site related to the 7.x.-4.x version of the Answers module uses a further enhanced version of the most recent dev release. Some of the views have been enhanced and will be pushed to D.O soon. These views are available already in Views Export format via files attached to comment #5 in issue #2783513).

The (new) view related to the questions has a tab titled "unanswered", which contains the list of all questions that are "unanswered".

So to actually answer your question, I suggest you experiment a bit with the updated view of questions as contained (in export format) in the issue mentioned above.

Disclosure: I'm a co-maintainer of this module.


How to change relative path in hyperlinks? I have developed site on localhost in XAMPP, in the folder C:\xampp\htdocs\drupLC
Then everything uploaded to the server.
And now all (or many of them) hyperlinks looks like

example.com/drupLC/user
example.com/drupLC/admin (etc).

How can I get rid of drupLC from all hyperlinks? Because my site is not usable.

You may need to:

Check the setting for RewriteBase in .htaccess (e.g make RewriteBase /)
Check the $base_url setting is correct (Should be automatic in D8).
Clear all caches ( Admin > Config > Development > Performance > Clear cache )

If you have inline links in body content with incorrect URLs, that's a different story, but the above may help with the standard stuff.


add class to fields on login block I am using drupal 7 and would like to customise my login form block.

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

if ($form_id == "user_login_block") {
        $form['links'] = Null; // Remove Request New Password and other links from Block form
        //$form['links']['#markup'] = t('Forgotten Password?') . ' ' . t('Forgotten Password?') . ''; // Remove Request New Password from Block form
        //$form['links']['#markup'] = ' ' . t('Register') . '' . ' ' . t('Forgotten Password?') . ''; // Remove Request New Password from Block form

    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

    $form['name']['#attributes']['class'][]= array("nui-input");

    $form['name']['#title'] = Null; // Change text on form
    $form['name']['#attributes'] = array('placeholder' => t('username'));
    $form['pass']['#title'] = Null;
    $form['pass']['#attributes'] = array('placeholder' => t('password'));

}

}

In the above code the following line does not seem to have any effect on my field :

$form['name']['#attributes']['class'][]= array("nui-input");

This is what will work

    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

   $form['name']['#title'] = Null; // Change text on form
    $form['name']['#attributes'] = array('placeholder' => t('username'));
    $form['pass']['#title'] = Null;
    $form['pass']['#attributes'] = array('placeholder' => t('password'));

    $form['name']['#attributes']['class'][] = 'nui-input';

Here is the reference : How do I use hook_form_alter() to add CSS classes to a custom input field in user_register_form?


Display page created using panel programatically I am using Drupal 7 and Panel module.

I have created custom page using panel module. page-welcome

I want to render this page on the following url user/%user/my-profile

Is there any way to print page programatically..

You should be able to set the path to /user/%user/my-profile within Panels.  For an example of this, look at the "User edit template" override provided with Panels, which, if enabled, overrides /user/%user/edit.

To set the path in Panels, go to /admin/structure/pages, choose the page you wish to edit, click Basic under Settings, and set the Path.

The help text there states the following:

  The URL path to get to this page. You may create named placeholders
  for variable parts of the path by using %name for required elements
  and !name for optional elements. For example: "node/%node/foo",
  "forum/%forum" or "dashboard/!input". These named placeholders can be
  turned into contexts on the arguments form.


How to translate a mobile jQuery menu? Drupal.t('Select a page') is not translated into another language (mobile menu) after clearing cache and translating strings through the translation menu. What should be added or changed to get translation?
Theme Growth Lite (jquery.mobilemenu.js)

var settings = {
    combine: true,  //combine multiple menus into a single
select
    groupPageText: 'Main',  //optgroup's aren't selectable, make an option for it
    nested: true,                   //create optgroups by default
    prependTo: 'body',              //insert at top of page by default
    switchWidth: 480,               //width at which to switch to select, and back again
    topOptionText: Drupal.t('Select a page')    //default "unselected" state
},

Actually, it was not clear but there is an option in the theme itself to put change the phrase 'Select a page' and it becomes untranslatable. You have to remove it in the theme itself and change it in the file jquery.mobilemenu.js and then translate it through Drupal.


How to easily alter an entity's base field definition per bundle We are using the group module in Drupal 8, which introduces a custom entity "group". This entity features a "label" base field with the title "Title". As groups administrator, you can create several different group types, which are handled as fieldable bundles of the group entity and inherit its label base field.

Depending on the group type, we wish to override the generic label title within forms, views, templates, and so on to e.g. 'Label', 'Name', 'Branch', 'Department', 'Section', ...

However, the group entity does not expose the label title within its config form as the node module does. So we tried overriding the title using hook_entity_base_field_info_alter() like this:

/**
 * Implements hook_entity_base_field_info_alter().
 */
function mymodule_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'group' && !empty($fields['label'])) {
    $fields['label']->setLabel(t('Name'));
  }
}

Which works, but changes the title for all bundles.

Our next try was hook_entity_bundle_field_info_alter(). It exposes bundle information, but it does not allow for base fields to be altered. Trying to re-add the base field definition with a different title (in order to let the core merge the field definitions and override the base field definitions) caused different run-time exceptions.

So we ended up in manually altering form build arrays and widget titles, which may cause trouble later when the amount of group types is increasing.

How can we alter the base field's title on a per-bundle base without having to extend the group module or manually altering all occurrences of our group entities' field labels?

Bundle specific labels for base fields are stored in label of a BaseFieldOverride config entity:

  Defines the base field override entity.

  Allows base fields to be overridden on the bundle level.

  Plugin annotation

@ConfigEntityType(
  id = "base_field_override",
  label = @Translation("Base field override"),
  handlers = {
    "storage" = "Drupal\Core\Field\BaseFieldOverrideStorage",
    "access" = "Drupal\Core\Field\BaseFieldOverrideAccessControlHandler",
  },
  config_prefix = "base_field_override",
  entity_keys = {
    "id" = "id",
    "label" = "label"
  },
  config_export = {
    "id",
    "field_name",
    "entity_type",
    "bundle",
    "label",
    "description",
    "required",
    "translatable",
    "default_value",
    "default_value_callback",
    "settings",
    "field_type",
  }
)

When you get a base field from EntityFieldManager::getFieldDefinitions($entity_type_id, $bundle), set a new label for the field and save the field definition, then this label is not stored in the entity type (which would not be possible, because this is in code and the same for all bundles), but in the mentioned base field override.


how to override the HTML of the search results page? i am trying to override the search-results page with no luck. All of the answers that i have found in google are about overriding the results template. since i am using a subtheme i want to override the whole HTML output of the page. I want to change the header, the footer etc..

Instead results page is using the page.tpl.php. So far i found this How to theme the page template for search results with no success.
Any correct way i can succeed this ?

Also i am trying to force the search to search only in specific content types and languages! Any suggestions?

Hope this will help you,

In Drupal 7, you can also achieve this

Using theme_search_results OR theme_search_result to override search results page.

theme_search_results : invoked for the search result page.

OR
theme_search_result : invoked to render a single result

Both these theme functions used in a template file (search-results.tpl.php and search-result.tpl.php).

Source


View (Read Only) access for Drupal Commerce - Orders I have added 2 attributes into my Drupal Commerce Orders set of fields - Fivestar Rating & Review. My client needs me to show the ratings and reviews in "Testimonial" section of home page in ticker format. I was able to successfully integrating Rating + Review into Orders and show the testimonial section for users with role as Admin.

Below pictures show my configuration:

A chunk (Sidebar second) of my home page for Admin user with running ticker:

However, the anonymous visitor to the webiste is not able to view the contents of this ticker because anonymous does not has view access on the orders created in the website:

Now, ideally the orders (and hence the ratings and reviews inside the orders) should be accessible to the anonymous users. But yet, the ticker does not show any content and also the Orders page "/admin/commerce/orders" will not show any orders at all:

I need help with the following 2 items:

Why anonymous user is still not granted the view permission for the orders (and it's contents). How can I fix this?
I do see that there is a security implication even to provide "View" access to anonymous users on my Orders. How serious is this threat? Is there any safer way to get view access to orders and its contents? What is the right way of doing this?

Thanks for any efforts by the community to help me out :)

Inside your view, what are you access options (located under "Page Settings")?  That would be a good place to start.  Naturally clear the cache after every permission change.

I also don't think it would be wise to allow anonymous users to view any/all orders.


Rule action seems to fire unexpectedly I've got a problem with a rule that fires when I think it shouldn't.

Background:

My Article content type uses the Node Expire and Node Expire Extras modules to control automatic Article expiration.  I have the following “expiration” rule defined:

{ "rules_expired_content" : {
    "LABEL" : "Expired Content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "node_expire" ],
    "ON" : { "node_expired" : [] },
    "DO" : [ { "node_unpublish" : { "node" : [ "node" ] } } ]
  }
}

The rule sets the Article to “unpublished”.

My users asked that I provide a way to selectively control if an email is sent when an article is updated.  To that end, I added a field (radio button) to the Article content type called “Send email” (field_send_email).  The field defaults to “Yes”.  I wrote two rules: when content is saved and when content is updated.  The rule for saving content seems to work flawlessly.  Here's the rule for updating the content:

{ "rules_updated_article_email_notification_cloned_" : {
    "LABEL" : "Updated Article Email Notification",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Email" ],
    "REQUIRES" : [ "rules", "node_expire", "php", "mimemail" ],
    "ON" : { "node_update--article" : { "bundle" : "article" } },
    "IF" : [
      { "data_is" : { "data" : [ "node:field-send-email" ], "value" : "1" } },
      { "AND" : [ { "NOT node_expire_rules_expired_check" : { "node" : [ "node" ] } } ] }
    ],
    "DO" : [
      { "mimemail_to_users_of_role" : {
          "key" : "xxxxxxxxxxxxxxxxxx",
          "roles" : { "value" : { "4" : "4" } },
          "active" : "1",
          "from_mail" : [ "node:author:mail" ],
          "subject" : "An article has been updated: [node:title]",
          "body" : "[node:body]",
          "attachments" : "\u003C?php\r\nforeach($node-\u003Efield_file_attachments[\u0027und\u0027] as $file) {\r\n  echo  drupal_realpath(file_load($file[\u0027fid\u0027])-\u003Euri);\r\necho (\u0022\\n\u0022);}\r\n?\u003E",
          "language_user" : "1",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Problem:

When cron runs, it fires the rule that detects that an Article has expired.  That changes the state of the Article to “unpublished”.  Changing the state forces the above updated Article rule to fire.  Today, December 31st, a series of emails was sent out unexpectedly.  I know it has something to do with the Updated Article rule, but, I am at a loss to pinpoint the cause.  I checked the system log and noticed the following line that looked suspicious:

  Notice: Undefined property: stdClass::$expired in
  node_expire_rules_expired_check() (line 98 of
  /XXXX/XXXX/public_html/XXXXX/sites/all/modules/node_expire/node_expire.rules.inc).

I did not find any reported problems with the Node expire module and the above message.

I also ran some localhost tests and the code appeared to run correctly although I'm not sure I'm simulating an expired node correctly by forcing it from Cron.

I've turned on Rules debug so that it will show in the system log for future issues with Articles.  However, if anyone can shed some light on this, I'd greatly appreciate it.

UPDATE:  I have since found that this bug is inconsistent.  I had one article that was unpublished and had the problem, and, another that did not.  The only difference seems to be that the one with the problem was also originally promoted to the front page.

UPDATE 2: I'm not getting any response on the Drupal Node Expire page.  If anyone knows of an alternative mechanism to implement Node expiration without using the above mentioned modules, I'd love to hear.

Your problem is node_unpublish will be saving the node, triggering the second rule on node_update--article thereby actioning mimemail_to_users_of_role

Looks like you'll need to add a condition to make sure the email should be sent. For example, you could check the updated node is not being set to "unpublished"

"IF" : [ { "data_is" : { "data" : [ "node:status" ], "value" : "1" } } ],


Is there module to generate form and save into content type? I find a module to create a form like Webform or Entityform and save this one directly into a node (specific content type or entity).

Entity form creates entity instances called "Entity form submissions". So the answer to your question is "Entityform module."


How do I customize node.tpl to print an entity reference field in a specific format I have content type called collection that has an entity reference field (multiple)  that references another content type called books. One the collection node page, I want to render all of the books as linkable titles, with a button next to them that says "add annotation to book" this will link the user to create a third type (entity) that has a reference field pre - populated.

So my question is this, how do I re- format the books fields of my collection type to meet my use case. So far I have toyed with the following options.

Add a custom node--book.tpl.php file and place code that take the reference field, loops through it, does and entity load on each referenced entity, then adds custom html to the add form of the third content type
Alter the field--type.tpl,php and add it in here - can't figure out this option because I'm not sure how to retrieve the nid, link, and title from this template.
Create a custom display for my book entity and set the field on my collection to render as this new display (this created other problems, I don't know if it's possible to have a separate template for this new display, and this complicated it).

I think your information architecture in inverted. It sounds more like Book is in Collection rather than Collection has Book. In other words Collection is an attribute of Book, not the other way around. It would be easier to put the reference field on the Book content type, and create a view of all Book s referencing a Collection to display on the Collection content type, using a Contextual filter to limit the list. No changes required to template files!

Then using the Prepopulate module, you can use the $_REQUEST variable to set your field_book value in the new node, and it is a simple matter to add  the Content:Nid to the view and rewrite the field to create the link.

First, install and activate the Prepopulate module. Then put your Entity Reference field on the Book content type and limit it to the Collection content type. Then add an Entity reference field to the Annotation content type and limit it to Book. In other words, you are identifying the Book the annotation belongs to.

Then create a view of Content (Book) with a display type of Block. In the views configuration, create a Contextual filter on Content: Collection (field_collection) and configure it to Provide default value and select Entity ID from URL.

Add the field Content:NID and configure the field. Select Rewrite results  and check Rewrite the output of this field. In the text box enter something like:

Annotate this book

(%5B = "[" and %5D = "]"). The actual link code may vary depending on how you have implemented the Entity reference field in your content type. The module has good documentation.

Save your view and under /admin/structure/block find the block created by the view and set it to display only on pages of type Collection.

The block will then display a list of book titles (linked to their content) and the custom link to add an Annotation page with field_book prepopulated, and limited to those books which reference the Collection being viewed.


Views: Display filters as a HTML UL list of links with clean mark up I have a View that has a filter which allows users to select nodes that contain specific taxonomy terms.

I would like to display this as a HTML list of links (<ul>). How can I do this?

Steps I have tried

1. Using Better Exposed filters

This displays a filter as links. But the links are displayed wrapped in <Div> tags instead  of a UL tag.

2. Using Views template

Using views-exposed-form.tpl.php lets you access the exposed form, but it doesn't let you access the actual widget the makes up the filter.

3. Using Custom Code

This page says you can turn a select list into links via a custom module. But it requires Javascript to make the links work, which seems bad practise to me

I would also go for step 3 and you really need JS for that option. Another option is, structure the links as it looks when you do a search like so..

// Merge the option name or key into the link
$link = "your-view?category=" . $select_option;
// Create the link
$somearrayforULlist[] = l($select_option, $link);

So when you click one of the links, it would reload the page and your view will use the filter values in the URL in your form.


D7 Views 3: Filter by relationship based on nid and uid I have a content type 'contest' that users submit guesses on. The guesses are entities that have uid and nid properties (and of course their own primary key, gid) to record the user and the contest to which they belong.

How can I display only contests on which a given user has submitted guesses?
A similar problem might be how to return only nodes of a certain type that a given user has commented on.

By using this within hook_views_data and setting the query to distinct (which I'd also prefer not to have to do) within the Views UI, I was able to confine the results to nodes that have guesses whose nid property match - but I can't figure out how to confine the results to nodes with guess entities whose nid AND uid properties match:

$data['node']['nid'] = array(
    'relationship' => array(
        'handler'        => 'views_handler_relationship',
        'base'           => 'entity_guess',
        'base field'     => 'nid',
        'title'          => t('Has guesses'),
        'label'          => t('contests with guesses'),
    ),
);

Thanks so much!

I ended up achieving the result that I wanted with hook_views_query_alter:

function site_views_query_alter (& $view, & $query)
{
  if ('block_3' == $view->current_display) {
    $account        = SiteUser::loadByID(arg(1), TRUE);
    $query->where[] = array(
      'conditions' => array(
        array(
          'field'    => 'node.nid',
          // Return just the IDs
          'value'    => SiteContest::getContestsPlayedBy($account, TRUE),
          'operator' => 'in',
        ),
      ),
      'args'       => array(),
      'type'       => 'AND',
    );
  }
}


Can Views theme/rendering be disabled programmatically? I'm creating an RSS feed using the default Views RSS display and by default it contains a bunch of characters that cause the output to be invalid XML  (I believe this has to do with bugs within views related to double encoding or other related functions).

So, to fix this, during hook_views_pre_render() I am able to manipulate the fields with php to output valid stuff.  Within views when I "preview" the output, it's exactly as it should be.

However, when I view the actual feed output at the views url, the output has changed because views has done something to render it (I'm assuming putting it thru the theme system, etc), thereby breaking my 'fixes' again.

Manipulation of the fields in the UI (ie. using plain text as the output, etc) don't do what i need, so those aren't an option.

Is there a way, programmatically, to disable any rendering and tell views to output exactly what I'm seeing in the Views preview?

Yes under Advanced there is a Theme Information link that will show you template file(s) that you can override to meet your needs depending on the display format selected (fields, rendered entity, etc).

If you need to change how the page itself renders for example, you can also affect the sitewide theme function used to create the url by changing theme function in hook_menu.


Programatically adding Taxonomy text field This code is throwing a FieldException: Attempt to create a field of unknown type text. in field_create_field() (line 111 of C:\wamp\www\local.test\modules\field\field.crud.inc).

field_cache_clear();

//Create the appropriate field type
$field = array(
    'field_name' => 'stock_exchange',
    'type' => 'text',
    'module' => 'text',
    'active' => '1',
    'cardinality' => '1',
    'settings' => array(
        'max_length' => 64
    )
);
field_create_field($field);

$instance = array(
    'field_name' => 'stock_exchange',
    'entity_type' => __DEFAULT_VOCAB_MACHINE_NAME,
    'bundle' => __DEFAULT_VOCAB_MACHINE_NAME,
    'label' => 'stock_exchange',
    'description' => 'stock_exchange',
    'required' => false,
    'widget' => array(
        'type' => 'text_textfield'
    ),
);

At my wits end here trying to figure out why this won't work. Have tried clearing cache and it's not that.

For some reason it's not accepting a basic text field.

Any ideas?

The only way to achieve adding a text field to a Taxonomy Vocabulary is to place it in the hook_enable() function of your module.

If it's outside of that the "Text" module won't be loaded and you'll receive the error above.

If anyone has a way around that please let me know.


Block body translation for Full HTML content After block creation and put HTML content in body field I can't translate this content because of:

  The string blocks:block:1:body for textgroup blocks is not allowed for
  translation because of its text format.

If I change to plain text I can translate block but it is treated as plain text while displaying. Do I have to create another block with the same HTML content (translated) and select to display only in specific language?

Found it,
http://drupal.org/node/1298440#comment-5127390

  In case anyone else has trouble finding this setting, it's at
  Configuration > Regional & Language > Multilingual Settings > Strings

  (admin/config/regional/i18n/strings)


Link's href value gets lost I am trying to make a link on node by returning this array(The array is being formed in the function by the name buildLinks() ):

     $links[$key] = array(

    'title' => $definition['title'],

    'href' => $this->urlGenerator->generateFromRoute('module.show_format.' . $entity->getEntityTypeId(), array('module_format' => $key, 'entity' => $entity->id())),
  );

but on the page the link title is appearing but the link's href value gets lost(I mean title is appearing but it is not appearing as link).What am I doing wrong?

Update: The above array is being returned over here:

    return array(
    '#theme' => 'links__entity__module',
    '#links' => $this->linkBuilder->buildLinks($this->request->attributes->get($entity_type)),
  );

So is there is a possiblity that I am doing something wrong over here?

Looks like the documentation around that theme function is out of date. Please open a bug report for that.

Have a look at template_preprocess_links, it is using url, not href. Also not that url is a Drupal\Core\Url object, not a path, so your code should look like this:

$links[$key] = array(
  'title' => $definition['title'],
  'url' => Url::fromRoute('module.show_format.' . $entity->getEntityTypeId(), array('module_format' => $key, 'entity' => $entity->id())),
);


Multiple textfield values im using form api and im trying to get to make a group of fields under one type, like for example a phone number, you would have 3 fields 1 being the area code and the other 2 fields being the number

I would think it would be something like this..

$form['phone'] = array(

    '#title' => 'Phone Number',
    '#tree' => TRUE
);

$form['phone']['areacode'] = array(
    '#type' => 'textfield',
    '#maxlength' => 3,
    '#size' => 3,
);

$form['phone']['number1'] = array(
    '#type' => 'textfield',
    '#maxlength' => 3,
    '#size' => 3,
);

    $form['phone']['number2'] = array(
    '#type' => 'textfield',
    '#maxlength' => 4,
    '#size' => 4,
);

or even something with options like this for example

$form['phone'] = array(
    '#type' => 'textfield',
    '#title' => 'Phone Number',
    '#tree' => TRUE,
    '#options' => array(
        array(
        '#value' => t('areacode'),
        '#maxlength' => 3,
        'size' => 3,
        ),
        array(
        '#value' => t('number1'),
        '#maxlength' => 3,
        'size' => 3,
        ),
        array(
        '#value' => t('number2'),
        '#maxlength' => 4,
        'size' => 4,
        ),

    )
);

Either way I want to have multiple textfield values under one form type.

Thanks

I know there are some parent and tree properties in the form API, but to be honest I have never use it. In a case like your I will create 3 text fields with a limit number of characters depending on the part of the phone number I am collecting ( 3 (for area code) - 3 (for the exchange) - 4 (for the number) ) and then on the submit function of the form I will concatenated them together.

function my_module_example_form($form, &$form_state) {

// If you edit the data using the same form then
// get the previously store phone number
$phone = $phone_from_db;

$form['area-code'] = array(
  '#type' => 'textfield',
  '#title' => t('Area Code'),
  '#default_value' => substr($phone, 0, 3),
  '#size' => 3,
  '#maxlength' => 3,
  '#required' => TRUE,
);

$form['exchange'] = array(
  '#type' => 'textfield',
  '#title' => t('Exchange'),
  '#default_value' => substr($phone, 3, 3),
  '#size' => 3,
  '#maxlength' => 3,
  '#required' => TRUE,
);

$form['number'] = array(
  '#type' => 'textfield',
  '#title' => t('Number'),
  '#default_value' => substr($phone, 6, 4),
  '#size' => 4,
  '#maxlength' => 4,
  '#required' => TRUE,
);

  return $form;
}

function my_module_example_form_submit($form, &$form_state) {
  // Submission logic.
  $phone = $form_state['values']['area-code']+$form_state['values']['exchange']+$form_state['values']['number'];
  // Save the $phone variable
}

There are also a couple of modules with the ability to add phone fields and they even offer validation of the phone number depending on the country.

http://drupal.org/project/phone
http://drupal.org/project/cck_phone
http://drupal.org/project/location


hook_node_update hitting a wall with a loop I created I have a taxonomy multi-select list that is used to create/delete entries in a field collection in my node. I'm trying to make it so that if the user deselects an item from the taxonomy list, the corresponding field collection item is removed from the node. I'm running into an issue when the user deselects a single option because of the way my code runs but I can't figure out how to get around it:

I compare the selected options in my taxonomy list
I look for them in the field collection
If they don't match, I add the differences to two arrays
I loop through one array to remove the field collection item if it's not selected in the taxonomy list AND
I loop through the other array to add the field collection item if it's on the taxonomy list but not the field collections

With one option difference, my code seems to delete and add it back so there is no visible change. It works if I make multiple selection changes. I believe the issue is that ->delete() and ->save() save the node as well so my code runs more than it needs to.

function commitments_node_update($node) {

    if($node->type == 'commitment') {
        if (!empty($node->field_conditions['und'])) {
            $condition_name = array();
            $fc_name = array();
            //Create array of all FC conditions
            foreach ($node->field_conditions['und'] as $key => $value) {
                $fc = entity_load('field_collection_item', array($value['value']));
                foreach($fc as $condition) {
                    $fc_name[] = $condition->field_condition_title['und'][0]['value'];
                }
            }

            //Create array of all selected conditions
            foreach ($node->field_commitment_conditions['und'] as $conditions){
                $tid = $conditions['target_id'];
                $term = taxonomy_term_load($tid);
                $condition_name[$tid] = $term->name;

            }
            $fc_diffs = array_diff($fc_name, $condition_name);
            $condition_diffs = array_diff($condition_name, $fc_name);

            //Remove deselected conditions from FC
            foreach ($fc_diffs as $fc_diff) {
                foreach ($node->field_conditions['und'] as $item) {
                    $fc = entity_load_single('field_collection_item', $item['value']);
                        $fc_name_search = $fc->field_condition_title['und'][0]['value'];
                        if ($fc_diff == $fc_name_search) {
                            $fc->delete();
                        }
                }
            }

            //Add new conditions to FC
            foreach ($condition_diffs as $key => $value) {
                $term = taxonomy_term_load($key);
                $condition = $term->field_condition['und'][0]['value'];
                $condition_name = $term->name;

                $condition_fc = entity_create('field_collection_item', array('field_name' => 'field_conditions'));
                $condition_fc->setHostEntity('node', $node);
                $condition_fc->field_condition_title[LANGUAGE_NONE][0]['value'] = $condition_name;
                $condition_fc->field_condition[LANGUAGE_NONE][0]['value'] = $condition;
                $condition_fc->save();
            }

        }
    }
}

Thanks to #drupal on IRC, I now only run the code once by creating a static cache:

function commitments_node_update($node) {

    if($node->type == 'commitment') {
        if (!empty($node->field_conditions['und'])) {
            static $cache = array();
            if(array_key_exists($node->nid, $cache)) {
                return;
            }
            $cache[$node->nid] = true;
            $condition_name = array();
            $fc_name = array();
            //Create array of all FC conditions
            foreach ($node->field_conditions['und'] as $key => $value) {
                $fc = entity_load('field_collection_item', array($value['value']));
                foreach($fc as $condition) {
                    $fc_name[] = $condition->field_condition_title['und'][0]['value'];
                }
            }

            //Create array of all selected conditions
            foreach ($node->field_commitment_conditions['und'] as $conditions){
                $tid = $conditions['target_id'];
                $term = taxonomy_term_load($tid);
                $condition_name[$tid] = $term->name;
            }

            $fc_diffs = array_diff($fc_name, $condition_name);
            $condition_diffs = array_diff($condition_name, $fc_name);

            //Remove deselected conditions from FC
            foreach ($fc_diffs as $fc_diff) {
                foreach ($node->field_conditions['und'] as $item) {
                    $fc = entity_load_single('field_collection_item', $item['value']);
                        $fc_name_search = $fc->field_condition_title['und'][0]['value'];
                        if ($fc_diff == $fc_name_search) {
                            $fc->delete();
                        }
                }
            }

            //Add new conditions to FC
            foreach ($condition_diffs as $key => $value) {
                $term = taxonomy_term_load($key);
                $condition = $term->field_condition['und'][0]['value'];
                $condition_name = $term->name;

                $condition_fc = entity_create('field_collection_item', array('field_name' => 'field_conditions'));
                $condition_fc->setHostEntity('node', $node);
                $condition_fc->field_condition_title[LANGUAGE_NONE][0]['value'] = $condition_name;
                $condition_fc->field_condition[LANGUAGE_NONE][0]['value'] = $condition;
                $condition_fc->save();
            }
            unset($cache[$node->nid]);
        }
    }
}


Is it possible to build a high-traffic Drupal community website without hacking? I would like to find out from anyone that has built a high traffic Drupal community website ( a website with at least 500,000 visitors a month, with anywhere from 10,000 to 20,000 authenticated users at any one time ), is it is possible to create this kind of site without having to do a high level of hacking to make Drupal scale?  Can standard Drupal scale without a lot of query and other types of hacking / coding?

Can I install Drupal, configure the modules I need, and then add more hardware and functionality (APC, Varnish, Memcache, etc) without having to do query hacking?  How do people deal with Drupal's high number of database queries without hacking, or is there no way around having to hack?  If you have built this type of community site with numerous authenticated user, what were the biggest hurdles and stumbling blocks when it comes to performance and scalability?  I already know about auth cache and pressflow.

Drupal can serve high-load sites without hacking.

You need to use memcache to store Drupal caches not in db but in memory.
For Drupal 6 you need to use Pressflow core.
You need to use Drupal cache mechanism, its configuration much depends on what users do you have most - anonymous or authenticated.

For anonymous users Varnish can dramatically increase site performance.

Don't forget to configure cache for each View and Panel on you site.

Also Drupal 7 can work with MySQL's master-slave architecture.

Don't forget to use cdn for loading static content such as images, css, js and files uploaded by users.

If you will have search on your site - I advise you to use Apache Solr.

I have created several high-loaded sites and haven't hacked any query that was provided by Drupal core. In some cases only queries that were provided by views module were altered - but this is not a hack.

But don't think you can built a high-load Drupal site without deep knowledge of Drupal architecture, API and lot of useful modules.


Custom view single content wrapper css style My custom view which shows only two rows of data looks like this

content1
content2

but I want to display them side by side like this
content1  content2

to do this I have to apply float left and width 50% to the content wrapper css class or id
but the problem it has a long views-row views-row-1 views-row-odd views-row-first css class how do I modify this class ?

Result I need is

You can reduce the standard markup with these options in views:


View/Page with form to insert data and display it I need to create a View/Page or whatever to display a form. This form only could be viewed by registered users, and on it, the user could insert different data (text, images, etc) and then this data need to be displayed on another view/page/section of the web.

I think this is very simple to do it with Drupal, but I'm a little lost, and I need a guide or some advice to go ahead.

Sounds like you need to create a content type and add some fields to it.

After that configure permissions so authenticated users can create that content.

The follow up display of that content can probably most easily be done with the Views module.


Add option values to field that already has data I created a content type with a field "Category".

In that field I added two values:
- Books
- Movies

I inserted data in this content type and I have a view showing the content per category.
Now i need to add a new value "Series" but it shows this message:

There is data for this field in the database. The field settings can no longer be changed.

What can I do?

Thank you in advance!

You should use taxonomy to create a vocabulary named Category and add terms to it. Then add a taxonomy term reference field to your content type.


How to output from custom module without rest of theme What the proper method of outputting a page from your module without any additional theming beyond your template, for example to make a page that is good for printing?

I've tried a few different methods based on Drupal 7 versions. The only one to work being to render the build array and the kill further PHP loading, however this doesn't feel right. In Drupal 7, I could set up a 'delivery callback' in the hook_menu() - but I can't seem to figure out how to replicate that behaviour now.

my_module.routing.yml:

my_module.user_timesheets:
  path: '/my_module/timesheets/{weekOf}/{uid}'
  defaults:
    _controller: '\Drupal\my_module\Controller\MyModuleAdminController::timesheets'
    _title: 'My Module Timesheets'
  requirements:
    _permission: 'admin'

my_module.module:

  $theme['timesheets'] = [
    'render element' => 'build',
    'template' => 'timesheets',
  ];

MyModuleAdminController.timesheets:

public function timesheets($weekOf, $uid = null) {
    $build['#theme'] = 'timesheets';

    ...code building values...

    $build['#staff'] = $staff;

    $build['#title'] = 'Timesheets - ' . $weekOf . ' to ' . $this->dateService->getWeekStartDate($weekOf);
    $build['#attached']['library'][] = 'my_module/timesheets';
    //print render($build);
    //die();
    return $build;
  }

my_module.libraries.yml:

timesheets:
  css:
    theme:
      lib/timesheets.css: {}

Edit:
   To over-ride something like page.html.twig in your module, you make a template called page--my_module--html.twig and then declare it in your modules my_module_theme() function.

/**
 * Implements hook_theme().
 */
function my_module_theme() {
  $theme['page__my_module__timesheets'] = [
    'template' => 'page--my_module--timesheets',
  ];

   return $theme;
}

The controller does not have to return a render array, it can also provide a symphony response, for example:

use Symfony\Component\HttpFoundation\Response;

$response = new Response();
$response->setContent('
Hello world
');
//$response->headers->set('Content-Type', 'text/xml');
return $response;

This will bypass the Drupal rendering and theming.

Edit:

You can use two approaches to replace your Drupal 7 code:

1) Override page.html.twig and html.html.twig, remove anything out of this templates and put only that in what you want.

2) Render the HTML like you are doing it now in Drupal 7 and use a Symfony response.

Rendering in Drupal 8:

use Symfony\Component\HttpFoundation\Response;

$output = \Drupal::service('renderer')->renderRoot($build);

$response = new Response();
$response->setContent($output);

return $response;


Does the Bootstrap 3 Theme for Drupal meet WCAG 2.0 and ATAG 2.0 standards? I'm currently creating a new website for work and I would like our drupal website to be accessible to users with disabilities, and I wanted to know if the Bootstrap 3 Theme meets web accessibility standards like the themes Zen and Adaptive.

I wanted to confirm that the Bootstrap 3 theme is accessible before moving forward with adding content.  I did not find any information on the Bootstrap 3 page on the drupal website specifying the accessibility aspect of the theme.

As you can see in this bugreport: https://github.com/twbs/bootstrap/pull/11757 Bootstrap aims to be WCAG compatible. But it does not claim it already is. Also, there are a lot of WCAG guidelines that are not theme-only. The very first one:

  Guideline 1.1 Provide text alternatives for any non-text content so that it can be changed into other forms people need, such as large print, braille, speech, symbols or simpler language.

Obviously, theme cannot force you to comply with it.

Audit

WCAG is now, effectively, a part of law in European Union. This means that no one will claim to be WCAG compliant lightly, and specialized law / audit companies charge big bucks to give you a "WCAG compatible" document with their signature on it. From my experience, we talk about 4, 5 digits sums, if you need it for government cooperation purposes (like, you want to sell website to a city). Possibly more. Open Source projects hardly have funding for that, that's why you "did not find any information on the Bootstrap 3 page", and you will not in predictable future.

Pay from your own pocket, or use at your own risk.


use Views module with organic group Using Views, I was able to apply CSS elements to content fields, but after applying Organic Group module and assigning each content to each group, I don't know how to take control of these content. The contents looks fine in the front page but inside the group's page it is a bit messy.

So is there's any way to fix that?

This module Code Per Node will make things alot easier for you.

Code per Node makes it possible to add custom CSS and Javascript per node, per content type, per block, and globally. The code is stored in the database, but served from the file system. It also supports syntax highlighting with CodeMirror.


Drupal 6 Ubercart - cancel/remove payment on order I have an older Drupal 6 site using Ubercart. We were recently doing some work to the payment gateways and upon the completion of the work we neglected to remove the test payment gateway and there were several orders that were submitted for which no actual payment was ever made.

My question is - is there a way to remove the erroneous payment and set the order back to non-paid? I know I can change the status, but I need to adjust off the amount that was actually paid in this scenario instead of the customer having to go through the whole purchase again. My thought is that they can just log back in and re-complete their order with the test gateway payment having been removed.

Rob, I'm afraid it may not be possible. In Ubercart, we handled shopping carts as pseudo order objects, tying cart items directly to a session. Once that cart has been checked out, as I recall, there's no way to run through checkout again with it. You may just need to contact the customers to resubmit the order or process their payment some other way (PayPal money request?).

Fwiw, this is why we made the decision in Commerce to manage all shopping carts as full order objects and use the order ID in the checkout URL. Much cleaner to support this type of behavior.


How to create add and edit pages for content types beside to Administration In my drupal installation (Drupal 7) I have various users.
What I want to do is, I want to enable somehow my users to be able to create content their own, without using the administration page.

Lets say, user clicks on a link to create an article or blog without going to administration page. The linked page contains a form for the article/blog and the user submits that form. So has been the content created.

What is the proper way to do it?
Self development of forms?
How is the URL then built?

I have found something like that
how-to-create-different-panels-for-add-and-edit-node
but here the module "Pages" is probably used.

It would surprise me that something like that does not exist.

If it's simply a matter of using the non-administration theme for node edit pages, there is a setting at admin/appearance, at the bottom of the page, for setting the administration theme. It also includes the following check box: "Use the administration theme when editing or creating content". Simply uncheck this to use your non-admin theme for node add/edit forms.


Removing required attribute on user entity fields not working I have added fields to user entity and make them required and show on registration page. So the user signing up have to fill all the fields. On the admin side these all fields are coming but i don't want to make them required when admin is creating any user. I thought it will be solved if i hook_form_alter  the user registration form and remove the #required attribute. I did this for admin and dpm($form). I set #required => 0 also unset #required but it keep on showing error of required field. I uncheck the required checkbox in field settings from admin panel and it does not show validation errors on both Admin and Frontend.

What i want is when admin create a user he just enter username and password and leave the rest of custom fields blank and it should register the user. But on the frontend users have to fill the whole form.

Below is the code:

    // If this is admin creating user
     foreach($form as $key => $value){
                if(strpos($key, 'field_') !== false){
                    $value['und']['#required'] = 0;
                    unset($value['und']['#required']); // This isn't working either
                }
            }
    // Endif

Updated Full Code:

/**
 * Implements hook_form_alter()
 */
function paypal_signup_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_register_form'){
      global $user;
      if(!in_array('administrator', array_values($user->roles))){
        //Submit handler for redirecting user to Paypal.
        $form['#submit'][] = '_paypal_signup_redirect_paypal';
    } else {
        // Remove validation when admin is creating user.
        foreach (element_children($form) as $key) {
            if (strpos($key, 'field_') !== FALSE) {
              $form[$key][LANGUAGE_NONE][0]['#required'] = FALSE;
              $form[$key][LANGUAGE_NONE]['#required'] = FALSE;
            }
         }
        dpm($form);
    }
  }
}

Drupal has element_children() to help you safely loop over render arrays. Looping over such arrays manually will inevitably causes problems. Your code should look more like this:

foreach (element_children($form) as $key) {
  if (strpos($key, 'field_') !== FALSE) {
    $form[$key][LANGUAGE_NONE]['#required'] = FALSE;
  }
}

Incidentally, your current code doesn't work because you're modifying a variable that has only ben declared within that function's private scope.


How do I view the string pulled from feeds image importer? I am importing images from a feed using xPath parser. I think that I have the correct attribute value, media:content@url, but I am getting a Unable to handle the provided embed string or URL. error. My first instinct is to check that I'm getting the proper string. How do I do this? Is there a way through devel to view the imported string? Devel?

The url string I want to pull is https://cdn2.orgsync.com/images/os-photos/s5o0zqk8o29mi46_710.jpg

I haven't solved my problem, but I found the hook needed to spit out the pre-parse data.

\**
* Importer testing.
*/
function wpi_events_feeds_after_parse(FeedsSource $source, FeedsParserResult $result) {
dpm($result);
}

This spits out the source strings, which is great, because it tells me my xpath selector is wrong.


Why does my node-type-specific hook not work I have implemented a hook_node_info() as follows:

function mymodule2_node_info(){
  return array(
    'mynode1' => array(
      'name' => 'MyNode1',
      'base' => 'mynode1',
      'description' => t('A Description of MyNode1'),
      'has_title' => TRUE,
      'title_label' => 'Title',
    ),
  );
}

I'd specified the 'base' property as 'mynode1', So I would expect that an implementation of mynode1_view() would work when this node is viewed.

function mynode1_view($node, $view_mode){

}

But I get the error messages instead:

Notice: Trying to get property of non-object in node_build_content() (line 1413 of
C:\wamp\vhosts\mydrupal72\modules\node\node.module).
EntityMalformedException: Missing bundle property on entity of type node. in
 entity_extract_ids() (line 7880 of C:\wamp\vhosts\mydrupal72\includes\common.inc).

Be sure to return $node at the end of your mynode1_view function. (This is different from most hooks, which generally modify the variable by reference).  You may have missed this. See this comment.


How to display cck node fields' values at the search result page? I need to display some specific cck fields such as Telephone Number, Address, etc. at the search result page.

As I see the search-result.tpl.php, there is no $node->... So how can I get the node fields into search result page?

In your theme, you can use template_preprocess_search_result()

function YOURTHEME_preprocess_search_result(&$variables) {
  if ($variables['type'] == 'node') {
    $node =& $variables['result']['node'];
    //Do something here
  }
}

Or, you can also implement hook_nodeapi() in a custom module for $op = 'search result'. The result of hook_nodeapi($node, 'search result') is available in $info_split in the search-result.tpl.php template.


How to make commands invoked by drush_invoke not to fail after adding extra option? I've added new option into drush command as suggested here:
function hook_drush_help_alter(&$command) {
  if ($command['command'] == 'features-revert-all') {
    $command['options']['cleanup'] = 'Remove non-existing components.';
  }
}

where features-revert-all is overridden by another created custom command as demonstrated here (so basically another custom-features-revert-all command is called).
However when my custom command invoking another commands via drush_invoke - they fail, because they cannot find that option. I really don't care about the option whether they can recognise it or not, but they shouldn't fail.
So basically when I run:
drush fra --cleanup --yes

I've these errors:

Unknown option: --cleanup.  See drush help features-cleanup-feature for available options. To suppress this error, add the option --strict=0.
Unknown option: --cleanup.  See drush help rules-revert-all for available options. To suppress this error, add the option --strict=0.

Here is how my function look (simplified for clarity):
function drush_FOO_custom_features_revert_all() {
  module_load_include('inc', 'features', 'features.export');
  $force = drush_get_option('force');
  $cleanup = drush_get_option('cleanup'); // At this point, the option is working.

  $features_to_revert = features_get_features(NULL, TRUE);
  if ($cleanup) {
    drush_invoke("features-cleanup-feature", $features_to_revert);
  }
  else {
    drush_invoke("features-revert", $features_to_revert);
  }
  drush_invoke('rules-revert-all');
}

So basically the option works fine within the main function, but sub-commands are complaining that this option that it's unknown to them.
Question is, what's the correct approach of fixing it (so they won't fail)?
Do I need to add option to every other command which uses drush_invoke into drush_help_alter? Maybe there is some way of passing original drush options along. Or maybe I am forced to use --strict=0? Or there is some better way of fixing this issue?

The preferred solution is to use drush_invoke_process() for subtasks. This will execute the command in its own process, completely isolate from the parent.

If you do need or wish to use drush_invoke() (doing so is a little faster, since you don't need to bootstrap again), then you should use drush_set_option('strict', 0); to disable options checking.


Differences between value and safe_value What are the differences between ['value'] and ['safe_value']?

It is a value, passed through the function _text_sanitize(). You can read more in the official docs.

If you are using 'safe_value', you may be also interested in this article: Rendering Drupal 7 fields (the right way).


How to override page title by content type I'm using the pagetitle core module to render a page title. However, for certain content types I want the page main title to be the content type label (e.g. "News") and not the node label (e.g. "Drupal 8 released!").

Is there a simple way to achieve it? My first guess was to use the template_preprocess_page_title but $variables has no context whatsoever about node, node type, etc...

As mentioned by Ivan Jaros You can use hook_preprocess_page_title.

You just have to load the node from the route first, to get some context.

function yourtheme_preprocess_page_title(&$variables) {

  // Load the node entity from current route
  if ($node = \Drupal::routeMatch()->getParameter('node')) {

    // Load the label of the bundle
    $bundle_label = \Drupal::entityTypeManager()
      ->getStorage('node_type')
      ->load($node->bundle())
      ->label();

    // Set the page title
    $variables['title'] = $bundle_label;
  }
}

If you just want to use this with certain content types, you can use $node->bundle() to get the machine-readable name and check against it.


Update multisite modules and core in one click I have a Drupal multisite install with 7 different sites, all sharing the same modules, themes and users but everything else is unique to the individual site.  At the moment, I only have to upload one version of Drupal core or any contributed modules when I want to update them but I have to run update.php on each website separately.  Is there an easy, quick way of making all of these updates run simultaneously?

I think the simple answer is no. And generally you would want it to be so.

Running update.php can cause sites to fail, so you should back up each sites database run update.php and then check it works. Each of your sites will work slightly differently, depending on the combination of modules. So a broken update hook, or a conflict would be something that you would want to check carefully for.

Having said all of that there are tools such as aegir which may make this possible to do safely.


Get all nodes of a specific content type and print the data of each node inside page.html.twig I have a content type (Flower) with two fields: Name and Color.

In my-theme/templates/page.html.twig, I want to print the name and the color of each flower.

    {% for flower in flowers %}

{{ [Flower Name Here] }}

{{ [Flower Color Here] }}

    {% endfor %}

How can I get all nodes of a given content type and print the values of each node inside page.html.twig?

Putting this in page.html.twig is a bad idea. Since this template will be used for every page rendered from Drupal using that theme.

Instead you should simply create a View. Views can be used to query a certain content type and to list nodes in a certain view mode or just certain fields of these nodes (the title and a color field for example). Then configure your view to provide a block and place that block in the region you wanna have the Flowers printed.

Views and block will take care of the caching. And you can use the block's visibility settings to have it displayed only on paths or nodes where you really need it.

If you still insist on coding this in a template (not recommended, too performance-heavy, too much logic in templates) you first have to pass all Flower nodes to the template.

/**
 * Implements template_preprocess_page().
 */
function MYTHEME_preprocess_page(&$variables) {

  $query = \Drupal::entityTypeManager()->getStorage('node')->getQuery();

  // Get all Flower node IDs.
  $nids = $query->condition('type', 'flower')->execute();

  // Load all Flower nodes.
  $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);

  // Pass them to page.html.twig.
  $variables['flowers'] = $nodes;
}

Then in your page.html.twig:

{% for flower in flowers %}
  {{ flower.title.value }}
  {{ flower.field_color.value }}
{% endfor %}


What is a front page in drupal ($is_front)? Nice to know for drupal beginners:

What is a front page in drupal and particularly in which case is $is_front true ?

$is_front is set on any template from _template_preprocess_default_variables() (itself called from template_preprocess()). It uses the result of the drupal_is_front_page() function.

drupal_is_front_page() will returns TRUE, if the path of the current page matches the site_frontpage configuration variable. This variables can be set from the "Site Information" configuration page.

Usually there is only a single front page on a Drupal site. If you use the Variable translation module (part of the Internationalization project), then you could translate the site_frontpage configuration variable and have a different front page for each enabled language.

It may also be possible to have other module alter the value of the variables on each request to have multiple front pages. Additional module may also alter the value of $is_front in all or only a few specific templates. However, I cannot think of any useful use case for this, except torturing the template developer with inconsistency.


No navigation links on 404 pages When I visit a page that does not exist, I expect to still see the primary and secondary links as on any other page, but what I get is no navigation links in the 404 page. See also No navigation links on 404 pages.

I have found a solution, but I am happy if something else can fix this (possibly without using extra modules).

You can do it by defining a page in a custom module.

Create a page for the category "Page not found" using hook_menu().

function MODULE_menu() {
  $items['page-not-found'] = array(
    'title' => '',
    'page callback' => 'MODULE_page_not_found',
    'access callback' => TRUE,
  );
  return $items;
}

function MODULE_page_not_found() {
  drupal_set_title('Page not found');
  $cust_err = "";
  $cust_err = $cust_err . "The requested page " . current_path() . " could not be found";
  return $cust_err;
}

The page callback uses current_path() to return the path of the page causing the 404 error.

Go to Admin > Config > System > Site-information, and enter page-not-found (same name as defined in hook_menu) under Default 404 (not found) page.

Now the error page appears like in the following screenshot.

It is clear that it contains all the navigation links, and also the page URL producing the error (very similar to the original page not found). And the module mentioned in the answer above by @Nikhil will output "The requested page could not be found." but does not contain the URL of the page causing the error.


Page title and body field of specific page I have a page--front.html.twig file. I can't figure out how to show a specific node title and body summary on the frontpage with only using twig. I know I can create a view of something like that and show it with: {{ drupal_view('viewmachinename', 'blockname') }}, but in my opinion it's a little bit overkill for just showing the title and body of specific node.
Normally I show the current node title and body summary with {{ node.label }} and {{node.body.summary}}, but I don't know how to show the page title and body summary with an other nid.
I try to show the page title and body summary with nid 2 on the frontpage.

If you must do this in twig only, you can use the drupal_field() function provided by the Twig Tweak module.
For example, to print the title of node 2:
{{ drupal_field('title', 'node', 2) }}

Or to print the body field for node 2 using the field's configuration from the teaser view mode:
{{ drupal_field('body', 'node', 2, 'teaser') }}

Or to print an image field with custom formatter settings:
{{ drupal_field('field_image', 'node', 2, {type: 'image_url', settings: {image_style: 'large'}}) }}

I'd probably aim to create a custom view mode here and then print the whole view mode as one chunk with the drupal_entity() function. For example:
{{ drupal_entity('node', 2, 'my_custom_view_mode') }}


Entity reference field to show translation of nodes I have a content type "Genetic Test" which has an entity reference field (select list) where I can select nodes of the content type "Material".
The Material nodes all have English set as their source language, but they are also translated in Dutch and French (entity translation).

The problem I'm having is, when I edit a node of the type "Genetic Test" with the interface language set to English, the select list shows the Material nodes, but when I change the interface language to Dutch or French the list is empty.

So my question is, how do I get the select list to show the Dutch or French node titles of the content type Material when I'm editing the Genetic Test node in said languages?

I hope I made myself clear a bit, English isn't my first language.

Thank you in advance for any help.

BTW: I'm working in Drupal 7.

I am not sure if you have already taken care of this but I think you would need to add title module as well since the title is not an entity by default and wont work with the entity translation module.

Another thing would to keep the language as neutral rather than keeping it English. Internally drupal would fetch the nodes with the lan


How to get project's data from packages.drupal.org Drupal projects can be searched similarly as Packagist:

https://packages.drupal.org/8/search.json?s=projectname
https://packagist.org/search.json?q=projectname

From Packagist can be also extrated the project's data (e.g. versions):

https://packagist.org/packages/symfony/symfony.json

Is it possible to get project's data also from the Drupal repository?

More info:

Using packages.drupal.org
Packagist API Documentation

Yes, the Composer documentation on repositories describes this mechanism, specifically, the provider-includes and providers-url properties.

These properties describe the package indexes & the URL pattern used for look up, for example:

https://packages.drupal.org/8/packages.json (root index)
https://packages.drupal.org/8/drupal/provider-2018-2%24082d3c8e1745428fcd819891137e88683576066b00ed52bd80811943e98e8d08.json (first index)
https://packages.drupal.org/8/drupal/commerce%24f8b852956418601bb4d985203d4138a18e2bfc0ae1b67b249a667228190fd26f.json (a specific package with all its releases)


Field collection table print row number I'd like to print a row number at the start of each table row in a field collection table.

Is this possible? Could you please explain?

thx in advance

The field table collection module is kind enough to provide a specific theme function for tables that it outputs.

As such, you can implement a preprocess hook for the theme_table__field_collection_table() function and add your row numbers in there:

function MYMODULE_preprocess_table__field_collection_table(&$vars) {
  // Add a new (blank) header
  array_unshift($vars['header'], '&nbsp;');

  // Add an incremental count to each row
  $count = 1;
  foreach ($vars['rows'] as $key => &$row) {
    array_unshift($row['data'], $count++);
  }
}


Displaying article image on full display conditionally I would like to enable/disable visibility of article image on full display for some articles while keeping article image always visible on teaser display. Is there a way to achieve that apart from dealing with views?

Thanks.

You have to use Field formatter conditions module to achieve this goal.

First thing attach a field on desired content type with boolean value and then use this field value as a condition in field formatter settings to display other fields as you want.

For more information go through the module documentation.


How to update taxonomy field in a node? node_load($nid);
$node->mytaxonomyfield['und'][0]['tid']=$data;
node_save($nid)

my corresponding terms : online,offline,pre-online  and the corresponding tid : 1,2,3

my question : what the program will be that changing the field data by words instead of tid

You can't (at least not directly). Don't forget that multiple taxonomy terms may have the same name so they need to be identified by their tid or you'd get clashes.

You have a couple of options to load a taxonomy term by name, but for each you'll need to know the vid of the term's vocabulary.

The first option is to use the deprecated $conditions parameter of the taxonomy_term_load_multiple() function:

$terms = taxonomy_term_load_multiple(array(), array('name' => 'online', 'vid' => $vid));
$first_term = array_shift($terms);
$tid = $first_term->tid;

As you can see it's limited to loading just one term at a time.

The second (much better) way is to use an EntityFieldQuery:

$terms = array(
  'online',
  'offline',
  'pre-online'
);

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'taxonomy_term')
  ->propertyCondition('vid', $vid)
  ->propertyCondition('name', $terms, 'IN');

$results = $query->execute();

if (isset($results['taxonomy_term'])) {
  // Get an array of tids
  $tids = array_keys($results['taxonomy_term']);
}

That way you can load multiple terms in one go, and take advantage of non-SQL field storage solutions if you need to.

If you're worried about speed you could also go directly into the taxonomy_term table to get this data; but I don't advise doing this unless you really know what you're doing.


NID in new created node title I don't like second node_save. But I need nid for title.

$node = new stdClass();
$node->type = 'bill';
node_object_prepare($node);
$node->uid = $user->uid;
$node->field_body['und'][0]['value'] = $bodytxt;
$node = node_submit($node);
node_save($node);

$node->title = 'Bill # '.$node->nid;
node_save($node);

Is there more elegant way?

Is there more elegant way?

Not really - the NID doesn't exist until the node has been saved the first time, so there is no way around this if you want to save the node title.

However, you could just add the NID to the title when the node is loaded:

function hook_node_load(&$nodes, $types)
{
  foreach($nodes as $node)
  {
    if($node->type == 'my_type')
    {
      $nodes[$node->nid]->title = '#Bill ' . $node->nid;
    }
  }
}


Why Cant add a class to an element by jquery In the page.tpl.php I have some elements like

I have linked js file to the page and it is correctly works since all functions operate based on click attributes. but I would like to mudify some elements in page.tpl.php page. for example in my JS file I have a code like this:

$(".play").attr("id", "myID");

I could not make it working. basically it does not add myID to .play.

Any idea?

Going on little information provided its probably because you cannot access jQuery with the $ by default in drupal.  This is to prevent other library conflicts (see jQuery.noConflict())  If this is the case you will probably be getting an undefined function error in your console.  To fix this you can either use jQuery or wrap it in a function like this:

(function($){
  $(".play").attr("id", "myID");
})(jQuery);

or can do this:

jQuery(".play").attr("id", "myID");

By default the version of jQuery that is used on drupal is 1.5.  You may consider using jQuery Update module for a newer version.

"Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $. If you need to use another JavaScript library alongside jQuery, return control of $ back to the other library with a call to $.noConflict(). Old references of $ are saved during jQuery initialization; noConflict() simply restores them."


Pass argument when overriding controller in RouteSubscriber I am having the issue of overriding the default taxonomy controller /taxonomy/term/{tid}.

I have created my own controller which takes {tid} as a parameter and I want to use it instead, so I overrode the default taxonomy controller in the RouteSubscriber like this:

    <?php

namespace Drupal\my_module\EventSubscriber;

use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\Core\Routing\RoutingEvents;
use Symfony\Component\Routing\RouteCollection;

class RouteSubscriber extends RouteSubscriberBase {

  protected function alterRoutes(RouteCollection $collection) {
    foreach ($collection->all() as $route) {
      if ($route = $collection->get('entity.taxonomy_term.canonical')) {
        $route->setDefault('_controller', '\Drupal\my_module\Controller\PagerController::handleDefaultPage');
      }
    }
  }

  public static function getSubscribedEvents() {
    $events = parent::getSubscribedEvents();
    $events[RoutingEvents::ALTER] = array('onAlterRoutes', -250);
    return $events;
  }

}

My sample page controller is this:

<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class PagerController.
 */
class PagerController extends ControllerBase {

  /**
   * Handlepage.
   *
   * @return string
   *   Return Hello string.
   */
  public function handleDefaultPage($tid) {
    return [
      '#type' => 'markup',
      '#markup' => 'term: ' . $tid,
    ];
  }
}

And its routing is this:

my_module.pager_controller_handleDefaultPage:
  path: '/taxonomy/term/{tid}'
  defaults:
    _controller: '\Drupal\my_module\Controller\PagerController::handleDefaultPage'
    _title: 'Taxonomy Pager'
  requirements:
    _permission: 'access content'
    _entity_access: 'taxonomy_term.view'
    taxonomy_term: \d+

But then, when I open the taxonomy page, I get this error which means, that I need to pass the $tid param somehow.

RuntimeException: Controller "Drupal\my_module\Controller\PagerController::handleDefaultPage()" requires that you provide a value for the "$tid" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one. in Symfony\Component\HttpKernel\Controller\ArgumentResolver->getArguments() (line 78 of /var/www/html/vendor/symfony/http-kernel/Controller/ArgumentResolver.php).

How to resolve it?

Actually, I have found an error in my code.
Everything works normally, when the param name and type are set properly.
So the final code should be:

My sample page controller is this:

<?php

namespace Drupal\my_module\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\taxonomy\TermInterface;

/**
 * Class PagerController.
 */
class PagerController extends ControllerBase {

  /**
   * Handlepage.
   *
   * @return string
   *   Return Hello string.
   */
  public function handleDefaultPage(TermInterface $taxonomy_term) {
    return [
      '#type' => 'markup',
      '#markup' => 'term: ' . $taxonomy_term->getName(),
    ];
  }
}

And its routing is this:

my_module.pager_controller_handleDefaultPage:
  path: '/taxonomy/term/{taxonomy_term}'
  defaults:
    _controller: '\Drupal\my_module\Controller\PagerController::handleDefaultPage'
    _title: 'Taxonomy Pager'
  requirements:
    _permission: 'access content'
    _entity_access: 'taxonomy_term.view'
    taxonomy_term: \d+


Is There a way to search non drupal solr index? I have a huge solr index. I'd like to build my UI within a Drupal site. I tested the apachesolr module but it only focuses on a Drupal node. Does anyone have a similar project?

The Sarnia module is the only solution I'm aware of. It leverages the Search API, but unlike the other SOLR modules, it is designed to expose the content of any index rather than index Drupal content. It also has some pretty decent documentation, here.

However, I'm having trouble getting it to actually work properly. Latest dev version is not working for me, at least at the moment.

[UPDATED] Most of my troubles arose because my SOLR index does not use the standard handler names, and so some manual configuration was required (hacking service.inc). Once done, it certainly works, although it does not cope with grouping/collapsing results, and I'm not sure how to expose facets.


Comment migration working? (D5 --> D7) View displaying comments not I thought I had this piece of the migration sorted, but I'm not sure what's off. As far as I know these are the places comment info is stored:

comment
field_data_comment_body
field_revision_comment_body
node_comment_statistics

I'm using a stored procedure to migrate the comments from the D5 db to the first three tables in the above list, the data appears to match what's generated by the native comment submission. After the stored procedure I run devel_rebuild_node_comment_statistics();

The results in the node_comment_statistics table look promising but some comments (rather their record in this table) are missing, or (after typing this all out) I'm realizing that this table probably doesn't store a record for every comment, just the last comment for that node (and comment count, etc).

Regardless, some comments won't display, even though their db records appear the same as neighboring comments that do display. I suspect this has to do with a subtle change in how the comment hierarchy is stored?

Also, (could be coincidence), one of the MIA comments did not have a record in the node_comment_statistics table, but this may be normal/works as designed.

The SQL statement within devel_rebuild_node_comment_statistics(); MIGHT be part of my issue (not blaming the function because it may not have been designed for how i'm using it) here is the function's SQL:

  SELECT c.nid, c.cid, c.created, c.name, c.uid, c2.comment_count FROM {comment} c
  JOIN (SELECT c.nid, MAX(c.created) AS created, COUNT(*) AS comment_count FROM {comment} c WHERE STATUS = 1 GROUP BY c.nid)
  AS c2 ON c.nid = c2.nid AND c.created = c2.created

Let me know if you need more info, or have an approach suggestion. Thanks!

UPDATE: So on a clean D7 install w/ devel generate, i'm seeing that a record is created not for every comment, but for every node in node_comment_statistics. The zero comment records are probably not related to my issue. Comparing the results of devel_rebuild_node_comment_statistics(); to native comment storage, everything seems fine w/ the function, so something is wonky in my comment migration.

Things I learned today, yes it took me all day, and I learned a lot. Like to test your assumptions. Test them early and verify the problem you're trying to solve in fact is in the place you are looking.

My debacle outlined above was completely separate from all the comment tables. The maddening part, was I narrowed it down to the comment bodies not appearing (or so I thought) because I was using a view to display the author's name, followed by the comment. Where this view pulled the author name from was the comment table, where the author's name wasn't was in the users table, I hadn't run the user migration in a couple weeks & enough users had joined & commented that, well, you get the picture.

Also contributing to the madness was the lack of information in the error messages, I kept getting malformed entity exceptions, which is probably because I was using views to display the comments.

Something else I noticed, that a comment's initial changed time is a few seconds before it's created time, not sure that's a bug, but definitely a quirk.