How can I shorten Facet API urls programatically? My site uses Search API and Facet API for search.

My user search has several entity references that are also indexed.  So, when just two facets are activated, this gives me a URL like this:

http://www.example.com/search&f1=field_acc_gen%253Afield_location_taxonomize_terms%3A885&f2=field_acc_gen%253Afield_languages%3A50

This is way too long.  What I'd like to do is collapse the field_acc_gen%253Afield_location_taxonomize_terms to co (country) and field_acc_gen%253Afield_languages%3A50 to la (language).

I know that Facet API Pretty Paths can be used to shorten the URLs but because I have about 20 facets, the regex that it uses seems to really kill performance.  I am also thinking about using Search API Page, which does not work with FacetAPI Pretty Paths.  So, I was hoping to find a way to rename the facets themselves in code.

I have my facets exported using the Features module.  I tried changing $facet->name, but this had no affect on the results:

  $facet->name = 'search_api@om_user_search::field_acc_gen:field_language';
  $facet->searcher = 'search_api@om_user_search';
  $facet->realm = '';
  $facet->facet = 'field_acc_gen:field_language';

to:

  $facet->name = 'search_api@om_user_search::la';

How can I programmatically rename a facet?

You want facetapi_alias.

The facets already have a setting "facet alias" internally, which can be different from the facet machine name.
But this setting is not exposed in the UI natively.

The FacetAPI Alias module simply exposes this setting on the facet display form.

If you want more advanced solutions, you could use facetapi pretty paths (as you mentioned), or write your own FacetapiUrlProcessor. I have done the latter, and I can tell you it was painful :)


how to save taxonomy terms in a custom user registration form in D7? I've got an Implementation of hook_form() on a custom page which I use for user registration.

For example I have this field:

function popover_form($form, &$form_state){

    // some other fields are left out here to simplify my question

    $form['second']['education'] = array(
      '#type' => 'radios',
      '#title' => 'Afgeronde opleiding',
      '#options' => popover_get_tax_term_options('education'),
      '#default_value' => variable_get('education', NULL),
      '#required' => TRUE,
    );
    return $form;
}

Then in form_submit() I'm trying to do this:

function popover_form_submit($form, &$form_state){
  $edit = array(

    // some other fields like username, email etc are also left out here.

    // field_firstname is a simple string and works.
    'field_firstname' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['first']['field_firstname']))),
    // education doesn't work ( because it is a taxonomy term ? )
    'education' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['second']['education']))),
  );
  user_save(drupal_anonymous_user(), $edit);
}

so either I need to change my submit handler because taxonomy terms are saved differently or I need to update the standard user edit 'view' ( $sitename/user/1/edit ) so the taxonomy terms become visible? Or I'm doing something else wrong?

EDIT:
I also found out that it is needed to connect taxonomy terms with the user on the admin/config/people/accounts/fields page before you can get this to work.

The column name for a taxonomy term reference is 'tid' rather than 'value', if you just change that your code should work:

$edit = array(
  'field_firstname' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['first']['field_firstname']))),
  'education' => array(LANGUAGE_NONE => array(array('tid' => $form_state['values']['second']['education']))),
);

user_save(drupal_anonymous_user(), $edit);


menu access callback per role I'm trying to implement an access callback per role for a specific menu item, but other roles can view that menu item also. Any tip is welcome.

/**
 * Implements hook_menu();
 */
function MODULENAME_menu() {

  global $user;

  $items['admin/backoffice/production/taxonomie'] = array(
    'title' => 'Taxonomie',
    'type' => MENU_LOCAL_TASK,
    'weight' => 0,
    'page callback' => 'MODULENAME_backoff_taxonomy',
    'access callback' => 'MODULENAME_user_has_role',
    'access arguments' =>  array($user, array('éditeur taxonomie', 'administrator')),
    );

  return $items;
}

function MODULENAME_backoff_taxonomy(){
  module_load_include('inc', 'taxonomy', 'taxonomy.admin');
  $form = drupal_get_form('taxonomy_overview_vocabularies');
  drupal_set_title('Backoffice - Taxonomie');
  return drupal_render($form);
}

function MODULENAME_user_has_role($user,$roles) {
  foreach ($roles as $role) {
    if (in_array($role, $user->roles)) {
      return TRUE;
    }
  }
  return FALSE;
}

To have a single access callback handle a dynamic number of roles which varies per menu link, try something like this in hook_menu()...

// hook_menu()
$items['foo'] = array(
  /* ... */
  'access callback' => 'MODULENAME_user_has_role',
  'access arguments' =>  array('éditeur taxonomie', 'administrator'),
);
$items['bar'] = array(
  /* ... */
  'access callback' => 'MODULENAME_user_has_role',
  'access arguments' =>  array('some other role'),
);

Then your access callback implementation:

function MODULENAME_user_has_role() {
  global $user;
  $roles = func_get_args();
  foreach ($roles as $role) {
    if (in_array($role, $user->roles)) {
      return TRUE;
    }
  }
  return FALSE;
}

That should do it.

Some alternatives

Remove the global $user and access arguments from hook_menu().

Then change your access callback function implementation to this:

function MODULENAME_user_has_role() {
  global $user;
  $roles = array('éditeur taxonomie', 'administrator');
  foreach ($roles as $role) {
    if (in_array($role, $user->roles)) {
      return TRUE;
    }
  }
  return FALSE;
}

Since hook_menu() is invoked only when the menu router is being rebuilt (e.g. a cache clear, typically done by an admin or drush), global $user is not usually very useful from within that function. Instead, an access callback function is invoked at a more appropriate time (i.e. when the page is being viewed, or a menu link is about to be shown [or not] in a menu), at this point it is much easier to make a decision about the current user's context.

To make the access callback more generic, and be able to handle multiple menu link paths, I'll typically use a switch/case on an arg() to further curate the context:

switch (arg(3)) {
  case 'taxonomie':
    // do stuff...
    break;
}


Add custom field to taxonomy terms I am writing a module that creates a vocabulary through code. Here's what I use:

$new_vocab_name = 'my_categories';
$vocab_obj = (object) array(
   'name' => t('My Categories'),
   'machine_name' => $new_vocab_name,
);
taxonomy_vocabulary_save($vocab_obj);

How do I add custom fields for terms that will be in this vocabulary? E.g., I want to add an image field for each term.

I think this article will be usefull for You because taxonomy is one of entity types:
Working programmatically with fields in Drupal 7

So You should set "entity_types" as taxonomy.


URL aliases [node:language] repetition issue I have an issue with URL aliases creation. I have set my configuration as following:

The default path pattern above is the only one configured. Yet, when I create my content type instances and translate them, I get the following:

http://mysite.localhost:8082/en/search-form
http://mysite.localhost:8082/fr/fr/recherche-de-mots
http://mysite.localhost:8082/ab/ab/dfghdf

EN is the default language, but why do I get double /fr/fr and /ab/ab? These are the links created in the language link available under node contents.

REM: Generate automatic URL alias is set on all node content translations.

Update

Of course, I would like to avoid repetitions (this is my real question):

http://mysite.localhost:8082/en/search-form
http://mysite.localhost:8082/fr/recherche-de-mots
http://mysite.localhost:8082/ab/dfghdf

That happens because Drupal is using the language prefix to generate the language URLs, and you are using the [node:language] token in the path pattern. As consequence, the language prefix appears twice.
In the first case, as English is the default language, the prefix doesn't appear twice because [node:language] is replaced from an empty string.

Just use [node:title], instead of [node:language]/[node:title] as path pattern.

The reason for allowing the use of [node:language] is that the other method to generate language URLs is through a domain for a specific language. Suppose you set http://exemple.com has domain for the French language; with your path pattern, the URL alias would be something like http://exemple.com/fr/recherche-de-mots, which is perfectly acceptable.


How can I serve a "410 Gone" HTTP status AND redirect my removed content? I have a load of content that is gone (don't ask). I would like to tell Google and other search engines that this resource is gone, please don't try to index it. This is what HTTP status code 410 looks good for.

This is great for search robots, but if it's a real person accessing the page, I'd rather they were redirected to the new content.

Luckily, all the gone URLs match a pattern.

Is it possible to have all those handled by issueing a 410, and a redirect of some sort?

(I worry that permanent redirects might affect SEO too?)

Put another way: what I want to say is "That content is gone, you should not link to it. There's new content here:..."

[EDIT: to express why this is Drupal related]

Drupal is my CMS. With any generic website I would find my own solution to present a page and the correct header. With Drupal there's usually "a module for that", sometimes an elegant way to solve a common problem, and sometimes a hideously inefficient way to square a circle known as "the Drupal Way" [joke].

Drupal has an in-built system for 404s that works great. You can set a page, and because it's got a url you can use the block module to put other useful stuff on it, e.g. a View.

So there's 2 questions:

Does Drupal (or a reliably contrib'ed module) have a way to issue 410s akin to the 404 system?
Does Drupal have a 302/301 redirect system that can work with path patterns (i.e. separate from node as these dead pages were from another module that has been removed)

You can always output HTTP 410 header and redirect human users using JavaScript in a body:

var delay = 10000; //Your delay in milliseconds
setTimeout(function(){ window.location = URL; }, delay);

JavaScript from this answer.

Note that by rfc2616:

  The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. These status codes are applicable to any request method. User agents SHOULD display any included entity to the user.

Emphasis mine. So, JavaScript outputted inside HTML body should work. But of course it is not guaranteed it will.

Your content is not nodes, so you probably have implemented hook_menu. If not, you can alter existing implementation with hook_menu_alter. What you need is to:

Using access callback and/or access arguments, ensure user gets the access permission to deleted content. If not, he will see 403 or 404, as this is Drupal's default behaviour for unpublished / deleted data.
In page callback test if content is valid, deleted or never existed.

If valid, default to the callback you are using now.
If deleted, use drupal_add_http_header to add "410 gone" header as appropriate. Output nice human readable page (optionally with JavaScript redirect, search box or anything appropriate).
If never existed, either default to what you were using already, or implement 404 the way you implemented 410 above.

Google says:

  We recommend that you always return a 404 (Not found) or a 410 (Gone) response code in response to a request for a non-existing page.


What is the best way to write a cron that deletes a very large number old nodes and comments? I am writing a module the preferably implements a cron job, and possibly a queue, to run sql queries to delete old nodes and their comment. Approximately 20 Million nodes, and about 40 mil comments. I want to run pure mysql queries and bypass the drupal api (as much as I can), for performance reasons. I have already developed the relevant queries and would like to know what would be the best way I could implement this so it does not user Drupal api? This is on drupal 7 by the way.

I would never think running raw SQL queries is a good idea because that can mess up a lot of things such as site maps, search index, caches, etc.

it's just a node_delete() and shouldn't be much slower that deleting a bunch of rows in multiple tables.

Whatever that is, you will need to implement hook_cron and retrive nodes to be deleted from 'node' table.

If you run a node_delete you won't need to delete comments.

You can limit the number of nodes to delete in a single cron run using LIMIT  keyword.

Update:
You might want to have a look at Delete All module. and there is a patch (which I submitted) to use the Batch API to do the job. From my experience I know even the Batch API can't handle it (or you have to wait several days with the browser open).

You can just use hook_cron to load a bunch of nodes to be deleted, and then delete them in your preferred way (node_delete or raw SQL). Let the cron finish, and in the next run, it will grab some other nodes.
Just get your nodes from node table and limit it with a LIMIT.


How to change search index for a view in the Views We made a lot views using Views module type of Search API index#1. Now, we realize that we need to go with another index#2. Is there any way to change indexes in existing Views? Can anyone point me in right direction?

Thank in advance!

I also had this problem after realizing switching indexes also requires changing the view's index. So to accomplish that quickest way I could think of was to change these values from the ‘export’ of the original index being used.

Main lines of original view:

    $view = new view();
    $view->name = 'es_connector';
    $view->description = 'Search box based on elasticsearch (connector)';
    $view->tag = 'default';
    $view->base_table = 'search_api_index_es_connector_index';
    $view->human_name = 'ES Connector';

New search view:

    $view = new view();
    $view->name = 'es_connector_rebuild’; // changed arbitrarily to my new view name
    $view->description = 'Search box based on elasticsearch (connector)';
    $view->tag = 'default';
    $view->base_table = 'search_api_index_es_connector_rebuild’; // changed to work - see below as to how determined
    $view->human_name = 'ES Connector Rebuild’; // changed arbitrarily

To find the name of base table click name of your new index (admin/config/search/search_api/index/) and append search_api_index_ with the machine name. Find and replace any occurance of your new view name.

Then paste all of the export into an import script. This will leave you with a new view based on the new index (with the original search view still available). Then just swap out the new search block for the old one. You also probably need to change the path under page settings of the  view.


Create Node contains Field collection with restws + services I am trying to create a node with RESTFULL api using restws and services modules (latest versions) on Druapl 7 - openpublish destro.
the node contains a Field collection (images field collection field) i was trying to attache the fid returned from the /backbone/rest/files.json [POST] but the field accept nothing

JSON Sample for the field

  "field_op_gallery_image": {

    "und": [

 {
   "value": "3",
   "revision_id": "3"
 },
 {
   "value": "4",
   "revision_id": "4"
 },
 {
   "value": "5",
   "revision_id": "5"
 },
 {
   "value": "6",
   "revision_id": "6"
 },
 {
   "value": "7",
   "revision_id": "7"
 },
 {
   "value": "8",
   "revision_id": "8"
 }

      ]
       },

Can any one help , thanks in advance

This sandbox will implement a field_collection service for services 3.x: https://www.drupal.org/sandbox/graber/2141747


Views Pager Add rel="nofollow to ALL Pager Links In Drupal 7 I am trying to add rel="nofollow" to ALL of the pager links in views. The closest I have got is to add the nofollow to next links, but I want it to include previous pages as well as "First" and "Last".

P.S. We specifically want the rel="nofollow" attribute to all pager links, we are not looking for other solutions (noindex, block with robots.txt, or rel=next/prev).

This is the code I am currently using:

function mytheme_pager_next($variables) {
  $text = $variables['text'];
  $element = $variables['element'];
  $interval = $variables['interval'];
  $parameters = $variables['parameters'];
  global $pager_page_array, $pager_total;
  $output = '';
  // If we are anywhere but the last page
  if ($pager_page_array[$element] < ($pager_total[$element] - 1)) {
    $page_new = pager_load_array($pager_page_array[$element] + $interval, $element, $pager_page_array);
    // If the next page is the last page, mark the link as such.
    if ($page_new[$element] == ($pager_total[$element] - 1)) {
      $output = theme('pager_last', array('text' => $text, 'element' => $element, 'parameters' => $parameters,'attributes'=>array('rel'=&gt;'nofollow')));
    }
    // The next page is not the last page.
    else {
      $output = theme('pager_link', array('text' => $text, 'page_new' => $page_new, 'element' => $element, 'parameters' => $parameters,'attributes'=>array('rel'=>'nofollow')));
    }
  }
  return $output;
}

Not sure of a hook right now for something cleaner. An alternative that will allow you to do what you want,

function hook_views_post_render(&$view, &$output, &$cache) {
    dpm($output);
}

You can use a regex, something like,

(<li.*pager-item.*><a)(.*)

That will give you two groups.
- Group one with every list of items and the opening tag of the anchor.
- Group two with the rest of the line

You can use this to iterate over and add in between both groups,

rel="nofollow"

Of course, you post an answer and find some information. You may want to see if you find these hooks useful, https://drupal.stackexchange.com/a/140867


How to hide flag link if current user and author are same? I need to hide flag link if the logged in user and the author are same.  Please find below codes.

function MODULE-NAME_views_pre_view(&$view, &$display_id, &$args)
{
    global $user;
    if ($view->name == 'VIEW-NAME' && $display_id == 'DISPLAY-ID') {
        $node = node_load(arg(1));
        if($node->uid == $user->uid){
            //echo 'hide flag';
        }else{
            //echo 'show flag';
        }
    }
}

If it is a flag on nodes, you just need to set "Users may only flag content of others" in the Flag access by content authorship paragraph of the FLAG ACCESS options.


Media Gallery not using lightbox and required libraries are in place. What is wrong? I'm trying to make a Gallery utilizing lightbox on my Drupal 7.26 site.
I've picked Media Gallery (7.x-1.0-beta8) and as it says it requires the following compulsory components to work:

Media (1.4)
Multiform (1.0)
ColorBox jQuery plugin

I've extracted a colorbox-master.zip under sites/all/libraries and renamed colorbox-master folder to colorbox. Now the sites/all looks like this.

I also have the colorbox module installed.

The images in the gallery doesn't seem to use any lightbox at all when clicked upon. I've checked a couple of other solutions elsewhere and I think I've gotten all of them covered as you can see on the screenshot above. Nothing else seems to help.

What am I doing wrong?

As Bala Varadarajan suggested. I gave sites/all/libraries/colorbox/ and all its contents full Read/Write permissions.

The lightbox is working now.


Page Caching wrong CSS got a weird issue I was hoping someone could help with.

I have a site that uses multiple subthemes, with different ones being served depending on url var. IE, subsiteone.mysite.com, and subsitetwo.mysite.com get different themes, but the same content.

I am using a module to style each subtheme css via theme settings (https://www.drupal.org/project/style_settings) and am having issues pages caching the wrong stylesheet.

The module setup works fine, rewriting modified css to files/style_settings/subthemeone.css

On initial save, all is fine, and page pulls correct (rewritten)
files/style_settings/subthemeone.css path.
After a while, page caches    (?) and reverts css reference to the
old (unwritten)    sites/all/themes/subthemeone/subthemeone.css

Clearing drupal cache results in the correct (rewritten) reference being called again. Would love to NOT have to resort to disabling caching/etc, so any thoughts appreciated!

EDIT: Using slightly modified code graciously provided below:

style_settings.module

function style_settings_init() {
      setcookie('custom_theme', $GLOBALS['theme'], REQUEST_TIME + 60*60*24*30, ini_get('session.cookie_path'), ini_get('session.cookie_domain'));
}

settings.php

// Check if cookie is set.
if (!empty($_COOKIE['custom_theme'])) {
  // Add theme name to page cache id.
  $_SERVER['REQUEST_URI'] .= '#' . $_COOKIE['custom_theme'];
  // Set Theme.
  $conf['theme_default'] = $_COOKIE['custom_theme'];
  //drupal_set_message($conf['theme_default'], 'status');
}
// Disable page cache if cookie not set so module can set the cookie.
else {
  $conf['cache'] = CACHE_DISABLED;
}

Answer is in here: https://www.drupal.org/node/361832#comment-4204294

You'll need a cookie for the user saying what theme they are using. This is done in a hook_init() call.

  // If no cookie is set, set a cookie with the value of theme_default.
  if (empty($_COOKIE['custom_theme'])) {
    setcookie('custom_theme', $GLOBALS['theme'], REQUEST_TIME + 60*60*24*30, ini_get('session.cookie_path'), ini_get('session.cookie_domain'));
  }

Then you'll need to modify the page cache cid ($_SERVER['REQUEST_URI']) in settings.php

// Check if cookie is set.
if (!empty($_COOKIE['custom_theme'])) {
  // Add theme name to page cache id.
  $_SERVER['REQUEST_URI'] .= '#' . $_COOKIE['custom_theme'];
  // Set Theme.
  $conf['theme_default'] = $_COOKIE['custom_theme'];
}
// Disable page cache if cookie not set so switchtheme can set the cookie.
else {
  $conf['cache'] = CACHE_DISABLED;
}

Code is from D6 but looking it over really quickly it should work for D7.


Subscribe to any order state transition I am trying to create a dynamic event subscription, for drupal8 commerce order state.

My use case is the following.
I want to create an invoice for any order which goes into state e.g. PENDING. There is a custom state/transition yml which i have created.

Which state transition should trigger an invoice creation, i want to make this configurable.

So, the admin should be able to select specific states, in a custom settings form, and the system should only create invoices when an order enters to one of these states.

I need to create an event subscriber, which is dynamic according to the settings that the admin has entered.

In terms of code, in the event subscriber, i have the following code

public static function getSubscribedEvents() {
  $events = ['commerce_order.place.post_transition' =>'onTriggerInvoiceCreation'];
  return $events;
}

public function onTriggerInvoiceCreation(WorkflowTransitionEvent $event) {
  $invoice_creation_states = explode(",", $this->config_factory->get("my_custom_module.settings")->get("invoice_creation_states"));
  $current_state = $event->getToState()->getId();

  if(in_array($current_state, $invoice_creation_states)) {
    //create the invoice
  }
}

So, a far as i understand, i need to do one of the following

In function getSubscribedEvents, i read the my_module.settings from configuration and find a way to construct the correct event subscriber.
So, instead of

$events = ['commerce_order.place.post_transition' =>'onTriggerInvoiceCreation'];

i should do something like the following

$invoice_creation_states = explode(",", $this->config_factory->get("my_custom_module.settings")->get("invoice_creation_states"));
for($i=0;$i<count($invoice_creation_states);$i++{
  $events = ['commerce_order.'.$invoice_creation_states[$i].'.post_transition' =>'onTriggerInvoiceCreation'];

As this function is static, i don't seem to be able to get hold of the config service in order to get the $invoice_creation_states.

So next thought is to create a more generic event listener, for all order state changes, and in the corresponding listener callback e.g. onTriggerInvoiceCreation i could get the custom settings and make the above condition in order to execute or not the invoice creation code.

Question: Is there a more generic transition event than
commerce_order.TRANSITION_ID.TRANSITION_PHASE

something like

commerce_order.ANY_TRANSITION.ANY_PHASE ?

This has recently been implemented in Fire generic events when transition are applied [#2832415].


cannot create taxonomy terms using hook_enable solved! i want to create 1 taxonomy vocabulary and 1 taxonomy term using drupal's hook_enable. but when i enable the custom module, it create only the taxonomy vocabulary. And if i disable and enable the module, the taxonomy term will be created without problem. the code is as below:

 $sql = "SELECT vid FROM {taxonomy_vocabulary} WHERE machine_name='article_type'";

$vid = db_query($sql)->fetchField();
    if (!$vid) {
      drupal_set_message(t("Created article type vocabulary"));
      // No vocabulary exists, we'll create one.
      $vocab = (object) array(
          'name' => 'article type',
          'description' => t('Automatically created by the custom_block module'),
          'machine_name' => 'article_type',
          'multiple' => '0',
          'required' => '0',
          'hierarchy' => '1',
          'relations' => '0',
          'module' => 'custom_block',
      );
      taxonomy_vocabulary_save($vocab);
      $vid = $vocab->vid

}

  $terms = (object) array (
          'name' => 'News',
          'vid' => $vid,
          'vocabulary_machine_name' => 'article_type',);

 $term_name = $terms -> name;

  $tid = db_query("SELECT tid FROM {taxonomy_term_data} WHERE vid = :vid and name = :name", array(
    ':vid' => $vid,
    ':name' => $term_name,
  ))->fetchField();

if ($vid && !$tid) {

    taxonomy_term_save($terms);
}

}

PS:i've figured it out! it's a stupid mistake. i did not get the vid after saving the vocabulary to the database. i just need to add $vid = $vocab->vid after taxonomy_term_save.

$vid remains FALSE throughout the entire first run. You need to set it after the vocabulary object is saved:

...
taxonomy_vocabulary_save($vocab);
// Add this next line
$vid = $vocab->vid;


Where do I declare a global variable? I need to define a global variable. Where should I define it?

I will not use the global variable in template files
I should not use settings.php
I will only use the global variable in all the custom module files

Personally, I would either write module that abstracts away the need for a global variable, or at least has a getter function for retrieving it.  Something like

function foo_get_the_service ()
{
  static $service;

  if (! isset($service)) {
    $service = foo_init_the_service();
  }

  return $service;
}

Several Drupal API functions do something similar (eg, menu_get_active_trail() and menu_set_active_trail());

And then preferably, your module would also have helper functions so you don't need to access the global directly.  If something really does need the global, then you would use the getter.

If your global is an instance of a proper PHP class, then you could look into using a real singleton.


How to create Ubercart recurring order with initial $0.00 charge Is there any way to configure (or trick) Ubercart (7.x-3.4) into accepting an order with initial 0 charge, then subsequently charge non-zero amount?

Goal is to offer a promotion with $0.00 initial charge, then start charging after n-number months or days.

When 0 is set as the cost of the recurring product, Ubercart responds with an erroneous error about no payment method being set up.

If you look at ubercart subscription it offers the ability to create a subscription product with an initial trial period of x days/months and then the amount to charge per day/month following the trial period.


Template file is not overriding drupal 7 defaults Why node--type.tpl.php is not working? I've cleared drupal cache 100 times no results. Is there something else i must to do?

Overriding node templates are done by placing node--'nodetype'.tpl.php templates inside your custom theme folder.
If the template isn't accepted after cache clear, check if the Machine name on admin/structure/types is the same as 'nodetype'.


Recover content from a deleted user and assign ownership to other user There is a user that needs to be deleted but I need to keep his content. I want to know if there's a way to transfer the ownership of all of his content (nodes, userpoints, etc.) to another user? I tried views bulk operations, but there is no option there.

I know that I can delete the user and keep the content and give it to the Drupal anonymous user, but it´s possible to set up an specific user?

Transferring ownership of nodes is a part of Drupal core's functionality. Outside of that, any other contrib module has to provide that functionality itself; Drupal core doesn't have a concept data ownership for contrib module data.

I've rarely seen a contrib module implement a data ownership transfer feature. For popular modules they might exist but it's not a given. For example, with userpoints there submodule called userpoints_donations in the User Points Contributed modules project. However, it covers the use case of one user giving to another, not transfership from an account set to expire.

You might be able to do this on a per module basis if you look at the data tables each module stores in its .install file. It would be pretty easy to look at each table for a uid column and perform a SQL UPDATE statement that changes any uid value from X to Y. If you know all the modules in question (with their respective data tables), it's quite feasible to build your own custom VBO operation that would automatically do the SQL queries for you.


Show "Add more items" for fields of limited cardinality? Is there a way to modify the behavior of a field that has limited input to do the 'add more items' button instead of show X fields on the screen?

For instance, I have added a link field, that can have up to 5 link values. When it is displayed on the form, it shows 5 empty link fields, instead of one with the option to add more. This display is cumbersome, and makes users believe they must fill all of the fields in, and conversely, become unsure how to 'remove' a link since clearing the field value is less intuitive than clicking 'Remove' that some other fields have.

For UX/training purposes, I would like for fields on forms to behave consistently for limited or unlimited. Has anyone accomplished this behavior using the Form API?

You can do this in a form alter:

     YOURMODULE_form_alter(&$form, &$form_state, $form_id) {

        if ($form_id == 'YOURFORM') {
           if (isset($form['YOURFILED']['und']['#max_delta']) && $form['YOURFIELD']['und']['#max_delta'] == 4) {
                $form['YOURFIELD']['und']['add_more']['#prefix'] = '
';
                $form['YOURFIELD']['und']['add_more']['#suffix'] = '
';
            }
}

The max delta should be one less than you want as the maximum. When the delta is 4, then after five addmore fields, the add more button will be hidden.


linking multiple node types to each other I have 2 node types, complaints and solutions.
Every node type has multiple fields.

How can I link multiple solutions to a complaint?
And the other way around, how can I link a solution to multiple complaints?

-Complaint1 -> Solution1, Solution2, Solution3

-Solution 1 is linked to Complaint1, Complaint2, Complaint3

With entity reference I can only link one on one relations.
The relations module seemed promising, but it seems it's only for admin users.

Okay, I haven't test this out, but I think this should work:

You first need  a way to generate a taxonomy term for each Complaint node. I think that the NAT could help with that or through Rules.
Next, add a term reference field for Solutions, enable multiple selections but disable the ability to create terms.
Override the term reference view for that particular vocabulary through a custom url using Pathauto, this would be the "Complaint1 -> Solution1, Solution2, Solution3" part
For "Solution 1 is linked to Complaint1, Complaint2, Complaint3", you already have links to the taxonomy term simply by displaying the field in your node. You could also do this through views.

Done! Hope it works!


Is it possible to get Views data in the views-view.html.twig file? I see this template just uses

{{ rows }}

Is it possible to get values from the views fields in this file?


Sync user roles across websites I am using Drupal 7. I want to sync my Drupal website roles on 2 websites on the same top level domain, as in, one is example.com, the other is other.example.com, how can i achieve this? Bakery module does not seem to share user roles, and i want to avoid sharing databases across my sites since it works but not recommended.

Basically, i want to reduce loading time on my main site and push my payment system (which contains many modules) to a new Drupal install so that when the payment is made on the slave site, the user role is updated on the slave site which is in turn captured on the main site. How can i achieve this?

i cannot provide detailed steps to achieve this but there are various alternatives Comparison of Single Sign On (SSO) Modules to the bakery module you mentioned that are capable of sharing users. although you might want to just create those roles via a feature, depending on what you mean by

  sync my drupal website roles.

Services
i18n_sso
Domainaccess
CAS
account_sync
simplesamlphp_auth
shib_auth
Omniauth https://drupal.org/node/2177681
Oauth Connector
Bakery 3.x current development effort suggest it might soon support exporting roles in 3.x if you are a developer you can look there. i believe issue 556666 was committed to 2.x already aswell


Extend the webform submission I am building a online purchasing system, and I use a Webform to gather clients' personal information.

A problem rises when I want to append some external data (which is not important enough to be included as a field in my registration form) to the webform before the submission.

What should I do? (I used hook_webform_submission_presave(), but it seems to me that it can only be used to change data, not adding additional data.)

Here's my presave hook; it works, but it's not serving my purpose.

function hook_webform_submission_presave($node, &$submission) {
  // Update some component's value before it is saved.
  if ($node->nid == 0) {
      $component_id = 1;
      $submission->data[$component_id]['value'][0] = 'foo';
  }
}

You can't create a new value to non-existing field, since the data has no place to save to the database. Ideally you should create a hidden field for your data and modify it in your handler on presave event or use hook_ENTITY_TYPE_presave. If you have multiple values to add, serialize it or save into JSON and assign to the hidden value.

You can also use Computed token field where you can define and place your custom token (with any dynamic data) into value of that computed field which can fetch and store the data dynamically.

Related: Is there a webform way to store additional data on a submit handler?


get images URL in a twig template I have two content types, the first is Homepage and the second is SLider.
The Slider content type has multiple fields like title, ink, and image.
In the homepage content type, I have an entity reference field referring to the slider content type with multiple selections. I've created a template in my custom theme as node--home-page.html and want to get the sliders fields values, All is okay with me except the image. I cannot get the image URL.
My code:-

{% for slide in node.field_hoeme_slideshows %}
        {{ kint(slide.entity.field_home_slide_cta.uri) }} {# This is working #}
        {{ kint(slide.entity.title.value) }} {# This is working #}
        {{ kint(slide.entity.field_home_slide_snippet.value) }} {# This is working #}
        {{ kint(slide.entity.field_home_slide_image) }} {# ****** This is not working *****#}
{% endfor %}

As an alternative configuration using Field Collections. Instead of using two content types and a field reference...

{% for item in content.field_slide %}

{{ item.getFieldCollectionItem().field_h2.0.value }}

{{ item.getFieldCollectionItem().field_p.0.value }}

{% endfor %}

This is off the top of my head so double check the code.

Then you just create a field collection field on the home page content type called slide. Go to field collections, select "slide" and add the fields: link, slide_image, h2, and p.


How to use Basic Cart module? I have installed and activated basic cart module.
then I went to admin/config/basic-cart
their I selected my content type.
Then in view I added a field content:Add to cart
When I viewed my view result their I wasn't able to see button for add to cart.
How to use that module so that it show me that button
Basic Cart
I an using Drupal 7

Make sure your field output has the correct format in the view - select the 'Add to cart button' in the field formatter.


Rule running after node update shows previous content Using Drupal 7.15. I wrote a rule containing custom PHP code that POSTs the node ID to an external system. That system accesses the Drupal REST server, retrieves the specified node, and copies its content.

Problem: It gets the version that existed before the current save command. The action specifically says that it is run "After updating existing content" so I can't understand why I consistently get the previous version.

0 ms Reacting on event After updating existing content.
15.618 ms Evaluating conditions of rule TEST rule on save content. [edit]
15.652 ms AND evaluated to TRUE.
    0 ms Rule TEST rule on save content fires.
    0.265 ms Evaluating the action entity_save. [edit]
    1.155 ms Saved node of type node.
        0 ms Reacting on event After updating existing content.
        0.393 ms Not evaluating reaction rule TEST rule on save content to prevent recursion. [edit]
        0.412 ms Finished reacting on event After updating existing content.
    26.716 ms Evaluating the action php_eval. [edit]
    1944.527 ms Rule TEST rule on save content has fired.
1960.253 ms Finished reacting on event After updating existing content.

Similar problem, but for user instead of node: Rules - After updating / saving user not working

Discussion on drupal.org: http://drupal.org/node/430274  I have tried the fixes suggested in replies #13, 14 on that page, with no success.

Update: I added a separate action on to run entity_save, and set its weight at 0. The original rule's weight is 5 so it should run after the force save is complete.  Same result, and it takes twice as long now.

0 ms Reacting on event After updating existing content.
16.051 ms Evaluating conditions of rule Force save after update. [edit]
16.083 ms AND evaluated to TRUE.
    0 ms Rule Force save after update fires.
    0.29 ms Evaluating the action entity_save. [edit]
    2.513 ms Saved node of type node.
        0 ms Reacting on event After updating existing content.
        0.386 ms Not evaluating reaction rule Force save after update to prevent recursion. [edit]
        0.431 ms Evaluating conditions of rule TEST rule on save content. [edit]
        0.448 ms AND evaluated to TRUE.
            0 ms Rule TEST rule on save content fires.
            0.161 ms Evaluating the action php_eval. [edit]
            1954.427 ms Rule TEST rule on save content has fired.
        1954.943 ms Finished reacting on event After updating existing content.
    1984.676 ms Rule Force save after update has fired.
2000.878 ms Evaluating conditions of rule TEST rule on save content. [edit]
2000.902 ms AND evaluated to TRUE.
    0 ms Rule TEST rule on save content fires.
    0.199 ms Evaluating the action php_eval. [edit]
    2422.949 ms Rule TEST rule on save content has fired.
4423.939 ms Finished reacting on event After updating existing content.

you can use

entity_get_controller('node')->resetCache(array($node->nid));

Working for me!!


How can I use the administration theme for the user/%/edit page? How can I get the user/%/edit page to use the admin theme that is used for the rest of the site?

That path is already one that will use the admin theme if the current user has the correct permissions to access it.

Try going to http://mysite.com/admin/people/permissions and checking the "View the administration theme" permission for the roles you wish to be able to use the admin theme.

It'll definitely work as the User module implements hook_admin_paths() to define that path as an admin page:

function user_admin_paths() {
  $paths = array(
    'user/*/cancel' => TRUE,
    'user/*/edit' => TRUE,
    'user/*/edit/*' => TRUE,
  );
  return $paths;
}


Associating nodes to a user I'm trying to create a Parish website. I have a list of parish members with email ids and without email ids. I've imported the users with email addresses as users, and the rest as nodes. Members that belongs to same family shares a common family code, and when a user log in I want to have a view of all family members and their necessary details (i.e. address,phone no,etc).

But the problem I have is that some users are created using user import and some (people without email) are created as nodes.

So how can I display all the members with same family code in a single view? How to relate a user with another user/nodes.

Is it with contextual filters/relationships? I tried with it but couldn't get it.

Firstly you must make all users users and not nodes. Somebody I know recently had an issue where users didn't have email addresses. His solution was to create fake email ids for those users since having an email id is mandatory for an account on a Drupal site.
Once you have everyone as users, I think you can add relationships between users using this module - User Relationships and hence easily show related users in views.


Select option values loaded with AJAX call, shows error illegal choice has been detected I have a select field in my form named country. on change country i need to load values in state. I already placed the field for listing state, only want to load the values from ajax. In same way I need to add city field also. whenever I submit form it shows state (field loaded by ajax) is ' An illegal choice has been detected. Please contact the site administrator'. How can I update the new option values of field state which I have loaded from ajax call to the drupal form. How to clear the particular field cache data?
i will provide a code sample soon .

$('#edit-field-p-location-value').change(function(){
        form_build_id = $('input[name=form_build_id]').val();
        locationval = $(this).val();
        var url = window.location.href;
        var arr = url.split("/");
        var result = arr[0] + "//" + arr[2];
        if(locationval!= ''){
            $.ajax({
                type : 'POST',
                url: result+"/gasf/getIPSecZone/"+locationval,
                data:{datacenter:locationval},
                success : function(data){
                    //$('#edit-field-p-ipseczone-value-wrapper').html(data);
                    $('#edit-field-p-ipseczone-value').html(data);
                }
            });
        }
    });

You need to use the in-build Drupal AJAX functions rather than writing your own. The Examples for Developers module has detailed examples you can copy.


Editing field twig template for taxonomy term I would like to edit field.html.twig for taxonomy-term.html.twig. I've tried field--taxonomy-term.html.twig and a bunch of other options, none of them seem to work. What is the correct naming convention?

Clarification: I mean the template for fields used on the taxonomy term page, not the fields used in content type to reference a taxonomy.

The field type for taxonomy terms is entity-reference. You can use the field type for the naming of the field twig:

field--entity-reference.html.twig

Because there may be more than one reference field, it is more specific to use the field name, for example a twig for the preinstalled tags field:

field--field-tags.html.twig

If you want to use the target entity of a reference field as theme suggestion you would have implement this in a hook.

Edit acc. to the clarification:

If the field is inside of a taxonomy term, you have to add one more detail, either the field name or the name of the vocabulary:

field--taxonomy-term--field-body.html.twig
field--taxonomy-term--tags.html.twig


Allow editing of own content but not show 'node settings' block Hello all and happy new year! ..

I have a question that I thought would have been answered before, but could not find anything..

I want users of a certain role to be able to edit their own content (nodes of a specific content type).  This all works well.  However, they can also see the 'Node Settings' option, which is a block on the right hand side with settings such as: 'CSS class(es), layout box' etc.  (see picture below)

I don't want the above settings to be available to the particular role, although that role would have the right to edit the node - in other words, I want them to be able to alter content, but not be able to mess around with css classes, layout boxes and anything like that ...

Ideally, I would like that whole 'Node Settings' block to be available only to administrators, and not to users of any role - even if they do have permissions to edit the content of that particular node.

I looked carefully into permissions and searched the web, but could not find anything ... My feeling is that this should be done as it must be quite a frequent case ..

Any help would be greatly appreciated.

I think that this is quite easy using hook_form_FORM_ID_alter like this,

function MY_MODULE_form_node_form_alter(&$form, &$form_state, $form_id) {
  $current_user = \Drupal::currentUser();
  $roles = $current_user->getRoles();
  if (in_array('YOUR_ROLE', $roles)) {
    unset($form['...']);
  }
}

if you don't know what the name of the element is called, try to find it using kint($node) if you have devel installed.

Hope it works for you.


How to display translated options for list(text) fields with field_view_field()? I have set up a list(text) field with translated content.

In display admin interface (admin/structure/types/manage/***/display), I have set up it to "Default translated" in "format" column. Then if I display the node, the options are well translated.

But when I try to load this field programmatically, I have always the main language displayed (instead the translation).

Here is the way I proceed.

$specialisations = field_view_field('node', $node_object, 'field_sp_cialisations_liste', array('type' => 'i18n_list_default','label' => 'hidden'));

render($specialisations)

You can pass $langcode parameter in field_view_field function


Drupal 7 Webform Components Related To Individual Nodes I am attempting to create a decision making "questionnaire" in Drupal 7. I am currently using the Webform module to create the questionnaire.

The questionnaire (webform) will create a list of related nodes based on the users submission. What I need is a way to relate the nodes to the webform components.

For example, if a user selects 'Coffee Shop' & 'Sandwiches' on one of the multiple choice questions, all nodes relating to 'Coffee Shops' & 'Sandwiches' will be added to the list.

Is there an available module that will allow me to relate webform components to nodes or would I some how incorporate taxonomies into this for the relationships?

Would EntityForm be a better module for this type of thing?

I'm not sure what UX you want, but with Fieldgroups webforms can be multi-paged. As of webform 4.x Conditional Fields (on the same page, or across pages) is supported by webform. You can have hidden fields already in webform if you need a simple storage mechanism not seen by users ...

I imagine you could then use webform rules and upon final submission of the webform to examine whatever values have been submitted and use a custom rule to populate an available list of NIDs based on the submitted criteria.

You could maybe use Entity List and nodequeues to solve this:

if component is selected on submission use Entity List X, which references a smart nodequeue to nodes of a certain content type ... etc.


Altering the view mode of rendered entities in a View Context via Ctools Plugin I don't even know if what I want to do is possible, so bear with me. My set-up:

I have a View Context that accepts an author UID argument from the Panel context, and then displays content created by that author UID. This View Context has been added to the user/%user system Panel in Page Manager. This allows me to create a custom CTools Plugin that takes that View Context, gives it an additional parameter (content type) to filter by, and spit out the final view programmatically.

The purpose of this is to create many small reusable lists of content in different content types that a specific user has authored, with custom more links and other mark-up around those lists. (I.e., we might show 3 of each content type on a profile page, and if they have created more than three, we link to a different user/%user/this-content-type page that has the full list of that type and a proper pager.) The custom header/footer/more links, the ability to insert additional custom copy or code between lists of nodes, and manual ordering of content types are the main reasons why I'm not simply using Views' default grouping function.

The relevant View rendering code in the CTools Plugin is something like this:

function custom_list_render($subtype, &$conf, $args, $context = NULL) {
  $block = new stdClass();

  if ($conf['type']) {
    $view = views_content_context_get_view($context[0]);
    $view_output = views_content_context_get_output($context[0]);
    $plugin = $view->style_plugin;
    $rows = array();

    foreach ($view_output['view']->result as $row_index => $row) {
      if (custom_content_type_match_function($row, $conf)) {
        $rows[] = $view_output['rows'][$row_index];
      }
    }

    $output = theme($plugin->theme_functions(),
      array(
        'view' => $view,
        'options' => $plugin->options,
        'rows' => $rows,
      )
    );

  $block->content = $output;
  return $block;
}

This code works. There's some additional admin form work going on that selects and saves the $conf['type'] for each iteration of this plugin that you add to a panel.

Right now, the view output is spit out as rendered entities in a custom view mode. I'm wondering if it's possible to alter the View Context at the plugin level so that when you add this plugin to a panel, you can also select which custom view mode you want the rendered entities to render as. (Think Teaser vs Full vs Block.) If so, at what point do I need to disrupt the view (I imagine before views_content_context_get_view?) in order to pass it the new view mode, and how?

Alternatively, could I somehow pass an additional custom argument to the view (e.g. "ctools_view_mode" or something) and then use hooks_view_pre_render to change the view_mode?

Thanks in advance!

Running: Most recent iterations of D7, Panels, Views.

I think you can bypass Views and get what you want with a content type plugin that does a query for the nids you are interested in, then passing that array to drupal_load_multiple(), then passing the result of that call to drupal_view_multiple().

drupal_view_multiple can take whatever view mode you want as a parameter, and will return a render array that you can just throw at whatever custom extra theming you need to do before displaying it.


Trying AJAX autocheckboxes example; getting Notice: Undefined index: #ajax in ajax_form_callback() I'm using the exact code found within the examples module function ajax_example_autocheckboxes though I have changed the function and callback names. When I change the select dropdown the field goes gray for a second as the AJAX process kicks off; but no checkboxes appear. I don't think it matters, but my form is in a block defined in my custom module.

I'm getting this in my recent log messages:

Type    php
Date    Wednesday, March 21, 2012 - 12:24
User    me
Location    http://localhost.com/system/ajax
Referrer    http://localhost.com/node
Message Notice: Undefined index: #ajax in ajax_form_callback() (line 379 of C:\Users\me\Documents\www\localhost.com\includes\ajax.inc).
Severity    notice
Hostname    127.0.0.1

UPDATE: I tried the examples module (ajax examples) in a clean D7 install and get 503 errors trying to open the example pages; now I'm investigating my hosting environment (xampp) will update once resolved.

UPDATE2: Installed a bitnami drupal stack & tested ajax examples; everything works as expected which points to an issue with my xampp environment.

FYI xampp details:

    ###### ApacheFriends XAMPP version 1.7.7 ######

  + Apache 2.2.21
  + MySQL 5.5.16 (Community Server)
  + PHP 5.3.8 (VC9 X86 32bit thread safe) + PEAR
  + XAMPP Control Panel Version 2.5 from www.nat32.com
  + (BETA) XAMPP Control Panel Version 3.0.2 by Steffen Strueber (not in the USB & lite version)
    see http://www.apachefriends.org/f/viewtopic.php?f=16&t=46743
  + XAMPP Security
  + OpenSSL 1.0.0e
  + phpMyAdmin 3.4.5
  + ADOdb 5.14
  + Mercury Mail Transport System v4.62 (not in the USB & lite version)
  + FileZilla FTP Server 0.9.39 (not in the USB & lite version)
  + Webalizer 2.23-04 (not in the USB & lite version)
  + Perl 5.10.1 (not in the USB & lite version)
  + Mod_perl 2.0.4 (not in the USB & lite version)
  + Tomcat 7.0.21 (not in the USB & lite version)

Reinstall XAMPP! if that doesn't fix it, try a different stack:

Bitnami
Acquia
MAMP

So installing the Bitnami Drupal stack and testing successfully there indicated a problem with my XAMPP install. Also wanted to try the Acquia stack, was ok, ended up going back to XAMPP.


Why doesn't watchdog() run when I execute my custom module from Drush? I have a custom module that performs an import from an XML file. It can be invoked in two different ways: from a menu callback or a custom Drush command.
The import works fine and all of its watchdog() calls work fine when I execute it from the menu callback, but when it's executed from Drush, the import works, but no watchdog() entries are logged.
Why is this? How can I get watchdog() to work in this module when it's triggered from Drush?

This is working for me, using the latest Drush dev-master:

drush @dev ev 'watchdog("system", "test watchdog message.");'

What I am doing here is just calling the 'watchdog' function directly with the php-eval command, after bootstrapping a dev site.  This should produce the same results as a watchdog function called from a module, and in fact I see the message logged in the Drupal admin/reports/dblog page.

Drush does install a watchdog handler, so that it can log the watchdog messages to the console in addition to the dblog page; however, many of these messages are ignored by Drush as uninteresting.  To see the full range of watchdog messages that Drush sees, set the --watchdog flag to 'print':

drush @dev --watchdog=print ev 'watchdog("system", "another watchdog message.");'

You should see this message printed in the console, and it should also appear in the dblog page.

I'm not sure why you are not seeing anything in your dblog page, but you might try upgrading Drush (if you're running an old version), and try some of these commands and see what results you get.  This should give you some indication of where the problem is, at least.

UPDATE:

It seems impossible that the Drush hook should be called, but that nothing should be added to the dblog.  The watchdog function in core does nothing but call hooks:

https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/watchdog/7

The actual database write happens in function dblog_watchdog(), which is in dblog.module.  It invariantly writes the entry to the database.

The only guess I have at this point in time is that perhaps you have multisite set up, and Drush is targeting the wrong site or database when you call your menu hook via a drush command.  drush status might help determine if this is the case. Next step would be to put a breakpoint on dblog_watchdog(), or add some sort of print statement there and see what happens when you run your function from Drush.


How do I know whether drupal_write_record has done an insert or an update? I use the function to insert or update records in a table, but sometimes I would like to know whether the function has executed an update or an insert. In my scenario I always provide the primary key:

drupal_write_record('mytable',$entry,'key');

The function inserts a record if $entry['key'] does not exists and updates the record with the new information otherwise.

Is there somewhere I can check to see what the function has done ?

Turns out that in order to know if the operation was an UPDATE or an INSERT you need to know whether the record existed or not before committing the transaction. This is not what drupal_write_record() does. This function just checks it's arguments and issues an update or an insert accordingly. So there is really no way to tell if the function did an INSERT or an UPDATE.

The solution is using db_merge() query, it is a relatively new SQL ANSI standard that does exactly what I needed (and in the case of MySQL does it in an atomic transaction).

$return_value = db_merge('mytable')
            ->key(array('id' => $key))
            ->fields($fields)
            ->updateFields(array(
                'updatedon' => $now,
            ))
            ->execute();

The return value is an integer returning 1 for inserts and 2 for updates.


Forgot password REST services_token I have picked up some work on a headless Drupal 7 site, using services, and service_token.

Where the "normal" service login, as I understand it, uses a cookie to authenticate, Services Token allows authentication by passing a token as the username in a basic auth header.

All appears to work well. But I have been asked to implement "Forgot password", and I am struggling to understand how that flow fits with Services Token.

Any guidance most appreciated.

It's already built into the Services module, just enable its corresponding resource then do a POST ?q=[my-endpoint]/user/request_new_password.json and send along a name, e.g.: name=john or an e-mail address: name=john@example.com


Problem with Jquery in Durpal 7 I am using Drupal 7 and bootstrap theme, I also have installed jquery update module,

Now I have created a js (jquery) file and saved it under js folder in bootstrap theme, I tried to call my js file in the info file using script[] = '...', the console then suggested  that '$ is not a function', which means my js file was called before jquery was called.

Then I decided to call the my js file from template.php:

function bootstrap_preprocess_html(&$variables) {
  $options = array(
    'group' => JS_THEME,
  );
  drupal_add_js(drupal_get_path('theme', 'bootstrap'). 'js/product_pages.js', $options);
}

then the following line showed up in the console:

GET http://localhost/Brompton/sites/all/themes/bootstrapjs/product_pages.js?mpprnf 404 (Not Found)

I am confused, how exactly can I get jquery work properly here?

Technically you've got two Problems. The first one is namespacing, like Molot pointet out. To use $ for jQuery you need at least to wrap your code into this construct:

(function ($) {
  $('body').fancystuff();
})(jQuery);

That's enough for getting your code executed, for the drupal way you need to attach a behaviour to the Drupal object like the tutorial in Molot's link shows.

The second problem is a missing slash in your drupal_add_js:

drupal_get_path('theme', 'bootstrap') . '/' .'js/product_pages.js'


Modifying a single menu link title I'd like to replace the link title on the top link of my secondary navbar (called "explorer", links to "mysite.net/explorer", but actually just triggers a dropdown-menu) with a glyphicon and the current user's name.

According to this thread, a title callback is the way to do this. However, adding this code in my template.php has no effect at all.

function mythemename_menu_alter(&$items) {
  $items['explorer']['title callback'] = 'mythemename_title_callback';
}

function mythemename_title_callback($arg1, $arg2) {
  global $user;
  $title = ''. $user->name;

  return $title;
}

What am i doing wrong? And why does the callback function take 2 parameters? (It doesn't work with 1 or 0 params.)

The "menu token" module almost crashed my site after installation, so I don't want to use that.

If you only want to change the title of an menu item, you should be able to do this through the administration. Go to admin/structure/menu and edit the correct item in your secondary menu.

To use hook_menu_alter() you must add it in a custom module not inside your template file. Remember to clear you cache in order for the changes to take effect. To clear the cache you can goto admin/config/development/performance.


Multilingual Taxonomy Views - Entity Translation I am trying to create a multilingual taxonomy view using Entity translation.  So far, I am stuck displaying an English view even when using a language code.

I'm looking for the steps needed for this. At the simplest, I am trying to create blocks or pages of taxonomy terms based on language.

Any suggestions?

Use the Internationalizations Views module, which extends the i18n module with multilingual support for views.

Also, to make view results correspond to the language switcher, add a filter for Content Translation: User's Current Language, which is the language that an authenticated user has set in the user settings (it is NOT the same as the current browser language or the site language).

If no option for the User's Current Language is available in the filter criteria form, then verify your configuration at Configuration -> Languages -> detection and selection: The order should be URL, Default, User and not something like Default, URL, User (as mentioned also in https://www.drupal.org/node/1701854#comment-6279474).

The above may turn out to NOT be the complete answer. Since you use the Entity Translation module, this option isn't there if you use it in 'entity' mode: if only some fields of the node are translatable the option is there but a bit more difficult to find. If you have the 'Body' of your nodes set to translatable entity then the option is "Body language" to be set to Current User Language.

Note: The Internationalizations Views module only has a DEV version for D7, but right now there are over 31K users using this version. Therefor I think "DEV" is not a valid release qualifier for that version anymore, because +31K users can't be wrong, right?


How to write a Drupal 7 query with "count" and "having" properties? I am unable to make the following query work in drupal7 standards..Can anyone help me with this? Its little urgent...

SELECT n.nid AS nid, n.title AS title, count(n.title) AS ncount
FROM node n
INNER JOIN taxonomy_index tn ON n.nid = tn.nid
WHERE (n.type = 'test')
AND (tn.tid IN( 23,37))
AND (n.title LIKE '%name%')
AND (n.status = 1)
GROUP BY n.nid
HAVING ncount = 2

This is off the top of my head so use caution...

$query = db_select('node', 'n')
  ->fields('n', array('nid', 'title'))
  ->condition('n.type', 'test')
  ->condition('tn.tid', array(23, 37))
  ->condition('n.title', '%' . db_like('name') . '%', 'LIKE')
  ->condition('n.status', 1)
  ->groupBy('n.nid');

// Add the COUNT expression
$query->addExpression('COUNT(n.title)', 'ncount');

// Add the HAVING condition
$query->havingCondition('ncount', 2);

// Add the JOIN
$query->join('taxonomy_index', 'tn', 'n.nid = tn.nid');

$results = $query->execute();


How to add tabs to a form without a module I want to add horizontal tabs (not vertical tabs as shown in examples) as shown on the site : http://www.nseindia.com/ (Get Quotes on the top). I tried using menu modules like superfish and nice menu's it didn't solve my purpose.

I want to add this form with tabs via code and this is what I'm using for adding form to my block:

/**
 * Create the form.
 */
function getQuotes_search_block_form($form, &$form_state) {
  $form['keys'] = array(
    '#type' => 'textfield',
    '#title' => 'Get Quotes',
    '#default_value' => t('Enter Script name/Code /ID'),
    '#size' => 35,
    '#maxlength'=> 255,
    '#attributes' => array(
         'onblur' => "if (this.value == '') {this.value = 'Enter Script name/Code /ID'}",
         'onfocus' => "if (this.value == 'Enter Script name/Code /ID') {this.value = ''}",
         ),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Search',
    '#states' => array(
         'visible' => array(
            'input[name="keys"]' => array('filled' => TRUE),
          ),
    ),
  );
  return $form;
}

/**
 * Create the form submit handler.
 */
function getQuotes_search_block_form_submit($form, &$form_state) {
  $id = $form_state['values']['keys'];
  if ($id && $id != 'Enter Script name/Code /ID') {
    drupal_set_message(t('The form has been submitted'));
    drupal_goto('custom/node/search/' . $form_state['values']['keys']);
  }
}

/**
 * Create the search results menu callback.
 */
function mymodule_menu() {
  $items['custom/node/search/%'] = array(
    'page callback' => 'mymodule_do_search',
    'page arguments' => array(3),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Create the search results callback function.
 */
function getQuotes_do_search($keys) {
  // set the page title
  drupal_set_title('FAQ search results');
  // get the search results
  $results = module_invoke('node', 'search_execute', $keys . " type:faq");
  return theme('search_results', array('results' => $results));
}

/**
 * Create the search form block.
 */
function getQuotes_block_info() {
  $blocks['faq_search'] = array(
    'info' => t('FAQ Search Block'),
    'cache' => DRUPAL_NO_CACHE,
  );
  return $blocks;
}

function getQuotes_block_view($delta = '') {
  $block = array();
  switch ($delta) {
    case 'faq_search':
      $block['title'] = 'Custom FAQ Search';
      $block['content'] = drupal_render(drupal_get_form('getQuotes_search_block_form'));
      break;
  }
  return $block;
}

How do I add the horizontal tabs?

You don't say what you want in the other tabs but if you want tabbed blocks I would recommend using the quicktabs module.

It will allow you to create a quicktabs block that contains your custom block as one tab, and any other block/view/node in other tabs.

It will be far easier than making it custom.
It is a very widely used and stable module.


Views - using "admin/" in path gets me to the home page I'm having an issue with the Views module.
Let me say in advance that the site urls have been customized with the module "rename admin path" and the path to the administration section is www.site.com/gestione/ , using www.site.com/admin/ will get me a "page not found" error. I thought this was something worth telling.
I want to make a view which as an administration layout and i have been told this can be achieved but using "admin/" ("gestione/" in my case) inside the path. So i put /gestione/my-archive as URL.

Now if i try to access the page i see the administration home page instead of the view. If i don't put any prefix (so that the url is www.site.com/my-archive) it works, but it has the normal front end layout, i have tried:

"gestione/content/my-archive" brings me to the content section of the administration menu
Any variation like "gestione/test/my-archive" still gets me to the administration home (likewise "gestione/content/test/my-archive" brings me to the content section)
Giving no access restriction
Anything that doesn't start with "gestione" will get me to the view but with front end layout
using "admin/" will give me a page not found error
Rebuilding the menu calling menu_rebuild();
Deleting the caches

EDIT: disabling the "rename admin path" and using /admin/my-archive did the job, but i wonder if there's any way to keep it working

Configure the view to have /admin/my-archive as the URL and then access it via /gestione/my-archive. Rename Admin Paths works using hook_url_inbound_alter() and hook_url_outbound_alter() which means that internally the path is still admin/*.


Place tag before input text field in search-block-form I would like to add an li tag infront of the input field in the search-block.
Should be possible with hook_form_alter. I've already printed the array containing the search-block-form, but I couldn't find input type text to add a prefix value.

function myTheme_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'search_block_form') {
     print_r($form); -> no input type text here to add prefix to.
   }
}

The "input" type you are referring to, is actually the element defined inside the array $form['search_block_form'],  of #type 'textfield'. That's the element that provides the input field when rendered.

In order to add a <li> tag in front and back of this input field, try using the properties   #prefix and #suffix. Also I would suggest creating a custom module for this, avoid using it inside the template.php file. Try the following (haven't tested it myself, though).

function myModule_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'search_block_form') {
     $form['search_block_form']['#prefix'] = '<li>';
     $form['search_block_form']['#suffix'] = '</li>';
   }
}


Something I can't understand in Acquia Marina theme I have downloaded the Acquia Marina theme yesterday.

I cannot understand well the following code; there is a lot of code like the following, in page.tpl.php.

<?php print theme('grid_block', $search_box, 'search-box'); ?>
<?php print theme('grid_block', theme('links', $secondary_links), 'secondary-menu'); ?>
<?php print theme('grid_block', $primary_links_tree, 'primary-menu'); ?>
<?php print theme('grid_block', $tabs, 'content-tabs'); ?>
<?php print theme('grid_block', $footer_message, 'footer-message-text'); ?>
..............

Acquia Marina theme version is 6.x-3.1. I didn't find a template.php file between its files. Where is the variable declared? Why doesn't the code use $primary_links_tree directly?

The Acquia Marina theme is a sub-theme of Fusion core. $primary_links_tree is defined in the template file of that theme, in the fusion_core_preprocess_page(), which the preprocess function that is called before page.tpl.php is used to output a page. Starting from line 80, you find the following code:

$vars['primary_links_tree'] = '';
if ($vars['primary_links']) {
  if (theme_get_setting('primary_menu_dropdown') == 1) {
    // Check for menu internationalization
    if (module_exists('i18nmenu')) {
      $vars['primary_links_tree'] = i18nmenu_translated_tree(variable_get('menu_primary_links_source', 'primary-links'));
    }
    else {
      $vars['primary_links_tree'] = menu_tree(variable_get('menu_primary_links_source', 'primary-links'));
    }
    $vars['primary_links_tree'] = preg_replace('/<ul class="menu/i', '<ul class="menu sf-menu', $vars['primary_links_tree'], 1);
  }
  // ...
}


Could not open input file: drush I have a relatively fresh instance of Ubuntu 16.04 running a Drupal 7 site, with php5.6 installed instead of php7.  The drupal site runs well.  I am trying to get drush installed so that I can easily do updates.

I have done the global install per http://docs.drush.org/en/8.x/install/

Specifically, as the ubuntu user (no root login)

wget http://files.drush.org/drush.phar

/usr/bin/php5.6 drush.phar core-status

PHP configuration      :  /etc/php/5.6/cli/php.ini
 PHP OS                 :  Linux
 Drush script           :  /home/ubuntu/drush.phar
 Drush version          :  8.1.12
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :

chmod +x drush.phar

sudo mv drush.phar /usr/bin/drush

/usr/bin/php5.6 drush --version

Could not open input file: drush

What am I missing?

The only way I have found to fix this problem is to change the default php used by the server. In other words, /usr/bin/php was originally a symlink to /usr/bin/php7.1, and changing it to a symlink to /usr/bin/php5.6 solved the problem.

But it appears that drush will always use the default php even if you install it with an alternative.


Show / Hide administration menu (module) Is it possible to use a javascript function for a link in Drupal?
I would like to make an option to show/hide the administration menu when clicked on the Drupal icon.
Something simple like this:

  $links['icon'] = array(
    '#title' => theme('admin_menu_icon'),
    '#attributes' => array('class' => array('admin-menu-icon')),
    '#href' => 'javascript: alert("ok")',
    '#options' => array(
      'html' => TRUE,
    ),

Very simple... Just found it myself :)

'#attributes' => array('onmousedown' => array('alert("ok")')),


Different attribute selection widget in a view I have a product display that lists multiple products with various pack sizes.
I added a taxonomy field to a Product for the attribute
e.g.
T shirt 1 pack
T shirt 3 pack

I have set the product display to list the pack sizes as a radio list for selection. Easy enough, in Configure Taxonomy Field I just set the "Enable this field to function as an attribute field on Add to Cart forms." and set the attribute selection widget to Radio buttons.

I would also like to show all the product displays in a view, also easy however, I would like the add to cart form in the view to display the pack sizes as a Select list.

T Shirt > dropdown 1 & 3 pack
Trousers > dropdown 1 & 3 pack

Any suggestions how I can achieve this?

Since the field definition isn't context sensitive (i.e. it can't have one value on a standalone page and another on a View for that setting), you're going to have to do this yourself via a form alter. Just be mindful that the options array for radio buttons / select lists are treated differently with respect to sanitization when formatted for display.


Drupal custom node type add field to relate content I was wondering if it's possible to create a custom node type with a custom field to relate it to another node content(same or diferent node type). And then in my node--customtype.tpl display the fields(render($content['myfield'])) of the custom node type but also to display all the fields of the related node and I want to do it programmatically.

I've been searching, and I found a module called References, but there's no documentation about how to use it exactly.

The other option that I thought is to add a int field to fill with the nid  of the related content, but I don't know if it's possible to generate a query with that nid and append it to the $content['extrafield'] and render it on my node--customtype.tpl

But here you are the experts and I hope you can guide me with the correct way to do it.

I found the answer, there's a module named Entity references, this allows you to add and Entity Field in your custom node type, and with this you can relate to another contents. To use it you just need to add the field, select what do you want to point to, an that's all. To render the entity field and it's fields you need to add to you tpl something this:

<?php print render($content['field_myentityfield'][0]['node'][62]['fieldof_entityfield']['#items'][0]['value']); ?>

You can check it with devel.


How can I detect when a node is changed from 'Published' to 'Unpublished'? In hook_node_update(), I can easily tell the 'status' of a node (whether it's published or not) after it's been updated.

However, is there an easy way to check to see if the updated node was published, but now is not? (Or vice-versa)?

I think Rules might have some condition for 'node value has changed' or something along those lines, but I'd like to do this programmatically.

I found this issue by fago (developer of Rules) on drupal.org that seems to deal with this in Drupal 7, but a nice explanation would be appreciated.

Nevermind. After reading through the issue linked above (especially comment #38), I found that the $node object (any entity, actually) stores the 'original' cached copy in $entity->original.

So, I wanted to detect whether a node changed from 'status = 1' to 'status = 0' (this happens when the node is unpublished), and the following code does this:

<?php
function custom_node_update($node) {
  if ($node->type == 'article') {
    // Act on the unpublishing of an article.
    if ($node->original->status == 1 && $node->status == 0) {
      // Do something here.
    }
    // Act on the publishing of an article.
    if ($node->original->status == 0 && $node->status == 1) {
      // Do something here.
    }
  }
}
?>


Recommendations for security testing a Drupal site? I'm about to relaunch my company's website using Drupal 7. I'm the sole web engineer in our IT department, so I have a lot on my plate as we approach the launch date. As this is my first major Drupal site, I want to be certain that it is as secure as possible. I have completed as many proactive security measures as possible, including following the secure configuration and the best security practices guides on drupal.org, I've subscribed to the security newsgroup, and hardened the LAMP server using industry best practices.

Now that I have completed due diligence with regards to proactive security, I want to run a security audit before we go live to be able to generate a report stating we are "as secure as possible" for management. I usually do all of the testing by hand, page-by-page, using the OWASP Web App testing cheatsheet; however, I'm new to Drupal, this site is hundreds of pages, and I have limited time.

What are your recommendations for security testing a Drupal site of this size? I have access to Rapid7's Nexpose Enterprise, so I will be using that for some automated testing. I do not want to use hosted scanning tools, but will consider security-audited tools that I can install myself to use. Do you have security checklists you go by, similar to OWASP, but specific to Drupal 7? Any other advice for things I might have missed are also appreciated!

Here's some slides on automated security reviews using Drupal tools
Here are some manual steps for a review
You can try to improve password strength
And to make all passwords stronger, Two Factor Authentication is helpful
Security Review is a good call
As is Paranoia
And Cracking Drupal is a good resource (disclosure, I wrote it)


Trouble making dynamics links I have two dynamic links that I want to put in a block, e.g. http://example.com/series/bomberman-jetters/node/add/gallery/82 ("series" is the content type, and "bomberman jetters" is the node title), http://example.com/series/bomberman-jetters/node/add/reivew/82 ("82" is the node ID).

I want to change the URL depending on what node is being viewed. Like if it's viewing node 99 then the links in the block should be changed to http://example.com/series/bomberman-jetters/node/add/gallery/99.

So what I did is insert <?php
print "Add album";
?> but it doesn't work in Drupal 7. The link is correct but it doesn't lead you to creating the node.

Your link code worked for me when I tried it on a random page so it's hard to tell what could be wrong from the information you provided. Generally a better way for creating links in code would be the l function:

<?php print l(t('Add album'), 'node/add/review/' . arg(1)); ?>

Drupal will handle the use of admin overlay automatically if it's enabled. Another thing I noticed is that adding arg(1) for nid at the end of node creation pages serves no purpose generally. If it's used by a module or custom code for something then it's a different story though.


How to access and edit files from admin panel? How i can acces my files without going to host control panel or by ftp. I mean if any module is for that to access and edit files from Admin panel.

Try elfinder File Manager module, which also allows inline text file editing, besides other file managing operations.


Drush misidentifies my D7 site as drupal 8 I'm using Drush Commandline Tool 9.2.1 in a Drupal 7 webroot and I'm unable to run it.
$ drush -vvv cc all
 [preflight] Config paths: /home/user/.composer/vendor/drush/drush/drush.yml
 [preflight] Alias paths:
 [preflight] Commandfile search paths:
             /home/user/.composer/vendor/drush/drush/src
 [bootstrap] Bootstrap to max [0.14 sec, 11.2 MB]
 [debug] Trying to bootstrap as far as we can [0.14 sec, 11.21 MB]
 [error]  `cache-clear all` is deprecated for Drupal 8 and later.
          Please use the `cache-rebuild` command instead.

Seems to suggest that it thinks the site is D8 but it's a D7 site.
$ drush list
(...commands listed as normal...)
! [NOTE] Drupal root not found. Pass --root or a @siteAlias in order to
see Drupal-specific commands.

Says it can't identify the root. I'm in it! And my settings file is fine at the normal location of sites/default/settings.php
Even passing --root and -l options does not help - I still get the same errors.
Never had this before. Any ideas?
EDIT
Here's why I didn't think this was a silly question:

Source: http://docs.drush.org/en/7.x/install/ at 23 Mar 2018.

I'm using Drush Commandline Tool 9.2.1 in a Drupal 7

Drush 9 only works with Drupal 8.4+

As seen on: http://docs.drush.org/en/master/install/

Uninstall Drush 9

composer global remove drush/drush

and install Drush 8

composer global require drush/drush:8.x


Create a bundle programmatically? I've been trying to figure out this problem of allowing the user to dynamically create project request forms (add his own fields including drop downs, multiselects, etc...). The user needs a way to create multiple project request types (bundles, perhaps?), for different business units. I figured the entity / bundle relationship would be perfect for this. So here is my idea:

Use the Schema API to define my base table "project". Use the Entity API hook_entity_info() to tell Drupal about my new entity, pointing it to the "project" table. Now in this hook I can define bundles - which is great. But I need for the user to be able to create a bundle. Where is the entity_create_bundle($entity_type, $bundle) call?

Example:

Entity TYPE: Project (with common fields defined in DB, and it is fieldable)

Bundle: IT Project, HR Project - which share the common fields from Project

A project_type table will store additional grouping I need (project requests for business units).

Now I've been reading Drupal 7 Module Development which has been great, and in chapter 6 they define an entity "artwork" that has a couple of bundles, "sculpture" and "painting". The way they describe the steps, is as if they are building an admin interface to create additional artwork types, but this is not true (from what I can tell). After finishing the chapter, I can only create entities of type "painting" or "sculpture".

How can I allow users to create bundles of the "project" entity type?

Am I missing something or is the functionality not there [yet]?

Examining the default Node bundles

The Node module does not create the "Article" and "Basic page" Bundles itself.  After some digging I found the definitions for these bundles in the standard install profile's install file.

/profiles/standard/standard.install

  // Insert default pre-defined node types into the database. For a complete
  // list of available node type attributes, refer to the node type API
  // documentation at: http://api.drupal.org/api/HEAD/function/hook_node_info.
  $types = array(
    array(
      'type' => 'page',
      'name' => st('Basic page'),
      'base' => 'node_content',
      'description' => st("Use basic pages for your static content, such as an 'About us' page."),
      'custom' => 1,
      'modified' => 1,
      'locked' => 0,
    ),
    array(
      'type' => 'article',
      'name' => st('Article'),
      'base' => 'node_content',
      'description' => st('Use articles for time-sensitive content like news, press releases or blog posts.'),
      'custom' => 1,
      'modified' => 1,
      'locked' => 0,
    ),
  );

  foreach ($types as $type) {
    $type = node_type_set_defaults($type);
    node_type_save($type);
    node_add_body_field($type);
  }

  // clear the site cache

A few notes about this code

It doesn't use Entity API
st() function should only be used during a Drupal installation process
Node contains a lot of non Field API fields that it handles in node_type_save
Node calls field_attach_create_bundle to tell Field modules about the new bundle

Creating a bundle with the Entity API

I'm not sure how you've defined your entities, but if you've used Entity API then your bundle-creation code might look something like this:

$bundle = new stdClass();
$bundle->type = 'project_hr';
$bundle->label = t('HR Project');
$bundle->is_new = true;
$bundle->description = t("A super cool project");

$controller = new ProjectTypeController('project_type'); //assuming you defined this extension of EntityAPIController
$controller->save($bundle);

A note about Entities

An entity type is an abstract base class
A bundle is an extended entity type class
A field is a class member, property, variable or field instance
An entity is an object or instance of a base or extended class

More about entities


Custom autocomplete field I am trying to create an autocomplete field for users.  The following code is fine for username searches but the requirement is for a search by any part of the user's first and last name.

$form['user'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'user',
  '#selection_settings' => [
    'include_anonymous' => FALSE,
  ],
];

I am wondering what the best way to filter by first and last name is.  Is it even possible to use 'entity_autocomplete'?  It doesn't look like any of the EntityAutocomplete class methods would make this possible and I'm not clear on whether or not the '#selection_handler' and '#selection_settings' properties could be helpful.

The selection_handler element property allows to specify a plugin id of a class that would override the default selection handler for EntityAutocompleteMatcher. A separate plugin would be able to build a different Entity Query.

Create a plugin of EntityReferenceSelection type. This should be a derivative of the DefaultSelection plugin similar to TermSelection.

Then you can override entityQueryAlter to add additional conditions to the entity query.


Count of the number of nodes tagged with a particular status I have a content type called promise whose node can be tagged with a status: not started, in progress, achieved, broken.

I wish to show a count for each of the above statuses in a view block. So say there are 100 promises, I want it to show the following.

90 of 100 promises are not started
2 of 100 promises are in progress
3 of 100 promises are achieved
5 of 100 promises are broken

How can I go about this? I know how to count a taxonomy term and show it has 2, 3 or 18 nodes tagged against it, but how to show out of 100?

To do this without code, I think you'd need a view for each category and then in the footer or header, choose "Global: Results summary" and build your message there using the tokens. I saw you post about colours elsewhere so if you have a separate block for each, you can then theme each one as you wish.

If you set the view to "Display All Items" and then add css .viewname .view-content {display:none;} or a custom module to hide the results, it should work nicely.

You could then use some caching to minimize the performance hit.


Problems to integrate a form into a block So far, the form is rendered in the block, but the following errors are displayed:

  Notice: Undefined index: ios_lang_checkbox_nameform_function in
  drupal_retrieve_form()

  Warning: call_user_func_array() expects parameter 1 to be a valid
  callback, function 'ios_lang_checkbox_nameform_function' not found or
  invalid function name in drupal_retrieve_form()

<?php

function ios_lang_checkbox_block_info() {
  return array(
    'ios_lang_checkbox' => array(
      'info' => t('Ios Like language switcher'),
      'description' => t('Ios Like language switcher')
    )
  );
}
function ios_lang_checkbox_block_view($delta='')
{
    $block['content'] = drupal_get_form('ios_lang_checkbox_nameform');

  switch($delta) {
    case 'ios_lang_checkbox':
      $block['subject'] = null; // Most forms don't have a subject
      $block['content'] = drupal_get_form('ios_lang_checkbox_nameform_function');
      break;
   }
   return $block;
 }

function ios_lang_checkbox_menu() {
    $items['ios_lang_checkbox'] = array(
        'title' => 'View the sample form',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('ios_lang_checkbox_nameform'),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM
    );
    return $items;
}

/**
 * Define a form.
 */
function ios_lang_checkbox_nameform($form, &$form_state) {

    $options = array(
        'de' => t('de'),
        );
    $form['ios'] = array(
        '#title' => t('Your Name'),
        '#type' => 'checkboxes',
        '#description' => t('Choose language'),
        '#options' => $options,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit')
    );
    return $form;
}

?>

Thanks a lot!

You've got _function on the end of ios_lang_checkbox_nameform_function...just change that line to:

$block['content'] = drupal_get_form('ios_lang_checkbox_nameform');.

The string passed to drupal_get_form() needs to be exactly the same as the function name itself, no need to put _function on the end :)


Altering menu local task title I'm trying to override the title of a system provided local task. I have the following code which works for uid 1 but not authenticated users:

function test_controller_menu_local_tasks_alter(&$data, $router_item, $root_path) {
  if ($root_path == 'user/%') {
    foreach($data['tabs'][0]['output'] as $key => $item) {
      if ($item['#link']['path'] == 'user/%/edit') {
        $data['tabs'][0]['output'][$key]['#link']['title'] = t('Password and email address');
      }
    }
  }
}

According to this issue this is expected behaviour for the time being. Is there another way round this?

i have an idea if you use string override module .this module provide the override  the local task menu.

http://drupal.org/project/stringoverrides/


theme individual block I looked over the theme suggestion but when tried with dummy text, the block doesn't show any dummy text.

on view source, it showed "id=block-menu-menu-top-menu-navigation"

Tried naming block--top-menu-navigation.tpl.php and block--menu-menu-top-menu-navigation.tpl.php but dummy text still doesn't show up.

Perhaps my naming the files is wrong?

The template file you have to create should be

block--menu--menu-top-menu-navigation.tpl.php

Hope that helps.


Problem translation of terms menu - Drupal 8.5.1 - Distribution VarBase how are they?
I have a problem with the menu item translation. when i make click in button translate i have a issue i attach image.

I am using Drupal 8.5.1 and the distribution VarBase 8.x-4.16.

Error: After the click, we see the following error.

El sitio web encontró un error inesperado. Vuelva a intentarlo más tarde.InvalidArgumentException: Field content_translation_source is unknown. in Drupal\Core\Entity\ContentEntityBase->getTranslatedField() (line 580 of core/lib/Drupal/Core/Entity/ContentEntityBase.php). Drupal\Core\Entity\ContentEntityBase->get('content_translation_source') (Line: 44)
Drupal\content_translation\ContentTranslationMetadataWrapper->getSource() (Line: 120)
Drupal\content_translation\Controller\ContentTranslationController->Drupal\content_translation\Controller{closure}('es')
array_filter(Array, Object) (Line: 122)
Drupal\content_translation\Controller\ContentTranslationController->overview(Object, 'menu_link_content')
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() (Line: 582)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() (Line: 151)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 68)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 664)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

I hope favorable answers!!
As always thank you very much

I solved it, going to admin/config/regional/content-language and check the box in Custom menu link and solve the problem.


How can I customize a menu to be intuitive for my users: show user name, have dropdown items I am looking to create a user menu. The menu when not logged in should have two options: 1. create account 2. sign in. These items will be displayed in-line.

Once logged in, I want the menu to have two options: 1. account name 2. sign out

When logged in the "account name" menu item will have a drop down with menu items linking to the various user tabs present in the user backend.

Information: I am working with a theme I downloaded. The main menu has a fairly extensive dropdown function but I do not know how it is doing it. If I could figure that out then I could apply that to the user menu for the function I want.

The reason I want this done: I had a potential customer loose interest and leave my site because he could not figure out where he could download his files from. So I figured I needed to create a easy to understand user menu.

Thanks for your help!

Drupal 7
link to my website: sonikloops.com

This can be easily done with the available following contributed modules.

Create menus from Admin UI, and restrict the visibility by Menu Per Role module. Here, you might like to to show the menus Create Account and Sign In only to anonymous (not logged in) users.
You can use the Menu Token module, if you wish to show username as menu. You'll need to install the Token module and the Ctools module in order to do this. This can be done in following way:

Create a menu link in your User menu using Admin UI by visiting http://yoursite.url/admin/structure/menu/manage/user-menu.

In the link title you input the user name. The following will replace the [current-user:name] with the username of the logged in user. You can even use other fields, under the "Menu Token Options" > "Replacement Patterns".

The output of the above:

As admin:

As an authenticated user:

For the dropdown feature of the menu, you can use the DHTML Menu or the Superfish menu.

Hope that helps. Please feel free to ask questions.


Content type aware in sidebar template I've added some image and link content to region-sidebar.tpl.php before it executes the print $content. All good, except now the client wants the images and links specific to content type. (I can't do it all in CSS, otherwise i'd go that route).

How can I test for content type in region-sidebar.tpl.php or have a variable that is set. The region-sidebar.tpl.php doesn't see a variable defined in preprocess_node.

In region-sidebar.tpl.php I need something like:

<?php if ($content):
  if ($mycontent_type == "foo") {
       ?> < add some html stuff here> <?php
  }
  print $content; ?>

You can get the current node like this:

if ($node = menu_get_object()) {
  if ($node->type == 'foo') {
    ...
  }

But don't put that logic directly in a template file - move it out to a preprocess function instead.


How to programmatically set the color scheme for a theme? Is there a way to programmatically change the color scheme, set by the color module, for a certain theme in Drupal 6 (in PHP or using drush)? For example, I can change Garland's color scheme from the UI:

but I want to do it programatically.

No - this is not possible in 6.x due to how color is intended to work. Its meant to be a simple way to change a very basic theme, not for advanced users. In 6.x, when you change your color settings, it is doing the following:

Replaces hexidecimal colour values in CSS files
Creates sliced images with the new colours for use as CSS background images
Copies unchanged images without alterations

This creates a dump of 'color files' that looks like this in your files directory (for the Garland theme)

bg-bar-white.png
bg-bar.png
bg-content-left.png
bg-content-right.png
...
style.css

It also creates a random number for the folder each time, so the folder is getting deleted and recreated each time you save the changes.

All of this is to make it easier for novice users to change their colors, with I assume the understanding that if users could configure their own CSS and theme in code, they wouldn't be using the color module to begin with. This approach is also confirmed here on D.O by Jeff Burnz

  Currently there is no way in Drupal core to export your custom color
  scheme to file, i.e. no way to capture the configuration

Conversely, there is no way to import an existing dump of colors files into your site.


Use image scale and crop in custom function In Drupal 7, I'm trying to use image_scale_and_crop() to take an image from an external URL and resize it.  Then I want to print it out to my page.  Here is my code:

$filename = $bjt_img;
$img_url = "http://www.mydomain.com/uploads/".$filename;
$myimg = image_load($img_url);
$myimg_scaled = image_scale_and_crop($myimg, 100, 80);

print '<img src="'.$myimg_scaled.'">'

I'm getting the message:

  Recoverable fatal error: Argument 1 passed to image_scale_and_crop()
  must be an instance of stdClass, boolean given, called in...

How exactly is the image returned with image_scale_and_crop()?

You problem is image_load($img_url) is returning FALSE, which is not an object.

$filename = $bjt_img;
$img_url = "http://www.mydomain.com/uploads/".$filename;
if (isset($myimg = image_load($img_url)) {
  $myimg_scaled = image_scale_and_crop($myimg, 100, 80);
  print '<img src="'.$myimg_scaled.'">'
}
else {
  print 'error'
}

Plus I think it must be a file,  not a url to a file