How to change a views block ID attribute to use it as anchor I have a views block with id=block-views-block-services-block-1 which I used in the menu link.

The menu link is now shown as https://example.com/gb/#block-views-block-services-block-1

As you can see it's really not looking nice with long hyphend words. Is there any easy way to change it to something like this https://example.com/gb/#services

I read an answer for Drupal 7 where we need to edit template.php to change the ID. But in Drupal 8 it seems that template.php is replaced with twig.html. I'm not very sure as I'm new to Drupal.

Could anyone please explain few steps on how to do it?

you should place this function in your themes/YOURTHEME/YOURTHEME.theme file:

function YOURTHEME_preprocess_block(&$variables) {
  dump($variables);
}

and you will see the name of your block. You have to look for block_html_id. Based on your description the value of the block_html_id will be block-views-block-services-block-1.

Then you can simply owerdefine it this way:

function YOURTHEME_preprocess_block(&$variables) {
  if ($variables['block_html_id'] == "block-views-block-services-block-1") {
    $variables['block_html_id'] = "services";
  }
}

Or you can create a custom module and you can put this function there too. In that case you have to replace the YOURTHEME to the name of the custom module.


All Contents related to a content list Say a user has a list of  2 favorite books , one with taxonomy term "adventure" and one with taxonomy term "art". (n favorite books, related with m taxonomy terms)

How to automatically display a list of all books with taxonomy term "adventure" or "art" (or m taxonomy terms)

The steps could be :

step 1 : build the list of the user's favorites books (views, flag,
filter : this is OK)
step 2 : get the list of all taxonomy terms referenced by theses nodes,
step 3 : get the list of all books referencing one or several of the taxonomy terms listed at step 2

My question is how to build a view which do these 3 steps.

Thanks

You can use views , build a view of content type book , then filter them based on taxonomy term , you even can expose the filter and let it to user to decide which genres want to view .


Can't run drush core-cli I have installed drush on crunchbang linux and while most of the drush commands are working, I can't get core-cli to work.  Typing drush @dev core-cli produces:

  The drush command 'core-cli' could not be found.  Run[error] drush
  cache-clear drush to clear the commandfile cache if you have
  installed new extensions.

I initially tried installing drush via apt-get, but when core-cli didn't work I tried getting it via pear, but it's doing the same thing.  With the version I got from pear - which is 5.8 - the command drush self-update works, where it didn't in the apt-get version, which was an earlier release.

I've made sure that my user has full rights to the /usr/share/php/drush folder.

Please let me know if you have any suggestions on getting core-cli to work on crunchbang (debian).

drush core-cli has been removed in Drush 5

  Drush 5 supports bash completion which is much more native and
  superior to the old core-cli command, which has been removed.

More information: Core-cli command removed in favor of Bash completion


Views link image to field I've created a view with two fields(field_img & field_pdf) and the Format as Fields.

Now I want to download the field_pdf file when I click on the field_img.

How to achieve this one?

Thank you.

You may be able to use "Rewrite the output of this field" to wrap the image in a link using the "replacement pattern" token for the PDF file url as the href there.

Note you can "Exclude field from display" to add a field to the token list without displaying it.

You'll also need to drag the field, in the field order, above the one you want to use it in as a token for it to be available.

hth


How to make form buttons call only javascript? I'm experimenting with JavaScript and Drupal forms. Currently I'm trying to make a button in the administration form of a module that will use JavaScript to append options to a select list. The problem I'm running into is that when I click the button, my JavaScript gets called but the whole form refresh. I've looked at the Forms API reference thinking there was some kind of attribute I can set on the button to stop it from but found nothing. Is there any way I can stop the button from refreshing the page or is this a dead end?

$form['#attached']['js'] = array(
  drupal_get_path('module', 'test').'/js/test.js',
);

$form['list'] = array(
  '#type' => 'select',
  '#options' => array(),
  '#attributes' => array(
    'name' => 'sellist',
  ),
  '#size' => 4,
);

$form['add_button'] = array(
  '#type' => 'button',
  '#value' => 'Add',
  '#attributes' => array(
    'onclick' => "add_to_list(this.form.sellist, 'Append' + this.form.sellist.length);",
  ),
);

//JavaScript
function add_to_list(list, text) {
  try {
    list.add(new Option(text, list.length), null) //add new option to end of "sample"
  }
  catch(e) {
    list.add(new Option(text, list.length));
  }
}

My final code:

<?php
function jstest_menu() {
  $items['admin/config/content/jstest'] = array(
    'title' => 'JavaScript Test',
      'description' => 'Configuration for Administration Test',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('_jstest_form'),
      'access arguments' => array('access administration pages'),
      'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function _jstest_form($form, &$form_state) {
  $form['list'] = array(
    '#type' => 'select',
    '#options' => array(),
    '#size' => 4,
  );

  $form['text'] = array(
    '#type' => 'textfield',
  );

  $form['add_button'] = array (
    '#type' => 'button',
    '#value' => t("Add"),
    '#after_build' => array('_jstest_after_build'),
  );
  return $form;
}

function _jstest_after_build($form, &$form_state) {
  drupal_add_js(drupal_get_path('module', 'jstest').'/js/jstest.js');
  return $form;
}

JavaScript
(function ($) {
  Drupal.behaviors.snmpModule = {
    attach: function (context, settings) {
      $('#edit-add-button', context).click(function () {
        var list = document.getElementById('edit-list');
        var text = document.getElementById('edit-text');

        if (text.value != '')
        {
          try {
            list.add(new Option(text.value, list.length), null);
          }
          catch(e) {
            list.add(new Option(text.value, list.length));
          }

          text.value = '';
        }

        return false;
      });
      $('#edit-list', context).click(function () {
        var list = document.getElementById('edit-list');

        if (list.selectedIndex != -1)
          list.remove(list.selectedIndex);

        return false;
      });
    }
  };
}(jQuery));

the form button definition below works for me, the #after_build is useful for loading in javascript that can attach the click handler.

$form['add_button'] = array (
  '#type' => 'button',
  '#attributes' => array('onclick' => 'return (false);'),
  '#value' => t("Add"),
);

$form['#after_build'] = array('[module_name]_after_build');

Then my javascript that is loaded in a separate file by the after build function, looks something like:

Drupal.behaviors.[module_name] = function(context) {
  $('#edit-add-button').click(function() {
   ...Do something here
  });
};


How to check if a node has a photo/video to use as an exposed filter in views? I am interested in creating an exposed filter with the following values:

Has photo
Has video
Has both photo and video

So this filter will check nodes and show only those with photos, if this filter is selected etc.

How can i do this? Should I create a new field on the content type and populate this according to having image/video?

Any ideas?

thanks

You should be able to add the photo field or fields as filters and set their criteria to "not empty". Then, only those records with a photo should be visible. The same applies for the video field.


Fatal error: Call to a member function advanced_render() on a non-object What I am doing wrong? The error says:

  Fatal error: Call to a member function advanced_render() on a
  non-object in
  /var/www/mydrupalsite/themes/myTheme/template.php
  on line XXXX

/**
 * Overrides theme_views_view_field for a view
 *
 */
function myTheme_views_view_field($view, $field, $row) {
  //Work only for mobile view and section field
  if($view->name == 'mobile' && $field->options['label'] == 'Section') {
    $new_items = array();

    foreach($field->items as $skey => $subitem) {
      $new_items[$skey] = array();

      foreach($subitem as $key => $item) {
        $parent = taxonomy_get_parents($key);
        if(count($parent) == 0){
      //do not set item in items, if taxonomy does not have parent
        }
       else {
         $new_items[$skey][$key] = $item;
       }
      }
    }
  //Assign new items list to field items
    $field->items = $new_items;

    return $field->advanced_render($row);
  } else {
    return $field->advanced_render($row);
  }
}

I think you may have copied that code somewhat from a Drupal 6 version? The only problem is that the pattern for theme function signatures has changed in Drupal 7; only the $vars argument is passed in now, which is an array of named variables for the function:

function myTheme_views_view_field($vars) {
  $view = $vars['view'];
  $field = $vars['field'];
  $row = $vars['row'];

  // ...
}


How to configure mysql database connection with a different socket I have a Drupal 6 site that I ran for years before walking away about three years ago. I would like to resurrect the site in a more modern CMS and am first considering Drupal 8.

I run my site on a shared server where I have my own mysql socket. In Drupal 6, I connected to the database successfully in settings.php through the following syntax:

ini_set('mysqli.default_socket', '/path/to/my/mysql/socket');
ini_set('mysql.default_socket', '/path/to/my/mysql/socket');
$db_url = 'mysqli://dbuser:dbpass@localhost/dbname';

Looking at Drupal 8's settings.php it's a completely different syntax, and I am stumped on how to configure it correctly either there or on the Database configuration screen during install.php. Googling things like "drupal 8 mysql socket" brings up old articles that aren't relevant anymore.

PHP 7.0 is provided and I don't have write access to the ini, so I can't override the socket there.

I have confirmed that the database is running with this command:

mysqladmin --socket=/path/to/my/mysql/socket --user=dbuser -p status

Any help would be greatly appreciated on how to get the database setup in Drupal 8, thank you.

Edit: from Clive's suggestion I added the ini_set() lines above to Drupal 8's settings.php to no avail. I'm assuming it's user error at this point so I'm still trying things.

According to this Drupal issue, setting the socket in the UI is just not possible right now: (at least in 8.6.10)

https://www.drupal.org/project/drupal/issues/793200

I also could not figure out how to set the socket in sites/default/settings.php.

I had to resort to hardcoding my socket in this file:

core/lib/Drupal/Core/Database/Driver/mysql/Connection.php

This block of code:

    // The DSN should use either a socket or a host/port.
    if (isset($connection_options['unix_socket'])) {
      $dsn = 'mysql:unix_socket=' . $connection_options['unix_socket'];
    }
    else {
      // Default to TCP connection on port 3306.
      $dsn = 'mysql:host=' . $connection_options['host'] . ';port=' . (empty($connection_options['port']) ? 3306 : $connection_options['port']);
    }

I could not find any way to set "unix_socket" value on $connection_options, so I resorted to hardcoding it before this block like:

$connection_options['unix_socket'] = '/path/to/my/mysql/socket';


How to specify a Rules event like "Content is 'going to be' viewed"? To answer the question about "How to restrict access to a node via node/12 and allow access via a path like content/sometitle?", I thought it should be possible to use the Rules module to do so.

I was thinking about a rule as in this exported rule (which has "Content is viewed" as event):

{ "rules_disallow_using_urls_like_node_123" : {
    "LABEL" : "Disallow using URLs like node\/123",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "site:current-page:path" ], "value" : "node\/[node:nid]" } }
    ],
    "DO" : [
      { "redirect" : { "url" : "no_access" } },
      { "drupal_message" : { "message" : "Sorry, URLs like node\/[node:nid] are not allowed around here ..." } }
    ]
  }
}

Here is the challenge (and my actual question): for any node you visit, and even when visiting nodes using the path of such nodes, the rules action always gets executed. That makes me wonder how I can rework that "Content is viewed" event into something like "Content is 'going to be' viewed", so before Drupal is actually going to display the requested node? And this without writing a custom module.

To better explain the 'going to be'-part of it: compare it to the Content Access" module: if you try to visit a page for which content access is set so that you do NOT have permission to (e.g.) view it, then Drupal will FIRST check via content access if you do have access to it, then decides you have no permission, and then you will NOT actually be able to "view" that page (even though you asked for it). So that "will FIRST check" is similar to "going to be" ...

I also looked at the (unasnwered) question about "I cannot see the Rules event "Page is going to be viewed"", in which one of its comments points to issue nr 514824 (which is for D6). And in that issue there is Fago's comment #8 like so:

  Use the "Content is being viewed" event when you need the node.

Assuming that was available (and working as such) in D6, what is the D7 equivalent of this event, if any? Because, obviously, my sample above seems to indicate that in D7 it doesn't work like that anymore.

Note: The exported source above is intentionally DISABLED, because if you'd want to import it and enable it, then it is always going to get triggered for ANY node you view. Only URLs starting with (eg) /user or /admin will not satisfy the Event in this rule (so that at least you can disable this rule again to be able to view /node paths also again).

You should react to the System > Drupal is initializing event and check for the URL there:

{ "rules_check_url" : {
    "LABEL" : "Disallow node/* access",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, URLs like [site:current-page:url] are not allowed around here ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "no_access" } }
    ]
  }
}

Also, notice that in the rule above we test against the site:current-page:url token, which contains the (full) original URL (as seen in the browser address bar). Checking against site:current-page:path would not work in this case as all nodes, even the ones being accessed via URL alias, would match.


How do I limit a taxonomy dropdown exposed filter to the terms used by nodes in view results? I'm trying to create a custom node search view, that takes Taxonomy terms as a filter (dropdown - autocomplete not an option). The problem I have, is that there could be >1000 terms and I would like to restrict the dropdown to show only the taxonomy terms that are already in use by the nodes returned in the initial view results. Does this make sense?

Can anyone advise if this is possible, and if so, how best to achieve it?

Like you can already read on the bug report from Drupal.org which you've copied from, a good solution is to use Views Selective Filters. It does exactly you're asking for.


problems with hook_form_alter() function heihachi_form_alter(&$form, $form_state, $form_id) {
    if ($form_id == 'ipaper_node_form') {
           unset($form['body']);
        }
}

the code above removed body field in node/add/ipaper. But how can i remove body inside a node? (mysite.com/node/4420 for example).

And 2nd question is: i did print_r($form) inside mymodule.module and now im watching in the page source code and see this:

Array
{

    [#node] => stdClass Object
        (
            [uid] => 1
            [name] => heihachi

i am on the right way if i use this construction to print the name for example:
$form['#node'] => ['name'] ?? Guess not.. :) That stdClass Object is confusing me :(

A better approach is to edit the content type settings and omit body altogether.

In Drupal 6, you can do this by going to /admin/content/types/ipaper and leave the "Body field label" empty.

In Drupal 7, go to /#overlay=admin/structure/types/manage/ipaper/fields and delete the Body field.

If you really need to keep old content in the node body, then use hook_nodeapi() with $op == 'view to unset $node->body


how do i create a subscribe or join group link in drupal 7? I am trying to create a join or subscribe link for groups on my site but i don't know how to go about it (using views). I want to create something similar to this http://www.popsugar.com/community/suggest .

Any suggestions?


How to render a form in table layout What is the Drupal way of presenting multi-row, multi-column module data to the user in Drupal 6? Nothing jumped out in the API documentation. I was googling for some answers, but they all applied to earlier versions or referenced dead modules.

Am I correct in thinking that the out-of-the-box functionality for the forms API is basically a key::value editing interface? If that's the case, is there a current, well-maintained module to do this, or should I present this data in a different way for the user -- perhaps a view?

Edit I would like this table to have form features for editing the data, such as insert, changing cell data, etc. That's why I thought it would be natural for it to reside in the module's settings, but that table functionality does not appear to be there.

A little bit tricky

function your_form(){
  $form = array();
  ...
  $record_ids = array();

  foreach($record_set as $record){
      $record_ids[$record['id']] = ''; // Collect ids of your record as index
      $form['column1'][$record['id']] = array('#value' => $record['field1']);
      $form['column2'][$record['id']] = array('#value' => $record['field2']);
      $form['column3'][$record['id']] = array('#value' => $record['field3']);
  }

  $form['select'] = array(
      '#type' => 'checkboxes',
      '#options' => $item_ids,
  );

  $form['#theme'] = 'render_your_form'; // Theme registry function to render this form
}

Define theme_registry

function your_module_theme(){
   ...
   $theme['render_your_form'] = array(
       'arguments' => array('form' => array()),
   );
   return $theme;
}

Now write your theme handler

function theme_render_your_form($form=array()){
   $head = array('Select', 'Title Col 1', 'Title Col 2','Title Col 3');
   $rows = array();
   foreach(element_children($form['select']) as $id){
       $fields = array();
       $fields[] = drupal_render($form['select'][$id]); //This will render a checkbox, omit if not required
       $fields[] = drupal_render($form['column1'][$id]);
       $fields[] = drupal_render($form['column2'][$id]);
       $fields[] = drupal_render($form['column3'][$id]);
       $rows[] = $fields;
   }
   $output = theme('table', $head, $rows); // Theme as table output
   $output .= drupal_render($form); // Render rest of form components. (For D6)
   $output .= drupal_render_children($form); // Render rest of form components (For D7)
   return $output;
}


write to code without prefix table name I work on D7, My Sql database name is dbdrupal7 and all table prefix with abc (abc_block, abc_node, ...), website work fine. I create a custom table without prefix abc (custom). I create a module and write to custom code.

$query = db_select('custom', 'c');

$query->fields('c');

$results = $query->execute();

...

...

Show "unexpected Error" when browse.

I not want to change table name custom to abc_custom in database.

My question is how write correct code db_select('custom', 'c'); without prefix.

That behaviour is hard-coded with a SelectQuery; the prefix will apply to all tables, without exception, and there's no mechanism in place to override it. It happens in SelectQuery::__toString() if you're interested.

If you want to change that, you'll need to subclass SelectQuery, add a mechanism to let the class know which tables should/shouldn't be prefixed, and override the __toString() method to take that into account. Then you'll need your own version of db_select(), which uses your new custom version of the class.

All that's probably not worth the effort given that you can run an arbitrary SQL string with db_query(). For example, the following won't attempt to prefix custom:

db_query('SELECT * FROM custom c')


Update Node Problematically is not working fine I am using Drupal-6 . I am trying to update single field using following code.

    $nodnew->id=14;
    $nodenew->field_site_url[$array_id]['value']=$website_url;
   $nodenew->revision=1;
   $nodenew->changed = $node->created;
   $nodenew->comment = 0;
   $nodenew->type ='product';
   node_save($nodenew);

It updates field_site_url sucessfully. But it also changes other fields to blank.
like title, body etc. i want to add only field_site_url.

Any idea how to do this?

You can try to load node with its id :

   $nodenew = node_load(14); // load the complete node

So when you use node_save() all other field values that was previously stored in database will automatically get loaded. Then only thing remains is the field you want to update.

   $nodenew->field_site_url[$array_id]['value']=$website_url;
   $nodenew->revision=1;
   $nodenew->created = time();
   $nodenew->changed = $nodenew->created;
   $nodenew->comment = 0;
   $nodenew->type ='product';
   node_save($nodenew);


Custom module with config exposed in json api I have a module with two pieces of config set using an admin form and Drupal the drupal config service.
Like this
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);

    $this->config('mars_spot_collection.defaultcollections')
      ->set('default_collection_title', $form_state->getValue('default_collection_title'))
      ->set('default_collection_description', $form_state->getValue('default_collection_description'))
      ->save();
  }

How do I make this conig available in the JSONAPI?
Cheers

You can't do it. Not with the core JSON:API module. Out of the box, the resources JSON:API exposes are all the entity definitions from EntityTypeManager which includes content & config entities (defined by extending ConfigEntityBase).
However, arbitrarily set config values will not be exposed. JSON:API also doesn't support custom resources, as JSON:API docs state:

The JSON:API module provides no PHP API to modify its behavior. It
is designed to have zero configuration.
• Adding new resources/resource types is unsupported: all
entities/entity types are exposed automatically. If you want to expose
more data via the JSON:API module, the data must be defined as entity.
See the "Resources" section.

The JSON:API Resources project attempts to fill this in if you want to design your own endpoint with custom responses.


Create a custom template for a custom URL I'm using the Webform module and need to redirect users to a custom URL (with replacement tokens) once they have completed a job application in order to track conversions in Google Analytics.

I've set the URL to /application-completed/[job-ref-number]. This redirect works but I really want a custom template to be rendered rather than the default Webform confirmation message on a 404 page.

I've tried the following in my template.php file but the issue here is that it's a completely blank template (not rendering html.tpl.php), whereas I'd prefer to render the page.tpl.php template and simply replace the $page['content'] area with the custom template (would this be a node template?)

function MYTHEME_preprocess_page(&$vars) {
  if (drupal_match_path(drupal_get_path_alias(), 'application-completedy/*')) {
    $vars['theme_hook_suggestions'][] = 'page__mycustomtemplate';
  }
}

You're on the right track. You just need to also create a file named page__mycustomtemplate.tpl.php (place it in your mytheme/templates directory). The starting point for this file should either be the page.tpl.php in your mytheme/templates dir (if there is one), or the one in mysiteroot/modules/system. Simply open one of these and save it as page__mycustomtemplate.tpl.php in your theme's templates dir. Then you can replace <?php print render($page['content']); ?> with your custom text/markup.


restrict some url access, based on user roles I am theming an administrative page.
There are 2 roles (admin, role2) that have access to all the administrative pages. Now, I want to restrict the access to some URLs to the role2 role: Users with that role should be redirected to other pages. How is this done using the template?

I know I can use permissions to restrict the access, but I want to restrict the access basing on the URL being visited.

You can implement hook_menu_alter in your custom module and can provide function for 'access callback' property of the menu item.

<?php

/**
 * Implements hook_menu_item_alter()
 *
 */
function custom_feature_menu_alter(&$items) {

  $items['admin/structure/types']['access callback'] = 'custom_feature_access_callback';

}

/**
 * Custom access callback
 */

function custom_feature_access_callback($arg) {

  global $user;

  $roles = array_keys($user->roles);

  //Adding condition for the user roles. You can change 3 to your user role. I have tested this with administrator user role
  if (in_array(3, $roles)) {

    return FALSE;
  }
  else {
    return TRUE;
  }

}


Duplicate alias for different nodes after submitting form twice - Pathauto? I have found this issue, in many different installations of Drupal (I'm running 7.35, but problem occurs even in 7.34 and I think every other previous ones): if I click many times quickly on submit button in node creation forms (be it in administration pages or in forum topic creation pages, I have double-checked it and it occurs in both situations), Drupal creates n nodes with the same content, generating the same alias for different nodes in the same language (content is exactly the same), I checked with this other issue Drupal duplicate alias for same node but no changes, the problem remains. I noticed that even if I don't click so quickly there are many cases in which many of the created nodes have the same URL alias.

Nodes created with "shared" alias does have "Generate automatic URL alias" unchecked, those nodes which get a different (nnnn-0, nnnn-1 and so on) have this option checked.

Another strange thing is that creation timestamp delta of nodes with the same alias is of exactly of 2ms; I think this generates some kind of problem in pathauto module.

You can use unique_field module to prevent node creation on the basis of field value(unique field).

if this do not help then you can try to use hide_submit module to disable the submit button after first click.


Display Suite vs. EVA for displaying a view as field I want to display a specific view as a field in nodes. It’s the same view for all nodes of this type, making use of the contextual filter "Content ID from URL".

I found two solutions using contributed modules:

EVA: Entity Views Attachment: it’s specifically for this use case
(there is also Viewfield, but that’s still in alpha)
Display Suite: it’s not its primary use case, but makes it possible by adding a "block field", where you can select the block generated by the view

Assuming that Display Suite is installed anyway (installing it just for this use case would be overkill, I guess), is one solution better than the other? Both seem to work fine, but I’m thinking of possible issues I can’t foresee now, like performance impact or compatibility with the Drupal ecosystem.

I think the best contender for EVA is Views Reference Field:

EVA: Entity Views Attachment
Views Reference Field

Both have stable releases. Main difference is the workflow. EVA is perfect if you want to impress your co-workers with the ability to attach a View to a content type like magic. Views Reference Field gives content editors the power to add Views to content themselves. Both modules don't need a block display, EVA provides its own and Views Reference Field can use any display type.


Custom configuration forms: translation access denied While creating custom configuration forms, I'm getting an access denied. But on the /translation page of the form only. Configuration form itself can be reached, filled and updated without problems.

Configuration does show up on the admin/config/regional/config-translation page but can't be translated for some reason.

Any idea's?

Overview of files:

schema.yml

faq.settings:
  type: mapping
  label: 'FAQ settings'
  mapping:
    faq_title:
      type: text
      label: 'Title'
    faq_text:
      type: text
      label: 'Text'
    faq_cta_label:
      type: text
      label: 'CTA label'
    faq_cta:
      type: text
      label: 'CTA'
...

routing.yml

aform.faq:
  path: '/admin/config/aform/faq'
  defaults:
    _form: '\Drupal\aform\Form\faqForm'
    _title: 'FAQ block'
  requirements:
    _permission: 'administer site configuration'
...

config_translation.yml

aform.faq:
  title: 'aform FAQ'
  base_route_name: aform.faq
  names:
    - faq.settings
...

For anyone stumbling towards a similar problem: it seems you have to set-up not only schema, routing and config_translations yml files but you also have to define each configuration in installation yml files so your config is picked up by Drupal.

So I had to include a faq.settings.yml file in /install of my custom module directory, like:

faq_title: ''
faq_text: ''
faq_cta_label: ''
faq_cta: ''
langcode: en

And boom you got yourself a translatable configuration form.


Drupal 7 views exposed filter: Removing -Any- and sorting items I am using Drupal 7.21 and views 3.7. I have date module installed. In one of my views, I want to give drop-down year as an exposed filter and it is working fine. I do have choices as
-Any-
2012
2013
But I want to remove -Any- and sort the items, so it will be like
2013
2012
I checked Required in exposed filter option without success and also used BEF module but there is not any option to do so. I also saw some blog and issue suggesting using hook__form_views_exposed_form_alter hook. I used that as http://eureka.ykyuen.info/2012/11/22/drupal-7-customize-the-exposed-filter-selection-list/ this blog suggested but in my form option there isn't even any options listed not as this blog said.

Can anyone help me to get the exposed filter I want to show?
Thank you

You should implement hook_form_alter on your exposed filters form (if you have devel enabled then use dpm to find the form's name).
Using the form alter sort (or just revert)  the date's array and remove the '-any-'.
By the way to remove the '-any-' you may also use CSS which will allow you to quickly bring it back in the future if you'll want to.

I edited a similar code I used in the past according to your need, so you will need something like this:

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

  switch ($form_id) {
    case 'views_exposed_form':
      if( !empty($form['#id']) && $form['#id'] == 'views-exposed-form-myview') {
        // This is the myview view

      // Remove the start date label
      if( !empty($form['field_sw_date_value']['min']['#date_label_position']) )
        $form['field_date_value']['min']['#date_label_position'] = 'none';

      // Remove the end date label
      if( !empty($form['field_sw_date_value']['max']['#date_label_position']) )
        $form['field_date_value']['max']['#date_label_position'] = 'none';
      break;
    }
}


Drupal 7.12 : views filters i have a mark as checkbox field with two options - published and unpublished.
i want articles marked as 'published' to appear on a view page and those marked as 'unpublished' to appear after the published items as an attachment to the view. the unpublished articles will only be visible to the author. How can i go about achieving this? I have tried using the filter but to no avail. i chose the field name and selected 'is one of' then selected publish, but this did not work. Any suggestions?

Drupal contains a published/unpublished feature by default, which can be filtered in views using the Content: Published filter.

If you want to use a custom field though it should be as simple as you described. Assuming the published field is a taxonomy reference, you should be able to apply a filter to that field and select 'is one of' and the appropriate term (published). I tried this and it works.

As for the second part, you can clone the view and change the field filter to unpublished. Then add a Content: Author relationship and a User: Current (Yes) filter to filter it to content that the current user has authored (you might also want to put some access restrictions on this view). This view can then be added to the 'Footer' section of the first view.


WYSIWYG + CKeditor breaks my  lines and mess my paragraphs After installing the WYSIWYG module + CKEditor / TinyMCE (same result) all my paragraphs are blown away resulting in an uneditable mess. Can you give me a clue how to make it read my paragraph markup? Thanks

I had the same problem and I solved it by allowing paragraph and line break in the configuration of the Filtered HTML:

Configuration » Content authoring » Text formats » Filtered HTML

In the "Allowed HTML tags" of the "Filter settings" I added <p> and <br>


What is the best way to use Panels I have D6 and the Panels module installed.

I want to be able to control the entire page layout from within Drupal itself, without having to write any new code such as a template file etc

To achieve this, I create a very basic template file which includes the standard html, style, body elements etc and just:

<?php print $content; ?>

This works great, it allows me to for example create a Panel layout for different page layouts, but it also allows me to create full-page landing pages without header/footer etc

The only drawback is that for pages that dont have a Panels template, say for example the user login page, how do I then style/structure this page?

I found this article:

http://ykyuen.wordpress.com/2011/09/13/drupal-customized-user-registrationloginforgot-password-page-with-panel/

Which describes how to workaround this issue with Panels.

This worked well for me, didnt take long at all, but it seems a little hackish. If anybody knows a better way please let me know.


EntityFieldQuery condition How can i ommit an condition in Entity Field Query if variable do not exist, for example

->fieldCondition('field_filter_color', 'tid', $filter_color)

Recieves in $filter_color one term id.
But there are situations where $filter_color is not present, so i would like to do:
if $filter_color is empty, ignore this condition.

Alternative is to present it as an array like

->fieldCondition('field_filter_color', 'tid', $filter_color, 'IN')

and prepopulate all values in $filter_color, and if $filter_color is chosen, create array with only one value, but i am not sure it is best way to do it.

You can simply do this:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
// all other conditions go here

if (isset($my_field_val)) {
  $query->fieldCondition('my_field', 'value', $my_field_val);
}
$result = $query->execute();

Untried code as I don't have access to my files at the moment.


Views fields settings style settings no options avaible In views, after I choose 'Fields' as format, I want to add HTML to the title field.
The way you would normally do this is is expand the "Style settings" fieldset, then check "Customize field HTML". Only on the Drupal site in question there is nothing that expands under the checked item. I checked permissions and flushed caches but other than that I don't know how I woul be able to look at this. Could this be a javascript issue? Also checked console for that, but no errors there.

I had the same problem and found that it is caused by using jQuery 1.8, so with an older jQuery versions it should works just fine.


How to add an image property to an entity? I have a requirement to add a unique icon to each bundle of an entity. My entity code is very similar to the model module. I have 2 entities, one for holding the actual entity instances, another for holding the type information.

Each entity type will have a unique icon which will be shown while adding that entity in the creation form. For this, I need to add a custom property to the entity which will hold the image file data.

You need to create an integer property that references the fid column in the file_managed table.

For inspiration, check out the user_account_form() function (the picture element) and associated validate/submit handlers. They show the exact methodology you need to use.


Fatal error: in boostrap.inc line number 2913 I ma facing a Fatal error It says
 Fatal error: require_once() [function.require]: Failed opening required '/home/myapp/myapp.com/sites/all/modules/views/modules/user/views_handler_field_user_name.inc' (include_path='.:/usr/local/lib/php:/usr/local/php5/lib/pear') in /home/myapp/myapp.com/includes/bootstrap.inc on line 2913

I am unable to login,or add content type or create a view. Please help to overcome this issue.

I am very much need in it.

My site works fine if not logined.

modules/user/views_handler_field_user_name.inc is one of the Views files.
Delete the /home/myapp/myapp.com/sites/all/modules/views directory (and the files it contains), and copy the Views files from the archive file you download from the project page. Just be sure to download the same version you installed before, and to copy the files in the same directory they were before. (The views.module file must be in /home/myapp/myapp.com/sites/all/modules/views/views.module, not /home/myapp/myapp.com/sites/all/modules/views/views/views.module, or /home/myapp/myapp.com/sites/all/modules/views.module.)


How to override other module function/hook from my custom module? I'm currently working on a custom module which holds a list of organization IDs that will be used to match with an attribute I get from a SAML idP response.

I'm currently using the saml_sp SAML Service Provider module which has hooks/functions for finding the Drupal user and log it in, otherwise create a new user if none exists with that email.

I need to check if the org. ID matches any of the IDs in my custom module's table entries instead, so there's a substantial amount of modifications needed to change this workflow.

Preferably, I wish not to do any modifications to the saml_sp code as future updates of that module or fresh installations would cause havoc and the login won't work.

Is there a way to bypass saml_sp's hooks/functions so that my custom module can "take over" once the particular hook/function in saml_sp gets called?

There seems to be a lot of mixed opinions about this. Personally I don't see the point in not being able to do this, as the typical Drupal installation consist of an orgy of modules and they should all be able manipulate each other, right? Or am I missing another simpler solution to the problem?

In general, if a module does not provide a hook, some other will do.
You could check if some hook in core fits to what you need to do.
Depending on what is the final result of your data change, you could perform it after a module generates the data to be changed, and before the data gets saved, for example.
By another hand if a module already uses the same hook you want to use it is still possible to rely on the weight of your module to be sure it will run afterwards.
By the description of your specific requirements (login a user and create a user) hook_user_login and hook_user_presave could be used.


Simplenews css theming using mime mail I am using simplenews for my newsletter and mime mail to send them by mail.

I am trying to use the same CSS for my newsletter mail than my newsletter displayed on the web site.

Is it possible to refere the same css file?

On admin/config/system/mimemail you can tell mimemail to try and use the site's stylesheet when sending an email. You'll have to make sure that your css selectors apply to the elements of your email message or adjust it appropriately.

Alternatively if you want more control over the styles, do not tell mimemail to use the site's stylesheet but instead create a file named mail.css in your theme. Mimemail will automatically use it when sending emails.

Also make sure your theme is set as "Theme to render the emails" under admin/config/system/mailsystem, otherwise you might get the wrong stylesheets when your emails get sent via cron, for example.


Facet API - Rewrite facet items via callback function I'm trying to rewrite the link text in an Apache Solr facet block, specifically the one to drill down by bundle/content type. By default the block displays the human readable name of the content type. I want to avoid simply editing the name as this would affect other things in the site.

So, in the block I would rather have a custom text such as 'Music Videos' rather than 'Article' from the 'article' content type.

I hoped to use the hooks created by Facet API Bonus to rewrite facet items via callback function, but am having difficulty getting the code to work.

Here is what I have, based on material from here and in the Facet API Bonus module readme:

function custom_module_facet_items_alter(&$build, &$settings)
 {
  if ($settings->facet == "apachesolr@solr:block:bundle") {
   {
    foreach ($build as $key => $item)
     {
      switch ($key)
      {
        case 'article':
          $build['article']['#markup'] = 'Music Videos';
          break;
      }
     }
   }
 }

I'm using Drupal 7.27, Facet API 7.x-1.5 and Facet API Bonus 7.x-1.1 .

Thanks in advance for any help.

Make sure this filter is selected for your facet(s): "Rewrite facet items via callback function"
admin/config/search/apachesolr/settings > Facets > YOUR FACET > configure filters > [x] Rewrite facet items via callback function
You can verify your hook is implemented using drush and devel module:

drush hook facet_items_alter
Enter the number of the hook implementation you wish to view.
[0]  :  Cancel
[1]  :  my_module_name

If you see something similar to above, then your hook is implemented. To see the implementation code, enter a number (1 in this example).


Drupal adding some sort of hash on end of clean URL? The site is working normally otherwise, but junk like this: #.ULQf0OOe90s is added onto the end of every URL.

Any ideas why this might be?

Thanks

This seems very similar to this topic in Wordpress:

http://wordpress.org/support/topic/random-hashtag-strings-added-to-url-in-firefox

Did you had the "Share this" module installed?


Styling Superfish menu with Zen and Sass Can anyone advise on the best way to style your superfish menu when using latest version of zen and sass?
I am currently styling my responsive theme using the sass files which regenerate the css, which is going great, but superfish comes with its own set of css files which are located sites/all/libraries/superfish/style/css.

I ideally want to use sass to style it from my sass folder (under theme root) so its all consistent, so I dont have to keep changing into the supefish folder changing css directly.

Any ideas?

The latest version of Zen is organized according to the SMACSS way. However, what SMACCS calls modules is called components in Zen. This to avoid confusion, since Drupal already has a definition for 'modules'. SMACSS defines modules (or components in Zen) as follows:

..Module is a more discrete component of the page. It is your navigation bars and your carousels and your dialogs and your widgets and so on...source

All SASS code concerning components is stored therefore in your_zen_subtheme/sass/components/_misc.scss file. I would choose to add style rules for your Superfish menu there. You can use the Superfish classes (with the .sf prefix) to target only the Superfish menu instead of all menus.


How do I install Flysystem and Flysystem S3? I'm using the Flysystem module, but I am not able to install the module. I am getting this error:

  Dependencies missing: Flysystem, replicate adapter, stream wrapper.

I followed the steps given on https://www.drupal.org/node/2541116, but I am still not able to install the module.

I have installed the Replicate and Stream wrapper modules.

Is there any other method to integrate S3 with Drupal 8?

That documentation you referenced is outdated and wrong. You should read the official documentation on https://www.drupal.org/node/2404989.

The easiest way to do this is to install the drupal modules with composer, as documented on https://www.drupal.org/node/2718229. Once you've configured the drupal.org repository, installing a module is as simple as composer require drupal/flysystem. That will download that module, including alll dependencies that it needs for you.

You can manage your whole installation, including core, with composer if you use composer create-project drupal-composer/drupal-project:8.x-dev. You can also add contrib modules if you installed drupal core by hand, but when updating core, you need to be careful to not lose your composer.json changes and run composer update again.


Referencing both a node and user in the same field In Drupal 7, I am looking to create a field in a content type that can either reference another specific content type and/or also reference a user.  I am creating the content type programmatically in the .install file and am looking to be able to reference both types in the same field.

It currently works with one or the other as:

  'field_sport_team_members' => array(
    'field_name' => 'field_sport_team_members',
    'label' => 'Team Members',
    'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    'type' => 'node_reference',
    'description' => 'The members of the team',
    'weight' => '3.5',
    'required' => 0,
    'settings' => array(
      'referenceable_types' => array('club_person'),
    ),
  ),

for the reference to the content type and

'field_club_person_user' => array(
  'field_name' => 'field_sport_team_members',
  'type' => 'user_reference',
  'label' => 'Team Members',
  'description' => 'If this entry corresponds to a user, you can select the user here.',
  'weight' => '3',
  'cardinality' => FIELD_CARDINALITY_UNLIMITED,
  'translatable' => TRUE,
  'locked' => FALSE,
  'settings' => array(
  'referenceable_roles'  => array (
    4 => '4', //captain
    5 => '5', //player
   ),
   'referenceable_status' => array(
     1 => '1',
     0 => 0,
    ),
   ),
  ),

for the reference to the user type.

I guess my real question is now with the advent of "entities", is it possible to make a entity reference, but also to specify which content types to search for as well?

There are a few ways to do this. You said "and/or", you could use Field Collection and add a node reference and a user reference to it. See the field collection module.

The other option would be the relation module or the entity reference module which can both reference any "entity." The former is a lot more complex. Entity reference has a usable widget with autocomplete which might be exactly what you need. To narrow the entity reference down to the exact content types you want along with users, you will probably have to write a custom widget. You can see the default widget implementation in the source.


How to redirect a user to mobile site? I have created a Drupal 7 site with all required functions. As per the requirement I have to create a mobile theme for this site, which I did effectively. Now problem is I need to redirect the user to the mobile site if the request is made from a mobile. If the request is made from computer he should be redirected to the main site.

Thanks in advance.

There are already existing modules to do it like mobile_tools. Where u can set what theme to use for mobiles. and redirection on mobile detection also.


Views Template for first Block being applied to all I have a View called News which has about 10 different block displays in it serving various roles. I created a template for the first block (not block_1 and not the master) in order to apply some unique structure.

Though the changes are seen on all the blocks in News.

Based on the template suggestions for the block I need it to apply to, it suggests the following.

Display output: views-view.tpl.php, views-view--news.tpl.php, views-view--default.tpl.php, views-view--default.tpl.php, views-view--block.tpl.php, views-view--news--block.tpl.php

I'm using views-view--news--block.tpl.php since its the most granular of the options.

Is there another I should use?

Simply changing the machine name setting on the display allows me to make it what I want, so I gave it the machine name block_0 and now I can make a designated template for it.


Drupalgap: Hello World sample - where is app folder? I have a Drupal 7 website and wish to develop a mobile app for it. I have successfully installed Drupalgap. I am trying to run the Hello World sample app described in the Drupalgap 7 docs. The instructions say to create a custom module and place it in the app/modules/custom/my_module folder. The problem is that I don't have an "app" folder anywhere. What am I missing?
Thanks for any insights.

The app folder is in the folder mobile-application

Root folder drupal

mobile-application

app

modules

custom

my_module


Can I include a list of sub-menu pages in the content of the parent page? I have a page that is the parent of a series of menu items, e.g. Projects, with some project pages as child items in that menu. I would like this parent page to automatically have the list of children in the content. Is this possible?

I have a block that I created that lists this menu via the Views module...if there is a way to use that, it might be an alternative.

Thanks

By some coincidence, there is an article on how to embed a block in the middle of your node body content on Drupal Planet today.

It seems to me, though, that if you put the block at the top of your content and floated it with css, maybe with a border attribute, the result would perhaps be better than adding content to an arbitrary location inside the content.


Find users who have not uploaded certain contents in last 30 days I need to find users who have not uploaded certain contents in last 30 days. I have tried this query it is not working. Can anyone help me?

  select uid, max(created) as max_created from node where
  node.type in ('page','story') AND
  max_created < UNIX_TIMESTAMP()-2592000

I am getting error in phpmyadmin:

  1054 - Unknown column 'max_created' in 'where clause'

SQL is evaluated backwards, from right to left. So the WHERE clause is parsed and evaluate prior to the SELECT clause. Because of this the aliasing of MAX(created) to max_created not yet occurred.

You can try this,

  SELECT uid, MAX(created) FROM node WHERE node.type IN ('page','story')
  HAVING MAX(created) < UNIX_TIMESTAMP()-2592000


Custom PHP code to create a node with rules I am trying to create an Automatic Registration with rules. Basically when a new asset is created a rule will kick off and create a new registration node with custom PHP but the new node is not being created. I don't see any errors in the reports. Here is the code:

$node = new stdClass;
$node->type = 'asset_event';
$node->title = 'Automatic Registration';
$node->[field_first_name]['und'][0]['value'] = [site:current-user];
$node->[field_asset_event_type]['und'][0]['tid'] = 791;
$node->[field_asset_additional_informati]['und'][0]['value'] = 'Event created by automatic registration';
$node->[field_link_to_asset_id]['und'][0]['value'] = [node:field-link-to];
node_object_prepare($node);
node_save($node);

Thanks for any help.

In Rule:

Create a new entity
Of type Node
At the end of your action, the "Provided variables" section will give you the label of the entity created
Use that entity, already fetched, to set fields (with "Set a value") of that node.

Enjoy !


Ajax example dependent dropdown callback I have two custom Drupal modules moduleA and moduleB.
moduleA has all the functions for Ajax calls i.e. ajax_example_dependent_dropdown_callback and _ajax_example_get_second_dropdown_options.

I create a content type in moduleB called content_type_b.
I am using Ajax calls in moduleB to populate drop down in content_type_b.

While creating content for content_type_b, I try to choose a value from the drop down.
The first time, it works fine. The second time I get an error saying "An Illegal choice has been selected. Please contact the administrator". All these events happen before a node insert.

When I looked into the logs, the hook_node_validate of moduleA is getting called. The node insert must happen in moduleB. So node_validate of moduleB must be called. I think since the Ajax functions were present in moduleA, the node_validate of moduleA is being called.

Please advice how to proceed in this situation.

The issue was fixed by changing one of the fields in the Content Type to List(text) instead of node reference. After this the "Illegal choice error" disappeared.


Search engines tries to access node editing links In my dblog occassionally I am seeing query coming probably from search engines for links as

http://mydomain.com/node/13130/delete?destination=node

I wonder how possibly search engine got idea to query that kind of links (of course those links are not exposed to anonymous users)

I have xml sitemap installed but no such links exists in the index

When I query google for that link, I see that link is present in index (of course clicking on that link leads to access denied page), and also shows

A description for this result is not available because of this site's robots.txt

One possibility is that one or more logged-in users have Google Toolbar or something similar installed. I don't have it installed any more because I noticed when developing locally that every time I fetched a page in my browser the request was repeated by the toolbar, presumably sending it to Google.

In my experience there is no such thing as a non-public URL as far as Google is concerned. Any URL can be listed for indexing and so crawlers may attempt to fetch it from time to time. I suspect other tools may record URLs in a similar manner.


How can I uncheck a required checkbox on the edit page for a given content type? I have a "required" checkbox (single on-off boolean field) which users must check to agree to the rules of the site when they post a node of a certain content type.  When users edit nodes of this content type, I would like to reset the checkbox to force them to check it again.

How can I do this in Drupal 7?

Implement hook_form_FORM_ID_alter() such that it clears the #default_value property of the widget:

function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  $node_type = 'example_type'; // TODO: change to the desired node type
  $field = 'field_example';    // TODO: change to the name of the field

  $node = $form['#node'];
  if ($node->type == $node_type) {
    $language = $form[$field]['#language'];
    $form[$field][$language]['#default_value'] = 0;
  }
}


How Do I improve the performance of my Drupal7 Site? For somebody who is new to Drupal,  I see that there are many resources available on Drupal Caching but I am not sure which of them to use.

These are notes from my experiences and might vary from what others experience. I predominantly use LAMP stack and have considered the same in my suggestions.

Thumb rules for caching that I generally follow.

Process Once Use Multiple Times.
Live with stale data when possible
Clear Caches infrequently and keep it very specific.
When possible do the changes at the lowest level in the stack.
LAMP - DCCc : Linux,    Apache, Mysql, PHP, Drupal Core, Contrib and custom module.

Improve Performance of a Drupal Site (In the increasing order of complexity)

Keep the core updated, contrib module and themes updated. Yes it
matters.
Install APC on your server. (Moved to top based on suggestion from
Letharion)
Page Caching : admin/config/development/performance Difference between Minimum cache lifetime and Expiration of cached pages
Block Caching https://drupal.org/project/blockcache_alter Caching options for all the blocks.
Aggregate javascript and css files - Front End Improvements
https://www.drupal.org/project/advagg
Disable Unnecessary modules. Every module adds to the amount of code
that needs to be available for a page load. And it also increases
the number of lookups. Wherver possible use a generic module in
place of multiple module that does specific functionalities.
Cache Views content - Content aware caching for Views
https://www.drupal.org/project/views_content_cache
Disable DB logging - Use https://drupal.org/project/syslog_ng
Reduce 404 Errors -  http://www.brokenlinkcheck.com/
Fast 404 Responses  - https://drupal.org/project/fast_404 - Try
handling at server level.
Client Side Validations -
 https://www.drupal.org/project/clientside_validation
Compress Image - https://www.drupal.org/project/imageapi_optimize
Lazy Loading of Images - Don’t load unnecessary images -
https://www.drupal.org/project/lazyloader
Use Sprite Sheets - https://www.drupal.org/project/spritesheets
Set Minimum Cache Life Time Value to a higher number and use cache clearing modules to clear the caches for specific pages - Whenever I edit/update a node all the page caches for anonymous user are lost
Use Devel Module to watch queries.
Rewrite Views Queries /  avoid Views if its a overkill.
XHProf - https://www.drupal.org/project/XHProf
FPM, HHVM.
DB Profiling and Tuning - https://www.drupal.org/project/dbtuner
Use Boost, don't Bootstrap DB if not required.
 https://drupal.org/project/boost For most of the small to medium sites Boost is good enough and you may not need Reverse Proxies or so.
Use CDNs - https://www.drupal.org/project/cdn Its easy to set up.
If your cache tables are huge use Memcached - If you can install
 memcached and set up RAM for it, it is not as complex as it sounds.
Etags - Configure Etags properly.
https://developer.yahoo.com/blogs/ydnfiveblog/high-performance-sites-rule-13-configure-etags-7211.html
Use Reverse Proxy Server - Varnish(at-least for assets). Helps a lot if most of your users are anonymous.
Compressed transfer - Enable gzip compression
Keep Alive - Use Persistent Connections where possible.
Progressive JPEGS -
CACHING IN CODE - Eaton’s blog is awesome.
 http://www.lullabot.com/blog/article/beginners-guide-caching-data-drupal-7
Implement Cache Warming - https://www.drupal.org/project/cache_warmer - Cache Warm the pages before the end user hits them.
Master Slave DB Config - https://www.drupal.org/project/autoslave makes it easier for you to set up one.
Database Clusters - https://stackoverflow.com/questions/1163216/database-cluster-and-load-balancing
Load Balancers -http://en.wikipedia.org/wiki/Load_balancing_(computing)
Use heuristic Cache Warming - https://www.drupal.org/project/cache_graceful
Authenticated User Caching - https://www.drupal.org/project/authcache


add_where() causes the view not to be displayed have a page that features a few views based on content types. Each content type includes a keyword field. This page is reached from a short quiz. I'm trying to limit the content in the views based on responses in the quiz by pulling the $_POST data and comparing it to the keyword field. The code is executing, and I'm fairly sure I have the join right, but instead of limiting the content to matching keywords, the entire display block just disappears.

Here is my module code:

<?php

if (!empty($_POST["q1"])) {

    $q1 = $_POST['q1'];
    $q3 = $_POST['q3'];

    /**
     * Implements hook_views_query_alter to add a where clause to the views queries
     */
    function iamru_keyword_filter_views_query_alter(&$view, &$query) {

        global $q1, $q3;

        if ($view->name == 'iamru_prepared_statement') {
            $query->add_table('field_data_field_keyword');
            $query->add_where(1,'field_data_field_keyword.field_keyword_value', $q1, '=' );
        }

        if ($view->name == 'iamru_word_for_you_view') {
            $query->add_table('field_data_field_keyword');
            $query->add_where(1,'field_data_field_keyword.field_keyword_value', $q3, '=' );
        }

    }

}

Can anyone see where I've gone wrong here?

Interesting update: If I replace $q1 with 'somekeyword' in the add_where call, it actually works.

It was a problem with accessing the global variables. In the end, I got it working with the following function:

function iamru_keyword_filter_views_query_alter(&$view, &$query) {

        $q1 = $GLOBALS["_POST"]["q1"];
        $q3 = $GLOBALS["_POST"]["q3"];

        if ($view->name == 'iamru_prepared_statement') {
            $query->add_table('field_data_field_keyword');
            $query->add_where(1,'field_data_field_keyword.field_keyword_value',  $q1, '=' );
        }

        if ($view->name == 'iamru_word_for_you_view') {
            $query->add_table('field_data_field_keyword');
            $query->add_where(1,'field_data_field_keyword.field_keyword_value',  $q3, '=' );
        }

    }


How do I keep content's styles? I have created a new custom content type: tw-how-to-guide.

This is a simple content type that only has one field: a paragraph module. And this paragraph module contains:

some nested paragraph modules
a number list

I would like the contents of the custom node template to display exactly as it does today. I am only looking to make two changes:

Wrap of the tw-how-to-guide content in a div with a css class
based on the selected number from the number list, add an additional div below the wrapper div, with the same class.

I have created a template file: node--tw-how-to-guide.html.twig
However, this is not displaying anything. I have tried using kint, with the following:

<div class="printPage" >

  {{ kint(content) }}

</div>

And I get the array in Kint, which is nice. However I do not wish to customize the display of the contents. I want the content to display as before. I am just interested in modifying the wrapping div.

I am concerned that I will need to recreate, or doing some complex work, to simply add some div tags.

I am really hoping this task can be done easily without having to parse each time in the array and call new templates. As I mentioned, it just adding a wrapper div, and then addition same divs based on selected number.

Any ideas on how to achieve this?

Content is not a variable of a field template. This is the reason kint(content) does not produce any output. The content of the field is in items:

  {% for item in items %}

{{ item.content }}

  {% endfor %}

Did you try twig debug to find the right template?

Debugging Twig templates

Edit: (Template in question was edited to node template)

This is no problem to add divs and classes to the node twig. Here is an example:

        {{ content }}

I've added two container inside and outside the article tag and one class to the article tag itself.


How do I see the ID of a content type record? Using Entity Reference, I'm able to create a Field in a Content Type (Person) which references another Content Type (Story). When I go to input link data, I see a list of Title(s) of Story(ies).

How do I know that I have the right story? There are many crime fiction stories with the same title.

Is there a way to expose the Content Type record ID?

When creating your entity reference field there is a "Mode" selection. The default is simple but you can choose to use a Views entity reference display type instead.

So in views if you create a new view (that displays the data you want) and add a entity reference display type to i. You can then use that in your entity reference field.

EDIT: Just seen the comment above referencing Show node IDs along with titles in Entity reference Autocomplete list Do that


Override Commerce Kickstart Features ( and Features Override module error) I have the Drupal Commerce Kickstart bundle in my project. This bundle contains a bunch of Features. Most of them are overridden now. It's not good to have most of setting inside the DB instead of features, so I want to save my changes inside my features.

As far as I know, it's not a good idea to modify the Kickstart Features, so I tried to use the Features Override module.

But, unfortunately, got "white screen of death" on Feautures Override Tab. Also, it broke all of my Kickstart Features.

The only "evidence" is the message:

  Notice: Array to string conversion in
  features_override_features_export_render_addition()

PHP: 5.4.9
Commerce Kickstart: 7.x-2.9
Features Override: 7.x-2.0-rc1

Do you have any ideas how to fix this problem with Featuers Override, or just how can I move my settings from DB to code in my situation?

I've found that Features Override works nicely in simple scenarios, but I've been unable to get it working in more complex scenarios, such as modifying Drupal Commerce.

One alternative — instead of modifying the Features Components provided by Drupal Commerce — is to clone them, make your changes to the cloned components, and then featurize the cloned components.


How to skip (not ignore) some rows in migration? I want to skip some rows in my migration, so that rows will imported on the 2nd attempt. for this am returning false in the prepare row function.

public function prepareRow($row) {
if($parent) {
      return TRUE;
    }
    else {
      return FALSE;
    }
}

but this ignore that rows and then I am unable to import the data again.
Is there any option to skip some rows so that I can import them on 2nd attempt?

Migrate doesn't work with attempts, so it always performs one migration (that you can update with the latest content).

Considering the fact you need some parent do be defined first, it might be easier to apply some sorting, so the parent is always created before the child (and you would not need several attempts). If you are migrating from a Drupal (7) site you can use the menu_links table for this. See the section about book hierarchies here: Migrating Book module nodes for a similar situation.

If you are not migrating from Drupal, but some other system you might want to look for a similar table.

As an alternative, you might be able to use the handleSourceMigration() function to see if the old parent id is already migrated (function returns NULL otherwise) and skip rows based on that, then re-run the migration. But I have never used this method and it might not work.


Using Entity API, if given an entity in a function scope, how do you get the entity type? This is very similar to this question: How do I get entity_type and entity_id from any entity page?
But I don't know what that asker means by "Entity Page," and in my case, using debug_backtrace (seriously?) doesn't cut it as I'd like this function to actually work from more than 1 scope.

Anyway... I am writing a module that uses numerous Entity Reference fields, and works the same code over several types of entities.  The trouble is that in my function scope I don't know the type of entity.

If I pass an Entity object into a function, I can access its type parameter:

function foo ($entity) {
  // bundle is:
  $entity->type;
}

But how do I get the "Entity Type" from this object?

For example, I have a dateset entity type with several bundles: class and retreat.  When I pass an instance of the class bundle into my function, I can identify that it's a class, and use identifier() to get its ID.  But I want my function foo() to also handle node entity types with bundles content_type_a and content_type_b

Given any instance of one of those bundles, foo() can identify the bundle:

function foo ($entity) {
  $entity->type; // class, retreat, content_type_a or content_type_b
  $entity->indentifier(); // numeric ID
}

But what about getting node vs. dateset?  Doesn't $entity know what type of entity it is?

UPDATE:
Even though I accepted Yury's answer because it provided a realistic workaround, I think the true answer is that you cannot do this in Drupal.  You have to pass around $entity_type anywhere you pass $entity (which really kind of makes the idea of having Entities as objects pretty much worthless... but I think any Drupal developer knows that object oriented concepts in Drupal are just hacked in and not ever truly related to real world object oriented design).  See this Drupal issue: http://drupal.org/node/1042822

There are various (convoluted) methods for getting the entity type and bundle, but none that I'd consider "acceptable" on a large-scale. What I've done is implemented hook_entity_load() and added the entity_id and entity_type properties on all entities at load-time.

The following code does this, and is part of the Devtools module I maintain:

function hook_entity_load($entities, $type) {
  // add the entity type & id to all entity objects for easy data access
  // from other hooks & modules
  foreach ($entities as $entity) {
    // we don't want to add these entity fields when the entity is being exported into
    // a feature, otherwise the feature will always show as overridden and will not
    // revert
    if (  preg_match('#admin/structure/features#', $_GET['q'])  // features page
            ||
          (                                                     // drush fu command
            isset($_SERVER['SCRIPT_FILENAME']) &&
            preg_match('/drush\.php$/', $_SERVER['SCRIPT_FILENAME']) &&
            isset($_SERVER['argv'][2]) &&
            $_SERVER['argv'][2] == 'fu'
          )
       ) {
      continue;
    }

    // set entity_type
      $entity_type_field = (!isset($entity->entity_type)) ? 'entity_type' : 'devtools_entity_type';
      $entity->{$entity_type_field} = $type;

    // set entity_id
      $entity_id_field = (!isset($entity->entity_id)) ? 'entity_id' : 'devtools_entity_id';
      list($entity->{$entity_id_field}, $vid, $bundle) = entity_extract_ids($type, $entity);
  }
}


Embed vimeo video into the body field How do I embed a vimeo video into the body field. The iframe is being removed in my input format. How do I add it?

The input formats can be configured at /admin/settings/filters/list so that you can add the <iframe> tag as an allowed tag to the input format that you are using.

Though, I think for security purposes, you may want to allow tags other than <iframe>.  One option it so use Vimeo's 'old' embed code (the link would be just above the box where you copy the code from).  The old embed code uses the <embed> and <object> tags, which you'll likely still have to add to the filter's allowed HTML tag list.


how to stop a view from executing within a views hook I am using custom code with a views pre_execute and i want the view to return an empty set if certain conditions are met , or not to return the view at all.
how can i do this ?  this is what i tried.

function mymodule_views_pre_execute(&$view) {
   // if certain conditions are met i want this view to be empty or not come out at all
  if ($myconditions){
   $view = null;
  }
}

this worked for me, i unset all the results and the view disappeared

foreach ($view->result as $key => $value) {
    unset ($view->result[$key]); // delete a row

  }


User login through JSON request returning HTML instead of JSON I am using Drupal 8.6.4

http://example.org/user/login?_format=json

When I try to submit a post request, it returns HTML page instead of JSON response.

I am sending headers:

  Content-Type: application/json

and data as:

 { "name": "admin" , "pass": "admin" }

What am I missing?

It turned out that the Redirect after login module was redirecting to the given URL, which resulted in HTML being output. I have disabled that and now I am getting the proper JSON response.


Creating Nodes and Referenced Nodes at Same Time I have a situation where I would like to be able to create nodes and referenced nodes at the same time.  Are there any solutions for this that work well for this?

To clarify what I am talking about, consider the following situation (highly simplified for the sake of explanation):

There is a content-type Class that has a node referenced field, Student.  I would like to have users be able to create Class nodes and Student nodes at the same time.  I would also like them to be able to use the normal node reference auto-complete to pick a Student who happens to already exist.

Ideally, I would like all of this to work from a single page, and also work within the confines of the Drupal permission system so I can have various roles and various permissions.

Yes, I know that in this case Student would be best served as a user (rather than a node), but Class and Student are just to illustrate the situation.  The real scenario really does need node references.

There is a similar question to this, Creating referenced nodes together with parent node, but I am specifically interested in Drupal 7 solutions only.

EDIT:

Not just looking for existing modules, but also head starts for custom code.

For a couple different sites now, I've done this using a ctools modal, and here's the basic outline of how I've implemented it (very simply):

Create a custom page callback in your module's hook_menu() that displays a basic node form for the node you want to reference (for a 'student' node, just have a name field and maybe a graduating year field). On that form, in your submit callback, save the node using node_save(), and store the node ID (which should be at $node->nid after you pass a new node object to node_save()) in the form's $form_state['storage']['student_id'].
Alter the master/Class node form using hook_form_alter(). You need to do a few things here:

First, you need to add in the ctools modal javascript and
    functionality so ctools knows what to do with your special link:

// Add in ctools modal js and functionality.
ctools_include('modal');
ctools_modal_add_js();

Second, you need to add a link to the page callback you created in step 1 in hook menu, and with that link, add the class 'ctools-use-modal'. So, for example:

// Add link to custom student form callback with ctools modal.
$form['add_student_link'] = array(
  '#markup' => l(t('Add Student'), 'mymodule/add-student', array('attributes' => array('class' => array('ctools-use-modal')))
);

In your custom page callback, you need to do a few things to make it work with or without JavaScript, and with ctools' form functions.

Here's an example callback:

<?php
function mymodule_student_form_callback($js = FALSE) {
  // Make sure $js (set by ctools) is TRUE/loaded.
  if ($js) {
    // Add in ctools modal form stuff.
    ctools_include('modal');
    ctools_include('ajax');
    $form_state = array(
      'ajax' => TRUE,
      'title' => t('Create a Student'),
    );

    $output = ctools_modal_form_wrapper('mymodule_create_student_form', $form_state);
  }
  else {
    return 'Javascript must be enabled for this feature to work.';
    // Or, if we wanted to load the form normally...
    // return drupal_get_form('mymodule_create_student_form');
  }

  // If the form is executed, dismiss the form and reload the page.
  if ($form_state['executed']) {
    $commands = array();

    // Close the frame.
    $commands[] = ctools_modal_command_dismiss();

    // Use one of the ajax framework commands to place the returned
    // student node nid into the proper form value, placholder div, etc.
    // See: http://api.drupal.org/api/drupal/includes%21ajax.inc/group/ajax_commands/7
    $commands[] = ajax_command_append('#student-id-placeholder', $form_state['storage']['student_id']);

    $output = $commands;
  }

  // Render the output.
  print ajax_render($output);
  exit();
}
?>

In mymodule_create_student_form($form, $form_state), build your form like you normally would, and then in the mymodule_create_student_form_submit(form, &$form_state) (submit) function, set the value of the NID of the newly created student node in $form_state['storage']['student_id']. This is how you'll get ctools/AJAX to pass back the new nid to your original Class form.
In my situation, I was using the modal to spit back some markup to the original page, so I passed the markup into a placeholder div using ajax_command_append(), then I had some jQuery on the original page monitoring the placeholder div, and when it found content in it, it would move the HTML into the proper place elsewhere on the node form. In your case, you'll need to populate a single or multi-value node reference field, which may be a little more complex. I haven't needed to do that yet... so I don't have more advice to offer for that part of the equation.


Sessions Table Getting Huge Currently, my sessions table is 1.6gb with 3,956,161 total rows. I think the sessions does not expired. I have a default settings in my settings.php as follows:

ini_set('arg_separator.output',     '&amp;');
ini_set('magic_quotes_runtime',     0);
ini_set('magic_quotes_sybase',      0);
ini_set('session.cache_expire',     200000);
ini_set('session.cache_limiter',    'none');
ini_set('session.cookie_lifetime',  2000000);
ini_set('session.gc_maxlifetime',   200000);
ini_set('session.save_handler',     'user');
ini_set('session.use_only_cookies', 1);
ini_set('session.use_trans_sid',    0);
ini_set('url_rewriter.tags',        '');

is the variable above related to sessions table? If yes, what is the recommended settings to expire the session after 2 days?

Update:

I just found that this is due to OS limitation of ubuntu which I am currently using. This was explain at this drupal module: https://drupal.org/project/session_expire

The problem is, Session Expire module is still in alpha release.

Is there any other module that can do this same?

While waiting for an answer, I found the solution at this blog.

All you need to do is to edit the settings.php under /sites/default folder.

Here are the two variables that need to be set:

ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 100);

Be sure to change also the cache expiry of the following variable according to your needs:

ini_set('session.cache_expire',     3600);
ini_set('session.cookie_lifetime',  3600);
ini_set('session.gc_maxlifetime',   3600);

The default is 200000. 3600 is equavalent to 1 hour.


Views output realname field as a contextual link Contextual is set up to display all content from a user for a specific content type.
www.example.com/users/realname/gallery where realname is contextual filter.
Realname is used with token that reflects field from registration: field-choose-realname.

Lets say we have 2 users and 1st writes "One" as realname and 2nd writes "One Two".
Realname contextual filter is setup to use lowercase and change spaces to dash.

Here is what happens:
www.example.com/users/one/gallery - ok

www.example.com/users/one-two/gallery - page not found error
www.example.com/users/one%20two/gallery - ok

For Contextual "when the filter is in the URL or a default is provided" i am using this php code (i did not write it so i have no clue what it does really):

if (!isset($argument)) {
  return FALSE;
}
$query = db_query('SELECT uid, realname FROM {realname} WHERE realname = :realname', array(':realname' => $argument));
$row = $query->fetchAssoc();
if (isset($row['uid'])) {
  return TRUE;
}
return FALSE;

To better explain what i want to do:
Get sidebar menu like on myspace for bands. When you land on bands page you can use sidebar menu to check their foto galleries, band members, video gallery and links must be made with a field that is not default username (it can be realname module or some other text field). Field validation is used so i do not get same name twice, and all links in pathauto are made example.com/bands/realname.
To repeat again it does work if realname contains 1 word.

Setting the contextual filter to transform spaces to dashes will not make the Realname field in the database contain dashes, so the filter fails. In your url you look for one-two, in the database this is One Two they are not the same and it doesn't work (one-two ≠ One Two).

First make sure pathauto is installed and enabled. It will provide your users with a pretty url. This will make sure every user has a unique path.
If you replace spaces and dashes in the URL as you do now, the contextual filter for these users One Two, One-Two, One'Two will all become one-two even if they are if fact different users. So your results will be mixed up. Pathauto will make sure they become unique; one-two, one-two2 and so on.

Do not rely on simple pattern matching, but use the uid from the instead. Luckily we can hide this entirely from the url by using a View's contextual filter.

Update

It seems I have missed a module requirement; Sub-pathauto (Sub-path URL Aliases).

  The Drupal Path module matches only full URLs when creating
  SEO-friendly aliases. This module extends that behavior by also
  matching known sub-paths and replacing them with their respective
  alias.

  For example, if user/1 is aliased to users/admin, this module rewrites
  the link to the user contact page user/1/contact to use the aliased
  URL users/admin/contact instead.

The is required to properly obtain the UID from the url.

Then create your view as follows:

Use must use the unaliased path for the path. So if your user is at /users/url-safe-realname and your gallery at /users/url-safe-realname/gallery, you enter /user/%/gallery (omit the s in users pathauto adds if using default settings).

For the contextual filter, in the WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED section, check Specify validation criteria, choose user and numeric UIDs.

The result will be a page that has the url-safe realname in the path and shows only content created by the user:


Ubercart override default flat rate quote Drupal 7.  Using Ubercart 7.x-3.10.  I created a shipping default flat rate quote of $7.  I created a product and gave it a flat shipping rate of $3.00.  When I check out, the shipping quote is $10 (default + product).  I don't understand how I get the product flat rate quote to override the default flat rate quote.  Could someone please point me in the right direction?  Thanks!

What I discovered is that in order for the default shipping flat rate quote to be overridden by product flat rate quote:

In Configuration->shipping quotes:
Base price must be set to 0.00
Default product shipping rate set to whatever the flat rate is.  In my example, it was $7.00.

In product ->shipping settings->flat shipping rates:
Flat rate quotes should be set to the overriding amount.  In my example, it was $3.00.

So, in the test product example, the flat quote shipping rate would be $3.00.  If no rate is set in the product, then the rate will be the default shipping quote of $7.00.

A bit confusing at first, but logical, I guess.


Find a URL inside Twig file from content made from another content type (referenced/ has a relationship) I'm new to Drupal, and have stumbled across this issue.
I have entries (entry) that are blogs held inside a blog_listing. E.g.
{% for entry in content.field_blog_listing_entries|field_target_entity %}

{{ entry.title.value }}

{{ entry.field_blog_excerpt.value }}

{% endfor %}

The blogs are their own entries that have automatically generated URLs. e.g. Blog 1 can be found on blogs/blog-1.
How do I get this URL from within the code block above?
I want to access the value in the same manner that I do with the title and field_blog_excerpt to put into an anchor tag. I've tried the same method e.g. entry.url.value & entry.field_blog_url.value but these don't return anything.
How do I access this URL value?
Any help appreciated.

You can use path function with the route for node (entity.node.canonical) and the entry.id (node id) for your blog entry. Pass the id in with the "node" parameter.

More info here: https://www.drupal.org/docs/theming-drupal/twig-in-drupal/functions-in-twig-templates


Can I get dependent services into a custom class without creating a service? I've got a class hierarchy where I need to be able to instantiate different objects within the hierarchy.  Instead of using global functions, I'd like to use injected services from the container via $this within those objects.

When researching this, it seems as though the only examples I can find involve creating a service, such as Dependency injection in a custom class.  However, I don't need a new service.  If I did create one, wouldn't I need to create one for every class within the hierarchy so that they could be instantiated?  This seems excessive.

If my parent class implements ContainerInjectionInterface and I have a create() method to inject the services, can I just instantiate the objects this way, or is it bad practice?

$thing = OneOfMySubClasses::create(\Drupal::getContainer(), ...);

Not sure how many classes/services you have, but the main point for having services is to have the dependencies injected. Drupal core alone has probably 100+ services, so I wouldn't worry too much about adding 10 or so more.

Using ContainerInjectionInterface is also fine, if you do that, you can use the class_resolver service that will take care of doing that, it also accepts both a class implementing that interface as well as a service name.

https://api.drupal.org/api/drupal/core%21lib%21Drupal.php/function/Drupal%3A%3AclassResolver/8.4.x

Depending on how you use/configure/decide which of your classes to you, you could also make a plugin type and make them plugins, e.g. like block plugins or field formatters.


using EntityFieldQuery with flagging condition I would like to perform a query to find the node flagged with a "myflag" based on a node field value. Is it possible to use EntityFieldQuery to accomplish that?
If not, how can I use Views api to do it?

Don't need to use EntityFieldQuery or views to perform this flag module has already give function to get is_flagged(). All you need to call functions like.

$flag = flag_get_flag('myflag');
$flag->is_flagged($node->nid);
if($flag && $flag->is_flagged($node->nid)) {
  print "This node is myflag!";
}


How to render a Get Locations map programmatically? I'm using Get Locations module and the getlocations_fields submodule. I have a content type where I created a "Getlocations Fields" field, this way I can select locations when adding/editing content. I have multiple nodes which contain locations.
Now I would like to display one Get Locations map from given nodes (I have some node ids) programmatically. (I know there's Views integration, but I have a complicated task.)

What is the appropriate way to do this? I haven't found the right method yet, I don't know how Get Locations module's API works.

Hmm, maybe inspecting "A map in your own module" (https://drupal.org/node/2061951) and getlocations_fields_field_formatter_view() in getlocations_fields.module is a good start.

OK, I created a block output as per "A map in your own module". Now I need to collect the content of $latlons array. Do you know how to retrieve these data from entities with Get Locations API?

On admin/config/services/getlocations, you can configure different map markers for taxonomy terms if you "Enable Markers for Terms (Select Vocabularies enabled in a Term reference field)". I set a term reference field for my content type, and this way the NODE appears with the given marker. I would like to keep this behavior, "querying" the Get Locations field's data with markers for a given node, and display that appropriately. But I can't figure out how.

As per hutch's comment, and my experiments, I managed to solve it. I wrote it down here: https://drupal.org/node/2082137#comment-7832139.

I created a separate function for the task:

/**
 * Load a map from multiple node ids with the appropriate markers
 *
 * @param array $nids The node ids of the nodes you want to get displayed on the map.
 * @param array $getlocations_extra_settings Some extra settings you want to override the default values with.
 * @see https:// drupal.org/node/2082137
 * @todo Patch for getlocations_setlocations() to accept settings which override the defaults, or figure out an alternative solution.
 */
function getlocations_nodemap_multiple($nids = array(), $getlocations_extra_settings = array()) {

  $latlons = array();
  $minmaxes = array('minlat' => 0, 'minlon' => 0, 'maxlat' => 0, 'maxlon' => 0);
  $count_nids = 0;
  // override default settings
  $getlocations_settings = array_merge(getlocations_defaults(), $getlocations_extra_settings);
  $marker = $getlocations_settings['node_map_marker'];
  $typemarkers = getlocations_get_markertypes('node');

  foreach ($nids as $nid) {

    // maybe a less resource consuming method should be used
    // btw., what about entity_load()? (https://api.drupal.org/api/drupal/includes!common.inc/function/entity_load/7)
    $node = node_load($nid);
    $locations = getlocations_load_locations($node->vid);

    if (isset($typemarkers[$node->type]) && $typemarkers[$node->type]) {
      $marker = $typemarkers[$node->type];
    }

    if (count($locations)) {
      // we should loop over them and dump bummers with no lat/lon
      foreach ($locations AS $key => $location) {
        $latlon = getlocations_latlon_check($location['latitude'] . ',' . $location['longitude']);
        if ($latlon) {
          $minmaxes = getlocations_do_minmaxes($count_nids, $location, $minmaxes);

          if (!isset($location['key'])) {
            $location['key'] = '';
          }
          else {
            if ($location['key'] == 'nid') {
              $location['lid'] = $nid;
            }
            elseif ($location['key'] == 'vid') {
              // not vid?
              $location['lid'] = $nid;
            }
          }

          // term markers
          $marker = getlocations_get_term_marker($nid, $marker);

          // per location marker
          if (isset($location['marker']) && ! empty($location['marker'])) {
            $marker = $location['marker'];
          }

          $count_nids++;

          $name = htmlspecialchars_decode($location['name'] ? strip_tags($location['name']) : strip_tags($node->title), ENT_QUOTES);
          $latlons[] = array($location['latitude'], $location['longitude'], $location['lid'], $name, $marker, $location['key']);
        }
      }
    }
  }

  if ($count_nids < 2 ) {
    $minmaxes = NULL;
  }
  return getlocations_setlocations($latlons, $minmaxes);
}

And now I can call it like this:

function testmodule_any_custom_page_callback_you_want_to_use($blabla) {

  $output = '';

  $nids_array = array(41, 45, 52, 73, 219); // of course, this array is generated

  $getlocations_extra_settings = array();
  $getlocations_extra_settings['extcontrol'] = 'testmodule';
  $getlocations_extra_settings['fullscreen'] = 1;
  $getlocations_extra_settings['streetview_show'] = 1;
  $getlocations_extra_settings['maptype'] = 'Map';
  $getlocations_extra_settings['visual_refresh'] = 1;

  $output = getlocations_nodemap_multiple($nids_array, $getlocations_extra_settings);

  return $output;

}

This solution currently has its limitations, because unfortunately the default settings are hardcoded to getlocations_setlocations (the values of getlocations_defaults() are currently hardcoded). I hope hutch will develop this part further. :)


How to create image gallery and integrate it to lightbox2 I have a content type Product with a field Images. There are 4 photos. When i go to the product-node page i want to click on one of the photos (1 of 4) and open a popup/modal window where i would like to see all 4 photos (not only 1, as  Lightbox does). How can i do that?

You can do this by using Colorbox module.

  Colorbox is a light-weight customizable lightbox plugin for jQuery.
  This module allows for integration of Colorbox into Drupal. Images,
  iframed or inline content etc. can be displayed in a overlay above the
  current page.

How to use ?


How do I choose which module to use when there are several options for the same functionality? It's not at all uncommon to find multiple modules that provide basically the same functionality. For instance, there are many SPAM control modules that offer extremely similar functionality (e.g., Spamicide and Hidden CAPTCHA). And there are lots of Taxonomy modules that do similar things. So when multiple modules meet my requirements, how should I choose which one to use?

Personally I do a few basic checks before digging deeper.

How many reported installs? (about the same in your example modules).
How long since last update to module? (Spamicide is 5 days ago (from today))
How many open issues?
Who is the developer? (Have they worked on other modules that I use, etc).

Then you can start digging into integration, if I where looking for an inline image management tool I personally would choose something that takes advantage of other modules instead of rolling it's own solutions, something that is features exportable, etc.


Is it possible to use a function which uses $node without the expense of node_load In cases where $node is not available but I know the nid, is it possible to mimic $node rather than using node load. I would like to try and cut the expense of performing a full node load..

For example to find a nodes taxonomy by vocab:

  $nid = 1;
  $vid = 1;
  $node = stdClass();
  $node->nid = $nid;
  $terms = taxonomy_node_get_terms_by_vocabulary($node, $vid);

I have tried the above but it doesnt seem to work. I want to use the taxonomy_node_get_terms_by_vocabulary function but dont want the expense of having to use node_load to get the $node object

In this case, I would just look at the source for taxonomy_node_get_terms_by_vocabulary:

function taxonomy_node_get_terms_by_vocabulary($node, $vid, $key = 'tid') {
  $result = db_query(db_rewrite_sql('SELECT t.tid, t.* FROM {term_data} t INNER JOIN {term_node} r ON r.tid = t.tid WHERE t.vid = %d AND r.vid = %d ORDER BY weight', 't', 'tid'), $vid, $node->vid);
  $terms = array();
  while ($term = db_fetch_object($result)) {
    $terms[$term->$key] = $term;
  }
  return $terms;
}

The only thing needed is $node->vid.  Note that vid in this particular referes to node revision and not vocabulary ID.  If you knew the vid, then you could just create your own function:

function mytaxonomy_node_get_terms_by_vocabulary($nodevid, $vid, $key = 'tid') {
  $result = db_query(db_rewrite_sql('SELECT t.tid, t.* FROM {term_data} t INNER JOIN {term_node} r ON r.tid = t.tid WHERE t.vid = %d AND r.vid = %d ORDER BY weight', 't', 'tid'), $vid, nodevid);
  $terms = array();
  while ($term = db_fetch_object($result)) {
    $terms[$term->$key] = $term;
  }
  return $terms;
}

The problem is that in most cases you don't know the $node->vid without doing a node_load.  Just querying using the nid may or may not be right if you use revisions or start using revisions in the futures.  The proper way to do it would be to JOIN the node table into the query so you can use $node->nid as an argument instead of $node->vid.


Limit text field to specific length In my custom content type, I want restricted the length of text entered in a text field. I want to check whether a user entered e.g. thousands of words. For this I tried this one but unable to achieve.

$my_field = field_get_items('node',node_load($nid, NULL, TRUE), 'my_field');
$my_field = substr($my_field,0,100).'...';
print $my_field[0]['value'];

Is there any way to do this in drupal 7 context?

If you're really trying to restrict the character count at the point of entry you need to set the field in your form to have a #maxlength in your form definition.


Adding variable to user profile page in drupal 6 I have a custom module let say mymodule. One of the function in this module generates or returns  some contents. Forget about what the content is. My question is how could i add this content to user profile page. I tried to override using user-profile.tpl.php file. I could override the theme. But how to add a variable to this page that contains the required content so that i can echo the variable. Is there any preprocessing function that will help

Use the hook_menu in your custom module and use MENU_LOCAL_TASK as the type, and the path in your custom module needs to start with user/

function HOOK_menu() {
      $items['user/%user/yourpage'] = array(
        'title' => t('My Tab'),
        'type' => MENU_LOCAL_TASK,
        'page callback' => 'yourmodule_page', //your module page should be a function
        //'page arguments'
      );
      return $items;
    }

function yourmodule_page()
{
   $uid = arg(1);
   $user = user_load($uid);
   //use user to get particular content belonging to them
   //return content
}


can register user control one page How can I make registered user take control (Edit/View/Delete) a piece of content type; a specific page for example. is that even possible?

First decide if this will be role based or user based. If it is Role based you can use the default permission system in Drupal.

If you want it per user consider using Content Access Module in conjunciton with ACL module