Translation of select field allowed values I have a field that has just one option to choose. It's:

Online|This product will be delivered online

I'm struggeling to make it translatable, but with no luck. I've checked everywhere and I stucked. So, in database there is core locales_source table that holds english phrases. There is a source and context of this phrase:

lid: 39
location: field:field_product_delivery:#allowed_values:Online
textgroup: field
source: This product will be delivered online
context: field_product_delivery:#allowed_values:Online
version: 1

There is also locales_target table that contains translations and there is:

lid: 39
translation: Este producto se ofrece online
language: es
plid: 0
plural: 0
i18n_status: 1

Still, the value is displayed in English on Spanish node view page.
How to force it to use correct translation, not the english phrase. By the way, my default language set in Drupal is Spanish.

Make sure you enabled the Field Translation module, a submodule (i18n_field) of the i18n module. Some more details about it (from the Community documentation):

  ... allows for translation of text associated with a field's settings including the label, help text, default value, and list options. Translation of these field settings can be added through the 'Translate interface' pages (Administration > Configuration > Regional and language > Translate interface).

Especially the "list options" mentioned above seem to be what you're looking for.


How to display entity properties using hook_entity_view_alter? Help with syntax I'm creating an entity in code using the eck. I've added both properties and fields to my custom entity. That is working great, except I can't figure out how to display certain entity properties when hook_entity_view is being called?

I have this in a custom module -

function mycustommodule_entity_view_alter($build, $type){
  if ($type == 'mycustomentity'){

  }

}

It's suppose to take a render array, but there is no $entity->content and I've tried various things to add a very simple render array #markup => 'somemarketup'; to $build, but I have not been successfully. Given that my property is named something like 'myproperty' and is just a text property (from eck) can someone help me with the syntax for adding it to the entity display using hook_entity_view_alter?

Accessing the entity

hook_entity_view_alter does not have an $entity parameter. This is a problem that has been addressed in Drupal 8 (see https://drupal.org/node/1618140).

In the mean time you can't be certain that the entity is available, because it depends on the function that invokes hook_entity_view_alter in the first place. Anyone can invoke hook_entity_view_alter, any may (or may not) provide you with the entity in the build array.

The EntityApiController from the entity module (which is not core, but is a requirement for eck) adds a '#entity' field to the build array which contains the entity. My feeling is that it should be safe in most cases to rely on this, but you can't be 100% sure that it will be there.

Here is an example, assuming a required field 'field_mycustomfield' which has a 'value' property (eg. simple text field):

function mycustommodule_entity_view_alter(&$build, $type){
  if ($type == 'mycustomentity' && isset($build['#entity'])){
    $value = field_get_items($type, $entity, 'field_mycustomfield');
    $build[] = array(
      '#type' => 'markup',
      '#markup' => "My custom value: " . check_plain($value[0]['value']
    );
  }
}

Adding values to the build array

You have a small mistake in your code: to be able to modify the $build parameter, you must take that parameter by reference (as showed on the documentation for hook_entity_view_alter). Look at my example above and notice the & before $build.


Change the URL of a node based on parent path So let's say I have a basic page node.

I want to have this as an entity reference inside another content type - let's say an event content type.

So let's say that the event content has a url like baseurl.com/eventblahblahblah

When a user clicks over to the basic page that is the reference on node eventblahblahblah, I want them to go to baseurl.com/eventblahblahblah/basicpagenodehere - this needs to be the URL in the browser.

In addition, basicpagenodehere can be in multiple references - so if basicpagenodehere is also referenced by event2blah, then I want it to also be located at the url baseurl.com/event2blah/basicpagenodehere

I'm looking at possibly doing this with alterRoute -

class RouteSubscriber extends RouteSubscriberBase {
  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {
  }
}

But I'm not sure if this is the correct place to do it.

This link suggests maybe PathProcessor, but I don't think that would change the actual URL on the node at the end of processing:

How to alter and rewritte current path programmatically in Drupal 8?

So how do I set a dynamic URL based on referring node?

The routing system is probably not the right place for this, you would need to rebuild the routing table whenever the content is changed, which is very slow.

PathProcessor is the right tool. By the way, path aliases are also implemented in a PathProcessor, the aliases are coming from a lookup table. You can change the path in and outbound dynamically or with your own lookup table if you need it for performance reasons.

Better for SEO would be a redirect to avoid duplicate content, but this changes the url in the browser, what you don't want.

Example for the symmetrical inbound/outbound (asked in the comments):

  public function processInbound($path, Request $request) {
    if (strpos($path, '/foo/') === 0) {
      $path = preg_replace('#^/foo#', '', $path);
    }
    return $path;
  }

  public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    $path = '/foo' . $path;
    return $path;
  }

This will add /foo to all paths.

One way to approach this could be, you get the child node node/x in the outbound processor as input, the parent node id from the current route. Then you get the title from each of both nodes and put the path together.

For inbound I suggest a third fix path parameter, so that you can identify this kind of path right away and scrap all but the title from the child node, query the node id and you are back where you started at /node/x.


What would be the best way of creating a drop down menu - selected go to page I would like to create a drop down menu that does two things and I am still new to Drupal and i am trying to figure it out. The two functions are:

automatically grabs the title of the pages i am trying to list.
When an item is selected it will navigate to the corresponding page.

I feel like this has to be doable, but i am just not sure how i would go about it. Would anyone have any ideas on how i would go about doing something like this? any help would be much appreciated! Thanks!

You can create a View (with the Views module) with the Format "Jump Menu"

In the fields include the title, and link it to its node in the field settings.

If that does not serve your purpose, there are several Jump Menu contributed modules http://drupalmodules.com/search/node/jump+menu


How to have OutboundPathProcessorInterface change the URL of the loading page I have a page my/topics.  The page presents content based on the user's selection from another page. Having made the selection, it and other information is passed to the page via a query string:

mydomain.com/my/topics/?choice=topic1...

I have no control over the creation of the incoming path. For the processing of the path and for SEO I need the path to instead be:

mydomain.com/my/topics/topic1

In both cases the target is my/topics, but the processing I need from that point depends on being able to access the additional information as part of the URL instead of as a query string.

The available topics are a large non-static list. It might be possible to do some regex magic in .htaccess to handle it as a redirect, but I'd rather handle it within Drupal, if possible.

To that end I've used OutboundPathProcessorInterface. The class is listed, below. The problem I am having is that the path is not changed in the browser address bar. If I put my/topics in a menu link on the page, or a link in the body text, it does become my/topics/topic1 in each of the links, and in the address bar on a subsequent click, but not in the address bar of the page that is rendered as part of the altering of the path... it appears as my/topics.

I have commented out the 'if' statement that limits the change to just that path, and the result is the same on admin/structure, for example. The browser shows admin/structure, but the link to it in the admin menu when hovered over shows admin/structure/topic1.

You'll note that I have the priority of the module being -32766 (I've also tried just -1). No difference.

url_remap.services.yml

services:
  url_remap.path_processor:
    class: Drupal\url_remap\UrlRemapOutboundPathProcessor
    tags:
      - { name: path_processor_outbound, priority: -32766 }

UrlRemapOutboundPathProcessor.php

namespace Drupal\url_remap;

use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Symfony\Component\HttpFoundation\Request;

class UrlRemapOutboundPathProcessor implements OutboundPathProcessorInterface {
  function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    $append = '';
    if ($path == "/my/topics") {
      if (sizeof($options['query']) > 0) {
        if (array_key_exists('choice', $options['query'])) {
          $append = substr($path, strlen($path) - 1, 1) != '/' ? '/' . $options['query']['choice'] : $options['query']['choice'];
        }
      }
    }
    return $path . $append;
  }
}

You need three components for this task:

Your outbound path processor UrlRemapOutboundPathProcessor::processOutbound is the first step to get this started.

Second add an inbound path processor UrlRemapOutboundPathProcessor::processInbound to the class similar to Drupal\system\PathProcessor\PathProcessorFiles\processInbound:

  public function processInbound($path, Request $request) {
    if (strpos($path, '/system/files/') === 0 && !$request->query->has('file')) {
      $file_path = preg_replace('|^\/system\/files\/|', '', $path);
      $request->query->set('file', $file_path);
      return '/system/files';
    }
    return $path;

Your path processor won't change the URL in the browser, this is by the way the same with other path processors, for example you can access nodes still by their internal paths (/node/[id]) after you've entered an alias.

So third you need a request event subscriber which redirects the unwanted internal URLs.

An example would be how Redirect does this in RouteNormalizerRequestSubscriber::onKernelRequestRedirect:

 /**
   * Performs a redirect if the URL changes in routing.
   *
   * The redirect happens if a URL constructed from the current route is
   * different from the requested one. Examples:
   * - Language negotiation system detected a language to use, and that language
   *   has a path prefix: perform a redirect to the language prefixed URL.
   * - A route that's set as the front page is requested: redirect to the front
   *   page.
   * - Requested path has an alias: redirect to alias.
   *
   * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
   *   The Event to process.
   */
  public function onKernelRequestRedirect(GetResponseEvent $event) {

http://cgit.drupalcode.org/redirect/tree/src/EventSubscriber/RouteNormalizerRequestSubscriber.php

Probably this global redirect catches the internal paths from step one/two as well. If you don't want to redirect all URLs globally or find issues with the alpha version of this module, you can use this event subscriber as example to write  custom code to target only the specific URLs.


How to get the file ID using managed_file on custom form? In Drupal 8, I have a custom form that I built using the Form API in a custom module. I am trying to upload a file using managed_file field. For some reason I can't get it to give me the file ID no matter what code I try. The file does indeed get uploaded and saved, but only as a temporary file.

Please see below for the code I am using. The value of the form field is always NULL.

buildForm:

public function buildForm(array $form, FormStateInterface $form_state, $event = NULL) {
  $validators = array(
    'file_validate_extensions' => array('jpg jpeg png gif'),
  );
  $form['event_image'] = array(
    '#type' => 'managed_file',
    '#name' => 'event_image',
    '#title' => t('Event Image'),
    '#upload_validators' => $validators,
    '#upload_location' => 'public://event-images/',
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Save'),
  );

  return $form;
}

submitForm:

public function submitForm(array &$form, FormStateInterface $form_state) {
  $event_image = $form_state->getValue('event_image');
  if ($event_image) {
    $file = File::load(reset($event_image));
    $file->setPermanent();
    drupal_set_message('Filename: ' . $file->getFilename());
  }
  ksm($event_image); // Returns empty array??
}

I think you need to save the file :
public function submitForm(array &$form, FormStateInterface $form_state) {
  $event_image = $form_state->getValue('event_image');
  if ($event_image) {
    $file = File::load(reset($event_image));
    $file->setPermanent();
    $file->save();
    drupal_set_message('Filename: ' . $file->getFilename());
  }
}


ng angular typeahead drupal Has anyone got the angularjs bootstrap-ui "typeahead" widget to play nice with drupal autocomplete?

seems like a match made in heaven

I will try this in the next week or so - but just checking if anyone has a working example before I set out on the journey.

OK. Its not hard.

To achieve the same thing in angular (being served by drupal), have to:

get angular and bootstrap ui working.
create the  element in my view
add a function to the controller $scope to access $http ($http needs to be injected as a dependancy into the controller).

In my FAPI form I had a autocomplete_path defined:

 '#autocomplete_path' => 'agc/ac/contact/_',

So to access the same call back, in my Angular template:

Model: {{result | json}}

  <input type="text" ng-model="result"
   typeahead="suggestion for suggestion in cities($viewValue)">

The controller:

angular.module('contactFindControllers', []).controller('contactFindCtrl',
  ['$scope', '$http', function($scope, $http) {
    $scope.cities = function(cityName) {
    var path = '/agc/ac/contact/_/' + cityName;
    return $http.get(path)
    .then(function(response){
      // see note below regarding "_.values()"
      return _.values(response.data);
        });
  };

}]);

FYI: I used this as a starting point.

Note: my callback returns a JSON object (because I have non-numeric keys) not the array I needed, so I need to extract the values with _.values().
You many not need to use _.values at all (or if facing the same issue just
grab the values from the object or modify your call back to
return a json array)


Number of contents created by a user in a organic group I am using organic groups. I have an organic group called A and its group content B.
Users have subscribed to group A and created  content for content type B.

Now, I created a view of users.
There are three columns.
One for the usernames.Second one for the uid. And in the third one I want to show the number of nodes of type B created by a user.
There is a contextual filter for organic group A.

I am unable to craete the view. Please help.

If you are happy to use the rules module or the user points module, this is relatively simple. I don't think it's possible using only views.

I would add an integer field to User and have a rule

Event: After Saving New Content
Condition: Entity is of type > Content Type B
Action: Calculate a value > Input 1 = site:current user:field / Operator + / Input 2 = 1

Then display that field in your view.

User points is another option but is unnecessary if you already use rules.


management menu invisible for the second administrator I am using Drupal 7.26, and I need a second administrator user. I created a user who can see the authenticated user's menu, but not the management menu which I (as user #1) can see.

How can I fix this? I want the user I created with administrator role to have access to everything from the management menu.

The page under admin require the access administration pages permission, or the administer themes one. (See system_menu(), the 'access arguments' lines.)

  $items['admin'] = array(
    'title' => 'Administration',
    'access arguments' => array('access administration pages'),
    'page callback' => 'system_admin_menu_block_page',
    'weight' => 9,
    'menu_name' => 'management',
    'file' => 'system.admin.inc',
  );
  $items['admin/compact'] = array(
    'title' => 'Compact mode',
    'page callback' => 'system_admin_compact_page',
    'access arguments' => array('access administration pages'),
    'type' => MENU_CALLBACK,
    'file' => 'system.admin.inc',
  );
  $items['admin/tasks'] = array(
    'title' => 'Tasks',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -20,
  );
  $items['admin/index'] = array(
    'title' => 'Index',
    'page callback' => 'system_admin_index',
    'access arguments' => array('access administration pages'),
    'type' => MENU_LOCAL_TASK,
    'weight' => -18,
    'file' => 'system.admin.inc',
  );

  // Menu items that are basically just menu blocks.
  $items['admin/structure'] = array(
    'title' => 'Structure',
    'description' => 'Administer blocks, content types, menus, etc.',
    'position' => 'right',
    'weight' => -8,
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('access administration pages'),
    'file' => 'system.admin.inc',
  );
  // Appearance.
  $items['admin/appearance'] = array(
    'title' => 'Appearance',
    'description' => 'Select and configure your themes.',
    'page callback' => 'system_themes_page',
    'access arguments' => array('administer themes'),
    'position' => 'left',
    'weight' => -6,
    'file' => 'system.admin.inc',
  );

The user you create must have a role with the right permission. Go to admin/people/permissions and assign to the role of that use the necessary permissions, listed under System.

Keep in mind that the user #1 has every permission, independently from the roles it has. If you are wondering why there is a difference between the user you created and the user you normally use, even if they have the same role, that is the reason. Drupal check the currently logged-in user is the user #1, as visible in the code for user_access().

  // User #1 has all privileges:
  if ($account->uid == 1) {
    return TRUE;
  }

User #1 could not have any extra role, and simply be an authenticated user, and still it would have all the permissions, contrary to the normal authenticated users, who have just the permissions you assign to the authenticated user role.


Webform results don't download We've been using our Drupal webforms for years. Suddenly today, if an authorized user or the admin tries to download the results, the resulting file is 0bytes. The data is definitely there. I am unsure how to even troubleshoot this problem.

The really odd thing is that my dev site is a near identical copy of the live site and it works on the dev site (but the results are outdated). Whatever changed on the live site would have been in the last couple weeks and I can't think of what may have caused it that I wouldn't have implemented on the dev site first.

Drupal 7.50 Commons, webform 7.x-1.0. Let me know what other information would be helpful to provide, thanks!

Things I've Tried, to no avail:

downloaded the results into different formats
downloaded results as regular staff and admin user
downloaded only final and non-draft results

I checked the permissions of the temporary files for our theme and sure enough, they were wrong. I am not sure what caused them to change, but they were set to root, whereas the dev site was set for www-data for both user and group. On our Debian server, Drupal uses the temporary files located at /tmp/example_theme.

To fix:

sudo chown -R www-data /var/example_theme

sudo chgrp -R www-data /var/example_theme

That fixed this and many other problems we were having today.


Sharing article to facebook adds reserved html characters in heading (&amp #039) I have a drupal 7 site, and after sharing posts to facebook, I saw strange behaviour. When I use quotes in heading, after sharing the article i see '"e; and #039, what causes this and how can I avoid it? I use addtoany drupal7 module.

Those are the encoded values of the characters. Before you share it to the facebook, check any hook if module is providing to decode it and then share it.

You'll have to use htmlspecialchars_decode($str); to do that.


Use Views field output as a class? Tokens? I have a field in my view which displays the taxonomy vocabulary that each result/node is linked to. However, I need a way to get that taxonomy vocabulary result and use it as a class for the view row - not just the field.

Has anyone had any success with something like this before? Options I can think of might be Tokens, direct template theming, or Display Suite, but I don't know how I would go about fetching that vocabulary field output and using it as the row's class.

Any help would be received gratefully :)

If you're looking to use it as a class for the whole row rather than just for the field, use a views template.

The Advanced -> OTHER -> Theme: Information section of your view usually has good ideas on what to call files but it doesn't seem to include anything for the row.

If you're using row style: fields... try making a template file called views-view-fields--myviewname.tpl.php.

To dig into the variables available to that template file, the first thing you want to do is install the Devel module, turn it on, and put this in the template:

dpm($content);

or maybe

dpm($output);

dpm() prints the named variable on the screen when the file is run.


Insert (Google ad) token in a template I want to insert a token from the Google Ad Manager module in a view.

But how do you insert a token like the ad_slot token in this module in a views template?

The Google Ad Manager module uses a filter for the tokens, not the Token module. You could call its internal function $content=_google_admanager_substitute_tags($text); to do the substitution for you, where you replace $text with [google_ad:ad_slot] but I am not sure if it will know enough to put all the google js in your page. Try it out, I guess.

Otherwise, you can do something like $content=theme('google_admanager_block', $gid, $google_ad); where $gid=variable_get('google_admanager_account',''); and $google_ad is your ad slot. That I've done all over the place myself with reasonable success.


how to populate select list using hook_form_alter()? I wanted to add values to a select list dynamically. Another module generates an array from a web service and I want to use those values to populate a select list in a form using hook_form_alter.

I tried directly adding the options in #options of the field using the following code

<?php $form['field_mage_category']['und']['#options']=$arr; ?>

The above code adds the options to the select list and returns a value according to the options selected but when the form is loaded again for editing. The option is set to default value and other issue is that when a single option is deleted. The respective value is not getting deleted from the field_data table.

I tried using #after-build property to populate the select list.below code is the call to _add_category_select_list function

      <?php function main_menu_form_alter(&$form, &$form_state, $form_id){
       if($form_id=='main_menu_node_form'){
           form['field_mage_category']['#after_build'] = array('_add_category_select_list');
          } ?>

and following is the code in the _add_category_select_list function

<?php function _add_category_select_list($element, &$form_state) {
$mlib=new Mlibrary();
$main_category=$mlib->get_main_menu_Categories();
   foreach($main_category as $main){
       $element['und']['#options'] = array($main['category_id'] => $main['Title'])+  $element['und']['#options'];
    }

return ($element);
   } ?>

The above code populates the select list but when the option is selected it is not returning any values for the options selected. Can anyone give me a proper way to add #options to select list dynamically using hook_form_alter or any other options that will allow me to add  options from my module.

For select field we can use as follows

$form['field_task']['und']['#options'] =$arr;
//array('black'=>'black')


How to create a cronjob to update all nodes I have a content type that has a computed field that needs to be updated constantly.
So I need to create a cronjob to update all nodes of a certain type (example 'page'), so that the code is executed from the computed field and its value updated.

thx

You need to create a custom module to do this.
Implement hook_cron to create a cron job in custom module
You can update a node programatically.. For more details see node_save


What is the front page path of the Recruiter Distribution? I am using the Recruiter distribution and I want to find the path of the front page so as to add it to the 404 redirect settings of the site.
However,there is no panel page as homepage.There is only used the context module that says if path=< front > then etc.Also I tried the path /node with no luck.

So how can I find the path of the homepage?

You can define it at /admin/config/system/site-information. This is the value the <front> path uses.

UPDATE:
The default frontpage after a fresh install appears to be /node as defined per /admin/config/system/site-information


Content items with multiple images I have created a content item in Drupal 7 which has multiple image fields (well it has an image field that accepts multiple images).

When I display the item, the images are displayed one under the other, or I can put them into a lightbox gallery.

How can I change or over-ride the CSS and JavaScript code associated with these content items? Additionally, I eventually want to be able to count up the number of images in the content item and write some js to do this. But I am not sure how to find the names of the items and/or if that is indeed necessary.

My goal is to make a gallery of images that can be flicked through like many JavaScript galleries that place content in hidden tags.

You can use javascript to add css to your page after all the other css files have been  listed.

<?php
  drupal_add_js();

  // Then in the js file you can add the css file

If you are still stuck then place a link here of your site and contact me.


Adding a new taxonomy term from a custom content type field Is it possible to automatically add a new taxonomy term (related to certain vocabulary) from a field in a custom content type; so when submitting a new content entry (related to that custom content type) I add a new taxonomy term related to that entry to create a richer tagging functionality by time for future entries?

Check out taxonomy_save_term(). Here's an example from the comments:

$term = array(
'vid' => 5, // Voacabulary ID
'name' => 'Drupal', // Term Name
'synonyms' => 'Druplet', // (Optional) Synonym of this term
'parent' => 11, // (Optional) Term ID of a parent term
'relations' => array(15), // (Optional) Related Term IDs
);

taxonomy_save_term($term);

You could use this inside hook_nodeapi() on the operations insert or presave (and update). See the comments at the first link for more info.

EDIT: For drupal 7 you have to check out the node api instead of of hook_nodeapi().


Is allowing Full HTML (HTML filter on) input for all user roles safe? Is allowing Full HTML input for all user roles safe as long as I enable the HTML filter?

Only trusted roles and users should have access to Full HTML. You can add some additional allowed tags to the Filtered HTML input format but don't add too many or you risk creating a vulnerability. (admin/settings/filters)


How to disable and enable all contributed modules in Mysql? I am trying to perform core update to site that was installed from backup of another Drupal 6.16 website with content and modules. Guides suggest to disable all contributed modules during update and enable them after. (Can this be skipped?) I know that modules can be disabled by changing their "status" in system table. I was thinking that contributed modules has different path value so they might be filtered somehow. Is it a good idea to export status column of the system table, set their status to 0, and import after?

It is not necessary to disable all contrib modules during a minor update of Drupal.  If you are planning on exporting and importing your database anyway, I would recommend using Drush to do the update on a local development copy of your site.  That way, you can test the result of the update before moving it back to the live site.  It is not advisable to update your live site directly.

You might also want to give serious consideration to finding a better hosting service.  If you had ssh access, you could migrate your database from live to dev with drush sql-sync, which is a great time-saver.

Edit: If you do want to disable all of your modules via Drush, here is a shell alias that will do it (from examples/example.drushrc.php in Drush-5):

# $options['shell-aliases']['dis-all'] = '!drush -y dis $(drush pml --status=enabled --type=module --no-core --pipe)';

If you want to enable all of the contrib modules from the live site on the dev site, you could do something like this:

drush @dev -y en $(drush @live pml --status=enabled --type=module --no-core --pipe)

I don't recommend disabling modules by manipulating the SQL directly; it's much more reliable to use Drush.


Taxonomy terms not mapping in D6>D7 migrate_d2d node migration I'm using migrate_d2d to migrate content from Drupal 6 to 7. I have a taxonomy term migration and a node migration. The taxonomy term migration runs correctly and creates 11 taxonomy terms, but when the node migration runs, the terms are not being mapped.

My migration code can be reviewed here: https://gist.github.com/vinmassaro/a7bce8175aa3cafffc2035092b0fe7be

It doesn't seem to be finding anything, because when I examine the output of of $row from prepareRow, there is no [1] element in the object coming from the source. What am I missing here?

Migrate documentation says say the taxonomy terms are mapped this way, which is the format I have it in:

$this->addFieldMapping('field_taxonomy_reference', 'legacytermid')
     ->sourceMigration('LegacyTermMigration');
$this->addFieldMapping('field_taxonomy_reference:source_type')
     ->defaultValue('tid');

Thanks in advance!

I was not properly implementing the prepareRow() method, missing this part:

if (parent::prepareRow($row) === FALSE) {
  return FALSE;
}


node--content-type.tpl.php did not override and now i stuck in using node override with content type.
I followed these step.

Create new content type name post (machine name: post)
Copy node.tpl.php from module to
my_theme/templates/node/node--post.tpl.php
Go to admin-configuration-performance and click "Clear all caches"

Well, it did not work.

Sorry for create duplicated article, but when i followed from answer, it did not work too.

If you created your sub theme correctly, the sub theme is located under drupal/sites/all/themes/ and NOT in the drupal/themes folder.

So your tpl.php file needs to be in

  drupal/sites/all/themes/commons_child/templates


Is there any method (function) in drupal which gets called after nodes being created. I am creating a custom module for Drupal 7. I wanted to post the node that gets created of type "Article" to facebook wall so that user doesn't have to manually create a wall post.

For that I need to get a method (function) in drupal which gets called as soon as the nodes gets created, where I can put my Facebook API codes.

You are looking for hook_node_insert()

This is from API page:

  Respond to creation of a new node.

  This hook is invoked from node_save() after the database query that
  will insert the node into the node table is scheduled for execution,
  after the type-specific hook_insert() is invoked, and after
  field_attach_insert() is called.

function MyModule_node_insert($node) {

  if($node->type == 'article') {
    //your code here
    custom_func();
  }
}

function custom_func() {
  //your code goes here
}


Services for Privatemsg module I am using privatemsg services module to create REST API of privatemsg using Services Module in Drupal 7.

If I send GET request to this url : http://example.com/rest/privatemsg/ I get all messages including messages in Inbox and Sent. Is there any way to Get messages from Inbox and Sent separately ? OR is there any way i can differentiate messages from Inbox and Sent ?

That resource has an optional type parameter, so you should be able to get away with requesting:

http://example.com/rest/privatemsg/?type=inbox

Or ?type=sent, etc


How to pass link to Read More manually I enabled the blog module and I created the blog called test blog. I created the template file as page--blog.tpl.php. Here is my code:

News

         <?php
        $type = "blog";
        $nodes = node_load_multiple(array(), array('type' => $type));
        foreach($nodes as $news):
        ?>

                <?php print date( "j",$news->created); ?>
                <?php print date( "M Y",$news->created); ?>

<a href="<?php print $node->nid; ?>">Lorem ipsum dolor sit amet, consectetur adipiscing elit.

<?php $body = field_get_items('node', $news, 'body');
                        $teaser= $body[0]['safe_summary'];
                        print $teaser; ?>

                + Read More

If the heading or ReadMore button is clicked. I want to display full blog content of particular node in the blog content type. How to pass the link in anchor tag.

missed value in href.  replace below code.

<a href="/node/<?php print $node->nid; ?>">Lorem ipsum dolor sit amet, consectetur adipiscing elit.


How to change placement of block or region on events? I want to change the placement of 2 regions based on window size. I know that I can print 2 blocks and use css dipslay:none based on window size, but I prefer not to double print a block.

Is there any way I can change the placement of blocks / regions based on events, such as screen size, using JS or similar?

You can use the flexbox order property: https://css-tricks.com/almanac/properties/o/order/


Search API node access limitation The Search API has a Node Access Data Access Alteration which adds info into the index which can be used to implement 'normal' drupal node access restrictions to searches.

This was working fine until recently when a particular user was granted one too many Realm + grant Ids: now the Search API is throwing a hideous exception that's killing my site.

Basically Search API seems to create a JOIN for each realm:gid combo, and MySQL is limited to 64 JOINS.

Is there any way around this or is it a limitation of the Search API?

Would using Solr (never done it), for example, provide a solution?

My solution was to patch the search api db implementation.

This looks to see whether the field is a one-to-many relationship; if it is, then the table is added for each condition. I presume that this is so that these matches can then be counted and add towards the relevance score. However, for access restriction we're only interested in a single match, and (presumably) shouldn't add this to the score anyway. Therefore for this case there is no need to add a join for each possibility.

The patch below looks for this use case and ensures the user access table is only joined once.

--- a/sites/all/modules/search_api_db/service.inc
+++ b/sites/all/modules/search_api_db/service.inc
@@ -1028,7 +1028,12 @@ class SearchApiDbService extends SearchApiAbstractService {
           $cond->condition('t.item_id', $query, $f[2] == '<>' || $f[2] == '!=' ? 'NOT IN' : 'IN');
         }
         else {
-          $alias = $this->getTableAlias($fields[$f[0]], $db_query, search_api_is_list_type($fields[$f[0]]['type']));
+          // the user access node table only needs joining once; we're not interested in
+          // scoring based on access; access is a boolean, so we do not need muliple joins
+          // which can break the query if there are more of them than the SQL engine allows joins
+          // (e.g. MySQL is limited to 64 joins).
+          $rejoin = search_api_is_list_type($fields[$f[0]]['type']) && ($f[0] != 'search_api_access_node');
+          $alias = $this->getTableAlias($fields[$f[0]], $db_query, $rejoin);
           $cond->condition($alias . '.value', $f[1], $f[2]);
         }
       }

EDIT: LOL - or as they did it...

+          $new_join = search_api_is_list_type($field['type'])
+              && ($filter->getConjunction() == 'AND'
+                  || empty($first_join[$f[0]]));
+          if ($new_join || empty($tables[$f[0]])) {
+            $tables[$f[0]] = $this->getTableAlias($field, $db_query, $new_join);
+            $first_join[$f[0]] = TRUE;
+          }
+          $cond->condition($tables[$f[0]] . '.' . $field['column'], $f[1], $f[2]);

Answer is: upgrade module to v7.x-1.0!


Modules needed to create the best WYSIWYG experience? What do you use to give the end user (editor) the best WYSIWYG experience, considering the following requirements (besides basic input):

Insert images/flash and align then left/center/right with optional caption, choice of sizes
Easily upload files and add links to them
Add custom css classes to content
Add custom buttons that provide custom/special formatting
Be truly WYSIWYG, i.e. using styles/typography that the end user will see

From a developer/maintainers point of view:

Keep front-end theme styles in-sync with styles used in WYSIWYG editor

Thanks, Egil.

You will need the Drupal WYSIWYG module http://drupal.org/project/wysiwyg and the TinyMCE Library here http://www.tinymce.com/

TinyMCE supports plugins and you can make that "best WYSIWYG experience" that you are looking for. You can hook it up with your theme CSS and apply styles to the text aeras and see them in the WYSIWYG. Also check the WYSIWYG plugins page http://drupal.org/node/1197256


How to keep some fields or a content type private I have a content type for concerts, and a view for upcoming concerts.

For some of the upcoming concerts, the performer (site owner) wants to list just the date and the venue, but cannot list the title of the performance, because the company has not yet announced the season.

Is there a way to keep part of a node of that content type private, preferable until a specific date has been reached?

I am looking for a secure and foolproof solution, because I don't want to be subject to a lawsuit, in case the information leaks prematurely.

The alternative could always be to create two nodes - one of them published with only the public information, with an expiration date, the second one with the full information, initially unpublished, with an automatic publish date. However, I would like to provide a more comfortable way to input the information - add it only one time and don't worry about it.

So, for the alternative solution - what is the best way to create a node from a node with extracting part of the info of the parent node to the child node? For this scenario, I imagine changing the content type permissions to allow only authenticated users, and creating or updating child nodes in a "public" content type with the allowed subset using something like rules.

Any hints would be greatly appreciated.

You can do this using Views. Set up a contextual filter for the node id. And then a filter that sets a condition on your date field. This means the View will only have results when (a) your node is displayed and (b) the date condition is matched. Set the filter up as a block. And set that block to show only for that node type.

This is an approach I've used a lot. For example, you can use the same approach to show some fields to logged on users but not to non-logged on users. In effect, you're using the View to show fields depending on some condiiton.


Generate reports of similar web forms results In Drupal 7, I want to generate a report of similar webforms (same fields but created 2 webforms to handle multilingual translations) results. All the fields in my both webforms are same. I tried to use Views to fetch the results of both webforms, which is not working.

Any idea on how to achieve this?

I did this to get the filename of teh fid saved in webform_submitted_data table.

Added SQL:

SELECT wsd.nid, wsd.sid, fm.filename,
       MAX(CASE WHEN wsd.cid = 2 THEN wsd.data END) fn,
       MAX(CASE WHEN wsd.cid = 3 THEN wsd.data END) ln,
       MAX(CASE WHEN wsd.cid = 4 THEN wsd.data END) email,
       MAX(CASE WHEN wsd.cid = 5 THEN wsd.data END) ph,
       MAX(CASE WHEN wsd.cid = 6 THEN wsd.data END) tr,
       MAX(CASE WHEN wsd.cid = 7 THEN wsd.data END) upr,
       MAX(CASE WHEN wsd.cid = 9 THEN wsd.data END) coc
  FROM webform_submitted_data wsd LEFT JOIN file_managed fm ON wsd.data = fm.fid WHERE nid IN(66,67) GROUP BY wsd.sid;

If Views can't do what you're trying to do, you might want to consider the Forena module (disclosure: I'm a co-maintainer) as a possible alternative.

As an example, create a custom "data block" (which is just an SQL statement) that fits your needs, to retrieve the webform data that you're interested in. Here is a (basic) example:

SELECT s.nid AS node, s.sid AS submission, d.cid AS component, d.data AS fieldvalue
FROM {webform_submissions} s JOIN {webform_submitted_data} d ON s.sid=d.sid
WHERE d.cid=3 AND s.nid=5
ORDER BY s.sid ASC

Then create a Forena "report" that uses this data block (maybe you want to enable something like the "CSV" option, within "document types"). Here is the (basic) layout of such report to illustrate the idea:

          node
          submission
          component
          fieldvalue

          {node}
          {submission}
          {component}
          {fieldvalue}

After you saved the report specifications and then browse the generated report, you could have a "CSV"-hyperlink (upper right of the report). Just use that link and ... voilà, there is your CSV file (in this case with 4 columns, since that is what in my (basic) report I asked for).

If this makes sense, head of to the Community documentation of Forena to get you going (which includes pointers to video tutorials). Or use the documentation that comes with Forena.

Of course, building the appropriate SQL statement to perfectly fit your needs is going to be crucial. But apart from that, it's just basic usage of Forena.

Update

To "create a temporary table" (as in your comment below this answer, and also per your updated question), you may want to have a look at what's suggested (by David Metzler) in this feature request. Though I personally have no experience with using Forena to create such temporary tables.

Reminder: Forena is to query data (as in your first version of your question), not to update, delete, etc such data.


What to choose Content Type or Drupal Commerce or Ubercart I'm working on a project where we've people managing product in site (including product creation, editing, viewing, reviewing, etc.). These are not going to be techie people so the product management should be easy to use with quick loading. The site as of now doesn't allow users to sell and buy product online (It might allow in future, but not confirmed - very less chances). Its just viewing, reviewing, rating products. Also there will be variety of product. We're also planning on creating Mobile App for this so user can manage products from App.

As I've already worked with all of these 3 earlier, my personal thought is that Drupal Commerce and Ubercart may add an extra overhead of e-commerce functionality on our site. I need suggestion on how should we proceed here, what things should we consider while selecting any one of these 3. What should be best choice to go ahead in such scenario i.e. Plain content type or Drupal Commerce or Ubercart.

Just go (start with) what you call "Plain content types".

For the "rating" requirements, have a look at my answer to "What are recommended modules or processes which support rating based comments or reviews?".

Should you ever want to expand that to a (rather basic) e-shop and/or add a shopping cart, you can always use the modules as I suggested in my answer to "How to create a simple shopping cart without Drupal Commerce or Ubercart?".

Next question?


How do I get a field translated in Drupal 8 I have a multilingual site in Drupal 8, and several node, some translated and others not.
As I can programmatically get the translated field or by default they give it back from the original language.

I got this:

$service_entities = entity_load_multiple_by_properties('node', array('type' => 'service'));

$services = [];
foreach ($service_entities as $entity) {
  $services[] = [
    'title' => $entity->title->value,
  ];
}

This code work fine, but when the title is translated Drupal give back in the default language in which it was created.

You can get a specific translation with $translation = $entity->getTranslation('de'), then you can use $translation exactly the same as $entity.

Usually, you don't want to get a specific translation, but the best translation that is available for the current language, for that, use getTranslationFromContext():

 $translation = \Drupal::service('entity.repository')->getTranslationFromContext($entity);


Creating module with autocomplete and accepting multiple values in textfield I am creating my own form in my module using the Form API.

How do I enter multiple values in the below textfield and have it autocompleted, and suggested (separated by commas, for example)?

Right now it takes whatever is in the textfield box as one single big string.

$form['keywords'] = array(
  '#type' => 'textfield',
  '#title' => t('Keywords'),
  '#size' => '40',
  '#multiple' => TRUE,
  '#autocomplete_path' => 'papers_pub_search/keywords_autocomplete'
);

function _autosearch($string) {
  $query = "SELECT name FROM users WHERE name LIKE :name";
  $result = db_query($query, array(':name'=> '%' . db_like($string) . '%'));
  foreach($result as $row) {
    $match[$row->name] = check_plain($row->name);
  }
  drupal_json_output($match);
}

You can use the following code.

function _autosearch($string) {
  $matches = array();

  if ($string) {
    $items = array_map('trim', explode(',', $string));
    $last_item = array_pop($items);
    $prefix = implode(', ', $items);

    $result = db_select('users')->fields('users', array('name'))->condition('name', '%' . db_like($last_item) . '%', 'LIKE')->range(0, 10)->execute();
    foreach ($result as $user) {
      $value = !empty($prefix) ? $prefix . ', ' . $user->name : $user->name;
      $matches[$value] = check_plain($value);
    }
  }

  drupal_json_output($matches);
}

This is the result.

If you want to avoid a username can be used more than once, then you can use the following code.

function _autosearch($string = '') {
  $matches = array();

  if ($string) {
    $items = array_map('trim', explode(',', $string));
    $last_item = array_pop($items);
    $prefix = implode(', ', $items);

    $result = db_select('users')->fields('users', array('name'))->condition('name', '%' . db_like($last_item) . '%', 'LIKE')->range(0, 10)->execute();
    foreach ($result as $user) {
      if (!in_array($user->name, $items)) {
        $value = !empty($prefix) ? $prefix . ', ' . $user->name : $user->name;
        $matches[$value] = check_plain($value);
      }
    }
  }

  drupal_json_output($matches);
}


Can't log in to Drupal instance after duplicating database I wrote a quick script to pull down a live drupal database on to a machine on a local network, and that works fine.

I also made a copy of the actual Drupal instance on my own machine.

I edited settings.php to use the db on the network, and everything appears to be working correctly when I run the site from localhost, except I can't log in.

At first I thought I should just change the password directly using MySQL, but that didn't work. Then I tried running update.php, which also didn't work.

I'm stuck, why won't it accept the username/password? I have double checked that I'm using the correct login credentials on the live site, and it works fine.

Edit: The site was duplicated from a Linux server onto a Windows 7 machine, if that makes any difference.

First check whether $cookie_domain is set to localhost or not?

If it is set as the URL of the live site then it might not work. I faced this issue previously.

Other cause might be clean urls. You can check whether clean URL is enabled in your localhost or not.

You can check whether mod_rewrite is on or not here. If clean url is causing problem then you can disable from your database. If you want to disable clean url goto your database find variables table, find clean_url variable and set it to 0.


How can I achieve taxonomy workflow (allowed next states of taxonomy terms)? I have a vocabulary containing some terms for issues' states:

Open
In progress
Closed

I want to be able to define allowed "next" states for each term. So that a user can only change:

Open -> In progress
In progress -> Open, or Closed
Closed -> None

I am using Drupal 7.

I don't think there's a ready made solution for this. The maintainer of workbench_moderation has said that a goal is to collaborate with other workflow modules and made one module to rule them all, and one of the primary goals of that initiative is "workflows for non-node entities" but this is still a long way off and doesn't seem to be very far past the planning stages at this point.

So I think the closest you can get currently is the taxonomy_revision module but that just adds revisions and doesn't help in automating a workflow out of them, so you'll have to do some custom development on top of that.


Why entity_metadata_wrapper->save() doesn't update node's revision? I'm developing a module to update nodes(enable revision). It looks like this.

 $nodes = node_load_multiple(array(), array('type' => $bundleType));
 foreach ($ndoes as $node){
    $w = entity_metadata_wrapper('node',$node);
    $w->MyFields->set($someValue);
    $w->save();
 }

It set fields correctly but node's revision-id didn't change after $w->save().

How can I update the revision ID?

When you edit a node via the UI, it is done via node_form().  This has a call near the top to node_object_prepare(), which sets up default values for that node.  This includes setting the default value of $node->revision, which is used by node_save() to determine whether a new revision is needed or not.

The Entity API is revision aware, but node_object_prepare() is a node-specific thing.  This means that you need to manage the values yourself, including setting the revision property to mimic what the node edit form will do.


Image upload in content type, no previous image is present Oddly worded title, I know. I'm not sure how to phrase it or what to ask exactly.

In previous versions of Drupal if I added an image field to a content type, once an image was uploaded it was saved in a library of images and it was available without being uploaded again.

Currently in Drupal 8.5.4 that's no longer the case.

I'm given the option to either upload or embed but not to select from an already existing list of uploaded images.

This is more of a nuisance since I have to reupload images even if I want to use them on a separate content type.

I'm not sure if this is a bug or it has completely changed in this version.

Drupal 8 bug tracker doesn't offer anything relevant.

Any help is appreciated.

A little more configuration is necessary to add the feature of browsing existing media, you can do it with Entity browser and Core Media module in Drupal 8.5 and upwards.

Here's a great tutorial on how to do that, you need the Part 4: How to Browse Media Assets: Managing Media Assets using Core Media in Drupal 8


TinyMCE buttons by content type I installed tinyMCE with IMCE in my Drupal 7 site. I'm finding a way to show different buttons in tinyMCE editor by each content type. For example, the image button is displayed for the Article content type, but it will not be displayed for my custom content type.
Is there a way to set this up with the existing module?

You need 2 text-formats.  Allow "Image" in tinyMCE profile of one text-format and not allow it for the other.

To set fixed text-format to each text-area field, you can use Better Formats module.  Download from http://drupal.org/project/better_formats and install it.

In "Managed Field" page of your text-area field, check "Filtered text (user selects text format)" and "Limit text format".  You will see all your defined text-formats with leading check-boxes.

Click the check-box of a text-format and save.  In your "Add Content" page, you will see your text-area is assigned with respective tinyMCE editor.


What is the url for product page in drupal commerce. Its admin url is : admin/commerce/products/2 I am using drupal commerce for first time. I have created a product. I am unable to find the product view url. Its admin url is : admin/commerce/products/2

In Drupal Commerce, you need to add product entities separately from product display pages. We simply create a product display node and reference all of our product entities using the product reference field.

See the docs for more help on this.

http://www.drupalcommerce.org/user-guide/products


Upgrading complex content types from D6 to D7 I have a Drupal V6 website with some complex content types that I have created using CCK and Contemplate. That is, the content types have fields of type Text, Integer, Link, Node Reference and so on. I've been unable to upgrade this website to Drupal V7.

I have a few Drupal websites without complex content types and I've been able to upgrade those so I think I understand the general upgrade concepts and procedures. However I'm having trouble with this particular site. The process seems to complete normally, but nodes with complex content types have not migrated and only their basic fields can be displayed and edited. Checking the DB, the raw data appears to be there.

I've read the standard upgrade procedure and the CCK upgrade procedure but with no luck. Has anyone done this themselves and can you outline the steps you took.

I had the same Problem, but when you follow cck upgrade procedure step by step, it works. I think you need additional Variable Check Module. After upgrade i had 2 corrupted vars. With Variable Check you can find corrupted vars and remove them.

My solution:

many cck fields are included in core
download and unpack missing modules in to sites/all/modules
download "cck 7.x version", "variable check" and unpack
after upgrading activate "Variable Check" and "CCK Content Migrate" modules
run upgrade.php
under admin/reports/variablecheck check the validity of settings in the variable table


Selected/Restricted Autosubmit with Better Exposed Filters in Drupal I'm using the Better Exposed Filters module to manipulate the filters in my view. It works great except for one issue that's affecting the whole layout.

Within my view I have four exposed filters out one is a Search (Search Terms). The auto submit works perfectly with the checkboxes filter but makes the search unusable. It basically submits it on every keypress and that hinders writing the complete word.

Is it possible, that I could have autosubmit on all filters except one (Search Terms filter)?

The documentation in CTools suggests adding the class ctools-auto-submit-exclude in the element #attributes key for the form element you don't want to processed:

function MODULE_search_submission_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "views_exposed_form") {
    if (isset($form['keys'])) {
      $form['keys']['#attributes']['class'][] = 'ctools-auto-submit-exclude';
    }
  }
}


How to add existing taxonomy terms to node on saving I've a field organization_name which is term reference with unlimited values. Whenever somebody saves the node I want to attach a few more terms in this field.

I've tried doing using hook_presave and also using submit handler of Forms API.

But the problem is that they both expect the term to be filled with plenty other values as below. Where do I get those values? From taxonomy_term_load ?

This is the dsm out of the form_state array in the form submit handler.

The only place you need to add values in your hook_form_alter() is the $form_state['values'] array. In there you should only see the tid value, not the whole term entity.

Alternatively, you can use the Rules module


Delete/create nodes programmatically I created a custom module that uses the Taleo Web API to get data from the external Taleo database and make nodes from this data. This works great.

But now I want to run this update script every night... The script works great whem I logged in into Drupal.

What would be the safest way to allow deleting and adding nodes programmatically when logged out?

function taleo_menu() {
  $items['taleo-update'] = array(
    'title' => 'Taleo Update page',
    'description' => 'Taleo Update page',
    'page callback' => '_taleo_update',
    'access arguments' => array('view content'),
        'type' => MENU_NORMAL_ITEM,
  );
    return $items;
}

function _taleo_insert($jobs) {
    foreach ($jobs as $job_object) {

        $node = new stdClass();
        $node->type = 'job';
        $node->title    = $job_object->title;
        $node->language = LANGUAGE_NONE;

        node_object_prepare($node);
        $node = node_submit($node); // Prepare node for a submit
        node_save($node); // After this call we'll get a nid
    }

    drupal_set_message(t('Added %count jobs.', array('%count' => count($jobs))));
    return array();
}

If you are looking for the safest way, I would say your current approach is not how most of us get things done in Drupal.

Basically, you can make use of a hook that wakes up your module, check last run's status and if suitable, start its next run.

Check out hook_cron. You can check last run status easily from a variable_get (you need to set the value first using variable_set). Cron runs anonymously regardless of a specific page call. Even if the cron runs frequently, you can use some condition to check last run timestamp and compare it to current system time. If it has exceeded the interval (1 day), you can now run the "create nodes" function.

If nodes are saved correctly, you will see a $node->nid set. use that as a condition and if all given jobs are done, you can set the last run variable to the current time.


How to track Drupal user login-logout session length and registration activities? Is there any hook_function/code in Drupal where I can track user activity, like:

User core logged in time / or third party login
User log out time
Login-Logout session length (active time)
registration submit core or / third party submit.

Please share event for these activity.

For standard login, and 3rd-party login modules that are properly integrated with core, you can use:

hook_user_login()
hook_user_logout()
hook_user_insert()

For 3rd-party login modules that aren't properly integrated with core (i.e. don't fire those hooks), you'll need to approach each on a case-by-case basis, and find out what hooks they provide.

You could measure the duration of the session in hook_user_logout, by checking the account object's login property against the current time -  there's no hook for such a thing as it's not an event, just a value which needs some context to give it meaning.


How to create a rule for changing a user field to a random string? Using the Rules module, I would like to have a replacement the is a random string.

I have added a new user field (= some_var, which is a 'Text field' data type), which I would like to change to some random string after the User account is created.

Any ideas or hints to get this to work?

There is a (sandbox) module for it, which is the Rules Random module. Here is a quote about it (from the linked page):

  A simple rule action to generate either a random string or integer. Can define the length of the random result. For random strings, can also choose to include numbers and lowercase letters.

Either you just use that module, or you look at its source code to understand what it takes to include this logic in your own (custom) module.

With that, all that's needed is to create a custom rule like so:

Rules Event: use whatever event that fits your requirements (eg: After saving a new account).
Rules Condition: "Entity has field", related to your some_var field. That will make this field available for subsequent processing in Rules Conditions and/or - Actions.
Rules Action: Use the action provided by this module, to set a value for your some_var field.


Strict URL alias checking with optional 404 redirect When I create a node with "This is sample title" as title, the Pathauto module will create "this-is-sample-title" as URL alias and some "node/123" as real node URL. But we can browse the same content with a different URL such as

SERVER/this-is-sample-title
SERVER/this-is-sample-title/some-garbage-here

In node head source code canonical url is set to "/this-is-sample-title" and shortlink to "node/123".
How do I make Drupal strict on the URL alias and redirect to 404 if URL garbage found (even if first URL segment is correct)?

You can use the url_inbound_alter hook to verify if the internal path of the request matches the used url alias. If not, trigger a 404.

function YOURMODULE_url_inbound_alter(&$path, $original_path, $path_language)
{
    if ($path === $original_path) {
        // path is same as url alias - don't do anything
        return false;
    }

    $alias = drupal_get_path_alias($original_path);
    if ($alias && $alias === $original_path) {
        // alias is same as url alias - don't do anything
        return false;
    }

    drupal_not_found();
    drupal_exit();
}

I've tested on some projects which are using the most common contrib modules (Pathauto, Globalredirect, Views, Sitemapxml, Wysisywyg, ...), and I don't have the problem. Url alias verification is strict and returns 404 for non existing aliases. But I'm able to reproduce it with custom menu callbacks (custom code or views).


Is there a module that provides a field for referencing values of another field Initially I thought I could use the same field on both entities, but I want the user to be able to select unlimited values from the reference field limited to the options that could exist in the original field.

In the field settings, I need to have the ability to select a field to reference.  When looking at the field instance I'd like to be able to tell which field the value should be compared against.  The user should be able to select from all of the possible values of field A and store that selection in field B.

Changed this, as it made it sound like I wanted something similar to node reference

  Entity 1: Field A

  Entity 2: Field B (Values from Entity 1: Field A stored in Field B)

The goal is to be able to use Field B to find entities having Field A that are the same value

Is there any way to achieve this kind of relationship between fields?

Field reference module may help you !

  Defines a field type for referencing one field from another.

  This module is modelled on Node reference and usage is similar.

  Depending on configuration, authors can pick fields from the same
  node/entity, from other nodes/entities, from specific revisions, from
  specific languages, or even a specific delta value within the field.
  Fields can be displayed using either the 'full' or 'teaser' mode from
  their original node/entity.


Is there a reason why I shouldn't be able to upload more than 95 items on to an image field? I have an unlimited items on a simple filefield using an image widget.
When a user upload more than 95 images, after saving the node, it turns it to unpublished and it removes the authoring information.

Afterwards, when you go back to edit the node it doesn't save any changes. Basically you have to go to the database and delete the extra rows until there are only 95 to be able to edit the node again.

This is critical because most of the nodes are supposed to have around 130 images.

Any suggestions?

I've already increased the php memory to 128M thinking it might be a memory problem because it looks like the save function is not executed properly.

Also, worth noting that if I change the order of the field on "manage fields" and get the image field on to the last slot, it save everything but the image field.

Thanks in advance! Any help will be greatly appreciated!

Installation:
Drupal 6
CCK - 6.x-3.0-alpha3
FileField - 6.x-3.10
ImageField - 6.x-3.10

Solution is to increase upload_max_filesize and post_max_size in your php.ini. Because POST data can be truncated if it exceed specified limits.
This can happen when you upload lot of images and send them all in one big POST.

Other way to fix this - is automatically upload image via AJAX request just after user select it - try JavaScript code from How can I automatically upload images on file selection rather than pressing the upload button?

Also try to increase max_execution_time in PHP settings. PHP may be lack of time to upload and save all 95 images during default 30 seconds.


Populate Dropdown list from a web service without code I know that in Drupal a drop down list field can be populated with taxonomy terms, but is there a way without having to go custom (custom PHP development) to populate a dropdown list from the results of consuming a web service?

Say I consume a web service that returns the weather for the current week (7 days), I would like to populate the data returned into a dropdown list so that whenever the data is changed at the web service it is automatically reflected in my list.

Is there way to do this in the Drupal UI?

Many Thanks

I think you have to do it in code call the webservice in a custom module process the results and pass it to the template for display as you need


Exposed Form in Block Missing? I'm trying to create a view based on a Solr search index that includes a search form in a block. The view seems to be working based on the preview I see when editing the view. I have set "Exposed form in block: Yes" and "Exposed form style: Basic". The block is assigned to a region, and the block itself is rendered appropriately when the page is displayed. The problem I'm having is that the form is not displayed in the block. I see the block title, but no form and no button. What might I be missing here?

Exposed filters on blocks will only work if you've enabled ajax on the view. Try enabling that and your filters should appear


Use Statistics module to view published/unpublished nodes I would like to know how to see the total number of nodes that have been published and the nodes that are yet to be published using Drupal 7 Statistics module.

I have installed the Scheduler module to publish nodes based on time.

The Drupal 7 Statistics module is for monitoring web pages. It records when pages are viewed and who viewed it. Per its documentation, "these statistics are useful in determining how users are visiting and navigating your site."

I think what you're asking for is a module that counts the content (i.e. the individual nodes). You should be able to do this with Views, by selecting the appropriate Fields (what kind of content), Field Filters (published or not), and then "Use Aggregation" (to calculate counts). I found a module called Count that might do what you want, but it's only for Drupal 6.

I'd be interested in other people's answers on your question.


drush make build script tries to download project itself from drupal.org I use a drush make build script to install a profile. Just started that install profile project.

https://raw.githubusercontent.com/groovehunter/releasemanager/master/build-releasemanager.make

When I do

drush make "https://raw.githubusercontent.com/groovehunter/releasemanager/master/build-releasemanager.make" -v -y

it prepares the core and tries to download

Loading release_info engine.                                                  [notice]
Unable to clone releasemanager from                                           [error]
http://git.drupal.org/project/releasemanager.git.

but that's oviously not successful. THe code is on github only. I have no clue where drush get the information the project lives on drupal.org ?

Cleared drush cache, also manually, but Cannot get it now

seems there were some wrong cached files.

I removed all ~/.drushrc/cache/git and downloads


Want to build a widget which gives price history on Drupal 7 We have our site built on Drupal 7. We want to make a widget which gives price history chart.

I found a module named Commerce Price History.
Can this module be used with Drupal 7 or it can be used only with Drupal
commerce.

Is there any other Drupal Module which can achieve the same.

I've just come across a module called Track Field Changes which may be ideal for you needs.

I found the documentation a bit lacking however but to get it to work I:

Install module
Visit /admin/config/system/track_field_changes and select your product node type
Save the configuration and then product will appear as a menu item in the left menu. Click it.
Select the price field and again save the configuration.
Create a new view that shows content of the type of your products.
Add the field called "Field Tracker: Value After (Value After)"

This will then show a log of all of your price changes. To then turn this into a graph check out the Views Charts module.


How to get random query? I use this code in my module for random query:

$query = new EntityFieldQuery();
$query
->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'client')
->fieldCondition('field_client_enabled', 'value', 1)
->addTag('random')
->range(0, 1)
->execute;

with additional function:

function mymodule_query_random_alter($query) {
  $query->orderRandom();
}

But why I get "undefined method" error when use

$query = new EntityFieldQuery();
$query
->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'client')
->fieldCondition('field_client_enabled', 'value', 1)
->orderRandom() // why is this wrong?
->range(0, 1)
->execute;

?

Update:
Answer:
Found that orderRandom() is SelectQuery function, but not EntityFieldQuery

Can I simplify first code to variant without additional function?

Can I simplify first code to variant without additional function?

Not natively, as you've rightly said EFQ doesn't have a random order method. At a guess that's because field storage is pluggable, and it would be tricky to come up with a cross-compatible method that makes sense for e.g. MySQL and MongoDB. Might be wrong though, it may simply not have been considered important enough to implement/overlooked/etc.

If the extra step is unacceptable, the other option would be to subclass EntityFieldQuery to add your own random order method, and override the execute callback with your own version of field_sql_storage_field_storage_query() to get it into the final query.

The method you already have is arguably a bit cleaner than that; certainly it's less effort.


How can I reference an entity field in a template file? I am trying to theme the node add/edit form for a custom content type (for example, Album). I implemented hook_form_alter() in the theme.
function mytheme_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  switch ($form_id) {
    case "node_album_form":
      $form['#theme'] = ['node_album_edit_form'];
      break;
  }
}

That correctly intercepts the node add/edit form and passes it to my theme hook which also finds the correct template.
function mytheme_theme() {
  return [
    'node_album_form' => [
      'template' => 'node_album_edit_form',
      'path' => \Drupal::theme()->getActiveTheme()->getPath() . '/scss/templates/album',
      'render element' => 'form'
    ],
  ];
}

In node_album_edit_form.html.twig, I can confirm that changes there alter only the album add/edit form and that I can remove elements with {{ form|without('advanced', 'footer', 'actions') }}, for example.
What I cannot do is placing the form fields where I want them because I'm not using the right reference to the field.

{{ field_album_title }}

{{ field_artist }}

I tried any of the following, but they didn't work.

{{ field_album_title }}
{{ form.field_album_title }}
{{ album_title }}

How can I reference an entity field in a template file?

Change your hook_theme code to:
function mytheme_theme() {
  return [
    'node_album_edit_form' => [
      'path' => \Drupal::theme()->getActiveTheme()->getPath() . '/scss/templates/album',
      'render element' => 'form'
    ],
  ];
}

and in your template file
{{ form.field_album_title }}


Domain relationship module for drupal 7? I want to create parent/child relationship in domain access module.
My use case is:

Parent Domain:
->child Domain

When I add a node to the child Domain it should also be automatically created on the parent Domain with an administrator approval required on the parent domain.

Means when I created a node on child domain it should be published and visible to the users on the child domain but it should not be visible to the user on the parent domain unless the administrator approve it.

I looked at the domain relationship module but it is only for drupal 6. Is there any alternative for domain relationship module for drupal 7?

I don't think you need another module.
Just use Domain Access.

You can let users choose to which domain this node will be published.
Make sure that the user that needs to approve the node has the following permissions:

Publish content to any assigned domain
Set domain access status for all content.


Add aditional field with title to every node I am trying to add additional field to nodes. I could add the field but I can't find a way to add its title. I have implemented the hook_node_view .
My code is

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

  $node->content['my_additional_field'] = array(
      '#markup' => "additional field",
      '#title' => "additional title",
      '#weight' => 1000
    );
}

The title is not appearing where the node is being printed. How can I add the title for this additional field?

As far as I know there's no generic #title property (it's certainly not mentioned in the render array docs); forms use them, but I don't think extends to any render array.

#prefix would be the way to go:

$content['my_additional_field'] = array(
  '#markup' => "additional field",
  '#prefix' => "
Title
",
  '#weight' => 1000
);


Permissions to edit only the Status of an order I have created a role called "Order Manager", he should be able to

View all the orders.
Update the status of any order.
Not be able to edit(can edit only the status field, nothing else)/or delete any order.

How do I achieve this in Drupal Commerce?

Install Views Bulk Operations
Clone the default user/orders/% view of all the orders, and restrict it to your new role.
Add a Bulk Operations field to the view in step 2.
Follow the steps outlined as you add the new field from step 3. You can limit which status states the user can select while modifying.


How to show conditional tab in webform 7.x-3.x I created an enquiry form using the webform 7.x-3.x module and I want to create condition on field, but not showing conditionals tab.

I also use webform_conditional 7.x-1.0-beta2 but conditional tab not  showing.

But,
I create again enquiry form from webform 7.x-4.x Module. In webform i show conditionals tabs.

My question is how to show conditions tabs in webform 7.x-3.x. I not want to upgrade module webform 3.x to 4.x.

Have any configuration or module to show conditional tab.

If you specifically want to use this within webform you need to use webform conditional to work smoothly.


How to get the field collection field value in twig file? I have field collection field. I need the field value in field in twig file.
How to print the field value.
Image of the below code.
{% for item in items %}
    {{ kint(item.content) }}
{% endfor %}

Need the "field_project_from" date field value.

Say you have a field collection field_test and the field collection has fields say field_name and field_age, you can access them using the below snippet.

{% for details in node.field_test %}
    Name: {{ details.getFieldCollectionItem().field_name.value }}
    Age: {{ details.getFieldCollectionItem().field_age.value }}
{% endfor %}

See reference and
another reference

I assume getFieldCollectionItem().field_name.value is what you are looking for.


Is there a way to add a button to my form that does not submit the form but performs a mini validation and adds more inputs to the form In my module's admin configuration page, I have a simple textfield that needs to be filled out before any other input of the form even appears. I thought that this could be done by adding a small button next to the textfield that, when pressed, will perform all the validation that I need (I have already created the functions that will be used) and then additional "select" form elements will be generated. Anyone knows how I can do this?

You can use #limit_validation_errors to limit the fields validated when a form is submitted with the button you add.
If you set $form_state['rebuild'] in the validation handler you add for the button the form will be rendered again instead of being submitted.
Then all you have to do it add some logic to the form that will display the extra fields. This can be done with the data in the $form_state.


Switch to data selection meaning? I'm setting up rules, trying to setup HTML emailing. I've it setup but not sure how to configure it. What does Switch to data selection mean?'

For an email action, there are 2 different input modes for the fields in Send HTML email action.

Direct input mode: You're supplying most of the data (e.g. the HTML body) with different token (e.g. [site:slogan]) inserted in it.
Data selector mode: You're using a widget (see image) that lets you drill into data that the Rules action has available. This is useful for finding contextual data (e.g. retrieving the current user's email when a node is updated).


Callback function in menu items field Is it possible to put callback function here $items['callback?'] ? I need to change this field every time when user make some changes. The biggest problem for me is that hook_menu() is cached and menu is rarely updating.

Technically, you can use a function to return an array of menu router items but practically it will not work because of caching.

However you can register wildcats paths like companies/so your page callback will be fired on every companies/ pages.

To do so, set the key of the $items like this:

$items['companies/%'] = array(...menu router info here ...);


Can drush show list all available modules? With yum you can do yum list available ..., and know the name of the package you want to install.

For example, there is the Mime Mail module in Drupal. What name should I use with drush dl, mime_mail, or mimemail?

So does drush have something like yum list available?

No, drush can't do that.

Why should it when you can see the entire list yourself on drupal.org.


How to create a view of counts of taxonomy reference fields by each user? I have a content type that contains a taxonomy term reference field. each user can create unlimited nodes of this content type and select different term at each time. now we want make a view of count of this terms selected by users as a table like this:

is there any plugin to support create these type of tables in views? or we should do it programmatically? I appreciate any help.

In the Advanced > Other section of the view, you should be able to enable aggregation.


Why /Drupal\Core\Form\FormBuilder->renderPlaceholderFormAction is taking so long? I'm profiling drupal 8 website in New Relic

Report shows me that method:

  /Drupal\Core\Form\FormBuilder->renderPlaceholderFormAction

takes ~2sec.

This method is called in:

  \Drupal\Core\Render\Renderer->doRender

Code related to execution:

// Build the element if it is still empty.
if (isset($elements['#lazy_builder'])) {
  $callable = $elements['#lazy_builder'][0];
  $args = $elements['#lazy_builder'][1];
  if (is_string($callable) && strpos($callable, '::') === FALSE) {
    $callable = $this->controllerResolver->getControllerFromDefinition($callable);
  }
  $new_elements = call_user_func_array($callable, $args);
  // Retain the original cacheability metadata, plus cache keys.
  CacheableMetadata::createFromRenderArray($elements)
    ->merge(CacheableMetadata::createFromRenderArray($new_elements))
    ->applyTo($new_elements);
  if (isset($elements['#cache']['keys'])) {
    $new_elements['#cache']['keys'] = $elements['#cache']['keys'];
  }
  $elements = $new_elements;
  $elements['#lazy_builder_built'] = TRUE;
}

Method code:

 /**
   * #lazy_builder callback; renders a form action URL.
   *
   * @return array
   *   A renderable array representing the form action.
   */
  public function renderPlaceholderFormAction() {
    return [
      '#type' => 'markup',
      '#markup' => $this->buildFormAction(),
      '#cache' => ['contexts' => ['url.path', 'url.query_args']],
    ];
  }

 /**
   * Builds the $form['#action'].
   *
   * @return string
   *   The URL to be used as the $form['#action'].
   */
  protected function buildFormAction() {
    // @todo Use <current> instead of the master request in
    //   https://www.drupal.org/node/2505339.
    $request = $this->requestStack->getMasterRequest();
    $request_uri = $request->getRequestUri();

    // Prevent cross site requests via the Form API by using an absolute URL
    // when the request uri starts with multiple slashes..
    if (strpos($request_uri, '//') === 0) {
      $request_uri = $request->getUri();
    }

    // @todo Remove this parsing once these are removed from the request in
    //   https://www.drupal.org/node/2504709.
    $parsed = UrlHelper::parse($request_uri);
    unset($parsed['query'][static::AJAX_FORM_REQUEST], $parsed['query'][MainContentViewSubscriber::WRAPPER_FORMAT]);
    return $parsed['path'] . ($parsed['query'] ? ('?' . UrlHelper::buildQuery($parsed['query'])) : '');
  }

I don't get it at all. This is basic method, no rocket science and 2 sec of execution :(

New Relic output:

Pretty sure that report is bogus.

That's just an arbitrary method, not a controller. They somehow identify that as the controller for that request but of course that doesn't make sense. That page lists transactions, so complete requests, not single method calls. So some requests take 2s which it incorrectly identifies as this.

Looks like new relic still can't reliably detect the route/controller for a request. Try our new relic module: https://www.drupal.org/project/new_relic_rpm. It reports the route name for the controller, then you'll see what kind of request this actually is.


Contextual filter with taxonomy term that is not in the url I'm hoping someone could please help me tame the beast that is known as contextual filters. :) I have a series of nodes that all have a specific taxonomy term assigned to them (all from the same vocab), but for my url path I do not include those:

For example:

Vocabulary name = videos

A node has terms:

-food
--vegetable
---carrot

assigned to it, but the only url that I want is:

site.com/videos/title-of-node

And then all other nodes which have terms on them will all be under the 'videos' directory:

site.com/videos/title-of-another-node
site.com/videos/title-of-yet-another-node

I created a view that has a contextual filter where I want to display only the nodes that have the carrot term. And it that works perfectly when previewed on the views page, but when loading up the actual page I get a listing of ALL the nodes under the "food" term because I have "WHEN THE FILTER VALUE IS NOT IN THE URL --> Display all results for the specified field"

My main problem I think is that "The contextual filter values is provided by the URL." And my terms are not in the url. So somehow I need to pull the terms associated with each node.

Any help would be much appreciated!

Instead of creating a node view create a taxonomy view.

In that provide two relationships:

Taxonomy term: Content with term;
Taxonomy term: Content using {Name of the taxonomy field in the
content type}*;
Add a contextual filter of the type Content : Title;
Use the first relationship for the contextual filter, Make necessary changes in the more option such as change to lower case turn space to dashes etc;
Add the required fields from the content with the relationship set to 2);

You are good to go.

EDIT : As per the discussion There was another need to also show the nodes under a term and its sub terms.

Create a view of the type content;
Add the required fields;
Add a contextual filter of the type Content: Has taxonomy term ID (with depth) and select the depth a value as deep as the hierarchy you have in the taxonomy.

Now when you pass the term id as the input it would show all the nodes under that taxonomy term including the child nodes.

If you wish to change the url to have the term name instead of the term ID Do the following.

In view give the path as taxonomy/term/% this will override the default taxonomy path;
Install Pathauto Module this depends on Tokens module so have to install that as well;
In Configuration -> URL aliases you have a tab called Patters;
Set the pattern of the "TAXONOMY TERM PATHS" to what you would like it to be. Make sure that the last value is [term:name] so if you want the path to be category/carrot you should give it as category/[term:name];
If you have already added the taxonomy terms then you would need to do the "BULK UPDATE" which is again a tab on the URL Alias page.

Now when you visit the page category/termname you will see all the nodes under the term including the child terms.


Selecting a product attribute from a select list won't update other attribute fields I'm working on a store created with Drupal Commerce where I have first created a product variation, then I created a corresponding product display type and finally I created different products, e.g. mattresses.

Now I find myself stuck with this problem: I have mattresses of different size and I have a product attribute (within the product variation) accounting for the different sizes - I have the option "Enable this field to function as an attribute field on Add to Cart forms" already checked.

When I select a size from the select list, the product price changes and displays accordingly but other product attributes, i.e. the sku, displaying on the same page, does not update.

Now, if I move on to the cart summary I can find the right sku, it looks like the price updates without the need for a page reload, while other custom attribute fields don't (you can see all of this live at http://www.dormiplus.it/cms/?q=it/materassi/stella, where "codice" is equivalent to sku).

How can I have the right sku displaying correctly whenever I select a different mattress size?

Why don't you have the clean urls enabled?
I think for the ajax to function, we might require or at least assume clean urls. That may be all the problem is.
The reason your injected fields aren't changing is because of a javascript error, and it is often not related to Drupal Commerce at all, could be a theme issue.


Paid membership plans on registration page I am creating a registration based website that has five membership plans.

Based on the selected membership plan, users have to pay the membership fee using Stripe payments.

How can I create membership plans and this kind of payment functionality?

For membership process you can use the (paid for) Moneyscripts module.

  Membership Suite is the most comprehensive subscription software for
  Drupal on the market and it is designed to seamlessly integrate your
  site with all of the features of a professional Paid Membership
  Subscription site. There is no other software available for Drupal
  that can provide the stability, ease of use, and features that
  Membership Suite offers.


Is it possible to login as / switch to a specific user using their password hash from the DB? I don't particularly want to enable Devel on my production environment to gain the Switch Users block. Is there a way to switch users without any additional php code?

There's Masquerade.

Masquerade adds some items to the Navigation menu to allow quick switching and switching back. It also creates a "Masquerade" block for quick switching which can be added to a sidebar or elsewhere on your site. It is visible only to those users with permission to masquerade.

Another module which accomplishes something similar is Role Switcher.

--a different Dan H


placeholder on searchbox here is my template.php code:

function sizin_preprocess_page(&$variables){
  $search_box = drupal_render(drupal_get_form('search_form'));
  $variables['search_box'] = $search_box;
}

function sizin_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_form') {
      // HTML5 placeholder attribute
      $form['search_form']['#attributes']['placeholder'] = t('Search ...');
  }
}

and in my page.tpl code:

  <?php print $search_box; ?>

but I can't able to see placeholder. Any Idea?

Install Placeholder module. Using this module you can convert any label of any elements of any form in your site in to a placeholder. Just add the CSS style of the form element in to this module configuration and it will do the rest of the jobs

You can also try this

$form['search_form']['#attributes'] = array('placeholder' => 'Search ...');


Rendering multiple comment form issue I have a view page on which I have rendered the comment form for each node in the field using the code below:

  $comment = new stdClass;
  $comment->nid = $n->nid;
  $form = drupal_get_form('comment_form', $comment);
  print render($form);

All my forms are printing fine, but the issue is that when I enter a message on message field and click submit, it redirect me to node page with comment form at browser top and my message is lost. If I type and click save here, my message saves without an issue.

I altered the form, added a custom_submit_handler as follows:

$form['#submit'][] = 'mymodule_custom_submit';

and defined it as:

function sparx_custom_submit($form, &$form_state) {
 if(isset($form_state['custom_redirect_path'])) {
   $form_state['redirect']  = $form_state['custom_redirect_path'];
 }
}

Now the problem I am facing is that each time I try the comment is getting added to the top-most node, not to any other node.

Any suggestions please

Using the following code to print comment helped me to solve this issue:

module_load_include('inc', 'comment', 'comment.pages');
$comment_form = drupal_get_form('comment_node_<content_type>_form', (object) array('nid' => $nid));
print drupal_render($comment_form);


How can I loop through a multivalue field's values? I have two authors for the same blog, so I want to display both authors details on a page. Below code will display only one because $node->field_author[LANGUAGE_NONE][0]['target_id'] contains 0. So next author value will be like this $node->field_author[LANGUAGE_NONE][1]['target_id'] So how can I use foreach loop here to display both author details?

if (isset($node->field_author[LANGUAGE_NONE][0]['target_id']) && is_numeric($node->field_author[LANGUAGE_NONE][0]['target_id'])) {
  $nid = trim($node->field_author[LANGUAGE_NONE][0]['target_id']);
  $nodeauthor = node_load($nid); //$node->type = 'poll';
  if ($nodeauthor) {
    $nodeView = node_view($nodeauthor, 'teaser');
    print drupal_render($nodeView);
  }
}

The solution is:

  foreach($node->field_author[LANGUAGE_NONE] as $key => $value){
    $nid = $value['target_id'];
    //$key is the index 0, 1 ....
  }


Views: sort criteria -> Post date, not start from latest but latest-3 is there a possibility to sort articles by postdate, but exclude the latest 3 and start with number 4 (because the latest 3 are already displayed in another view).

Or even better: is there in general a possibility to exclude articles already displayed on the same page but in another view?

Yes, in the Use Pager options, you can specify an offset, which by default is 0, but can be any number, which, amusingly, in the help section offers:

The number of items to skip. For example, if this field is 3, the first 3 items will be skipped and not displayed.


hook_menu_alter() with node URL alias I have a node with ID equal to 60, which has a URL alias that is "mynodes/about-us." I would like to change the access callback of that node to myfunction().

It doesn't work when I use the URL alias:

function celsis_forms_menu_alter(&$items) {
    $items['mynodes/about-us']['access callback'] = myfunction;
}

function myfunction() {
     return FALSE;
}

But it works when I use the node number:

$items['node/60']['access callback'] = myfunction;

How can I get the url alias to work and would it be possible to change the access callback for all nodes with alias starting with mynodes/*?

You cannot do that because when Drupal invokes hook_menu() and hook_menu_alter() the value contained in $_GET['q'], which is used to find the menu callback to use, has been already changed from the path alias to the normal path.
drupal_path_initialize(), which is called by drupal_bootstrap() contains the following code:

  if (!empty($_GET['q'])) {
    $_GET['q'] = drupal_get_normal_path($_GET['q']);
  }
  else {
    $_GET['q'] = drupal_get_normal_path(variable_get('site_frontpage', 'node'));
  }

What you are trying to achieve can be accomplished in another way: implementing hook_node_access(). Differently from the equivalent hook in Drupal 6, it can be implemented also from modules that don't define a new content type.

function mymodule_node_access($node, $op, $account) {
  if ($op == 'view') {
    $path_alias = request_path();
    // ...
  }
}

$account contains the user object to which is being given access to the node. If the hook returns NODE_ACCESS_ALLOW, then the user has access to the node for the operation passed in $op; if the hook returns NODE_ACCESS_DENY, the user doesn't have access to the node; when it returns NODE_ACCESS_IGNORE, it leaves to other modules the decision.

request_path() returns the path alias if one was used. This means that if the user is using a URL like example.com/node/60, it returns "node/60"; if the user is using
example.com/mynodes/about-us, which is an alias for example.com/node/60, it returns "mynodes/about-us." In the case the user is using example.com/index.php, the function returns an empty string.


How do I modify the login block markup? I want to change the source order of the "Create new account"/"Forgot your password?" links and the Submit button, so the Submit button comes first.

I am able to modify certain contents of the login block by using this function.

function THEMENAME_form_user_login_block_alter(&$form, &$form_state){
  $item = array();
  if (variable_get('user_register', USER_REGISTER_VISITORS_ADMINISTRATIVE_APPROVAL)) {
    $items[] = l(t('Create new account'), 'user/register', array('attributes' => array('title' => t('Create a new user account.'))));
  }
  $items[] = l(t('Request new password'), 'user/password', array('attributes' => array('title' => t('If you forgot your password, click to request a new password via e-mail.'))));
  $form['links']['#markup'] = theme('item_list', array('items' => $items));
}

And this template does pick up the changes and allow for markup changes around the form, but simply outputs the form in one variable. How do I modify the $content variable and print each element out separately to swap item locations?

block--user--login.tpl.php

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

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

<div id="user-login-block" class="block block-<?php print $block->module ?>">
  <div class="content"<?php print $content_attributes; ?>>
    <?php print $content ?>

This example uses straight markup out of Firebug and it does function, but there should be a cleaner way to do this by printing variables that already contain the markup, and that doesn't remove the "Create new account" option if the site registration is restricted.

you can change the weight of the links like this:

$form['links']['#weight'] = 10000;

now it should be after the submit button :)


Creating Primary Sub menu's programmatically I want to display the latest 10 nodes of node type 'ABC' as a sub menu link under my primary menu. Are there any modules for Drupal 6 to help me achieve it.

I have created a view which gives me a latest 10 nodes sorted by creation date. However, I am unable to figure out how to integrate as an submenu links under the primary menu link.

So is there any other way I can achieve this?

You could use the menu views module:

  What Menu Views Does

  Menu Views is a utility module. It provides back
  end support for replacing a standard menu item link with a menu item
  view. Menu items (in any menu) now have the option of toggling between
  two different menu item types: link or view. Depending on which option
  is selected, the appropriate configuration form is displayed on the
  admin side and the appropriate type of item is rendered on the
  front-end.

Once you create a submenu, you can attach a view to it. Your title suggests you're asking to do this programmatically. From what i know, i'm not totally sure if that's possible without a lot of headache.


How does Drupal handle autoloading of classes? How does Drupal handle autoloading of classes through modules? For instance, if I have an Events module, and I declare a class called Event, and then in the .info file I include the class file, how is this registered?

The problem is that I'm trying to dynamically get an array containing all loaded class names. get_declared_classes() does not return the names of all my classes declared in this manner, so I'm assuming that they're autoloaded somehow. Following the suggestions from another stack overflow question, I tried getting all of them with spl_autoload_functions(), but that was also unsuccessful.

Any ideas?

All files listed in .info files are parsed when modules are rebuild (Only changed/new files in that list are, for performance reasons).

That information is then stored in the {registry} and {registry_files} tables. So if you want to get all classes or those according to a given naming pattern, you can query those tables.