How to fix “Cannot read property 'icons' of null” error? First of all, I'd like to mention this answer is not related, I'm using Drupal 8.6.1.

I'm trying to create a CKEditor plugin with a new button. In the /admin/config/content page I get the error but the button appears well:

However when I go to /node/add/article page, I get the error and there is a display issue on CKEditor windows:

Clearing the cache does not change anything.
The error does not appear anymore when I uninstall my custom D8 module.

modules/custom/inline_comment/js/plugins/inline_comment/plugin.js

CKEDITOR.plugins.add('comment', {

    icons: 'comment',

    // The plugin initialization logic goes inside this method.
    init: function (editor) {
        // Define the editor command that add a comment.
        editor.addCommand('comment', {
            // Define the function that will be fired when the command is executed.
            exec: function (editor) {
                ...
            }
        });

        // Create the toolbar button that executes the above command.
        editor.ui.addButton('Comment', {
            label: 'Add comment',
            command: 'comment',
            toolbar: 'insert'
        });

modules/custom/inline_comment/src/Plugin/CKEditorPlugin/InlineComment.php

namespace Drupal\inline_comment\Plugin\CKEditorPlugin;

use Drupal\ckeditor\CKEditorPluginBase;
use Drupal\ckeditor\CKEditorPluginConfigurableInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\editor\Entity\Editor;

/**
 * Defines the "inline_comment" plugin.
 *
 * @CKEditorPlugin(
 *   id = "inline_comment",
 *   label = @Translation("CKEditor Inline Comment")
 * )
 */
class InlineComment extends CKEditorPluginBase implements CKEditorPluginConfigurableInterface {

  public function getFile() {
    return drupal_get_path('module', 'inline_comment') . '/js/plugins/inline_comment/plugin.js';
  }

  public function getButtons() {
    return [
      'Comment' => [
        'label' => t('Linkit'),
        'image' => drupal_get_path('module', 'inline_comment') . '/js/plugins/inline_comment/icons/comment.png',
      ],
    ];
  }

The location of the icon is: modules/custom/inline_comment/js/plugins/inline_comment/icons/comment.png

To anyone who is running into this issue:

 * Defines the "inline_comment" plugin.
 *
 * @CKEditorPlugin(
 *   id = "machine_name_that_must_match_with_icons",
 *   label = @Translation("CKEditor Inline Comment")
 * )
 */

and

getButtons() must return the same ID.

Annotation is new to me and I am sure it's not new to anyone else who are Drupal 8 developers but it might help someone who is new/still learning about how Drupal 8 works.

https://www.drupal.org/docs/8/api/plugin-api/annotations-based-plugins


How to convert Rules 'text' data type to 'text_formatted' type? I am working with Rules to set a node's body. Based on the data selector, the node body requires a text_formatted type as input.

Currently, my custom event only provides a plain 'text' Rules data type. Is there a way I can programmatically convert the plain text to text_formatted? And when and where should it happen?

I tried fixing this myself but I'm not sure if this is the best.

I took a peek at entity/includes/entity.property.inc and found the definition of entity_property_text_formatted_info() enough for me to define it properly.

I simply wrapped the plain 'text' with an array definition of a

    $text_formatted = array('value' => $text_plain,
                            'summary' => $text_plain,
                            'format' => 'full_html');

And fed $text_formatted to the event invoke call.


How do I customize the Fivestar module? I need to customize part of the Fivestar module's output, so that I am able to assign points ( e.g. 1, 2, 3, 4, 5).

I want the module to sum up and display the total points received by the content or user, and I want to use my own icons in the widgets.

Is this possible?

I am using Drupal 7.

Your first two items are settings that can be configured on the Fivestar CCK field's display options. You should read through the Fivestar Documentation thoroughly for instructions on how to set up a rating system.

If you want to use star icons of your own, you can simply override the styling of the Fivestar widget in your theme using CSS. However, if you want to create a star set that can be easily reused across sites, you can follow the instructions for creating a fivestar widget set


Should I translate string inside a Unit test? I have a Unit test where I need to print a string so I decide to use the t() function to translate it:

$this->assertTrue(is_numeric($expected), t('Parameter is numeric.'));

But the problem is that in the Unit test the t() function is not available. So I decide to check a similar Unit test in core (SortArrayTest) and the test don't translate the string:

$this->assertTrue(is_numeric($expected) && is_numeric($result), 'Parameters are numeric.');

I know that at this moment Drupal don't have integration with the Unit test from the UI, but this can be possible in future, so:

Should I translate string inside a Unit test? If the answer is Yes, How I can do it?

No, you should not. An assertion message is basically on the same level as a code comment, you're not translating that either.

We used to do that in core, also because it was all Simpletest then and the messages were shown in the UI, so an argument could be made that should be translatable. But we did massive patches to get rid of that, it just adds more complexity without any additional benefit.


Organic Groups - define content type to be of Group type I am using the Organic Groups module and am following the readme file. I am on step 2 and already struggling...

Create a new content type via admin/structure/types/add. Call it "Group", and
   define it to be of Group type.

How do I define it to be of Group type?

I have enabled the following modules:
Entity Reference    7.x-1.0
Organic groups  7.x-2.0
Organic groups access control   7.x-2.0
Organic groups context  7.x-2.0
Organic groups field access 7.x-2.0

On the create content type page you should have a vertical tab named Organic Groups. If this tab is missing, make sure you have enabled the Organic groups UI module. Clicking the Organic Groups tab reveals a couple of check boxes. Check the one for Group and hit save to make this content type a group which you can associate content with.

The other check box Group content defines that the content type can be posted into a group, i.e associated with the group you previously created.

To get you started you can also enable the OG example module.

The above is mainly for OG 7.2.


Add Custom Bulk operations to an existing Views I am creating a custom bulk operation using hook_action_info and I can see that the operation is created successfully. But however, I want to add this to an existing views. I can do this using Views UI with editing the view and editing "Selected bulk operations". So there I can select the custom operation that I have written.

So far doing this works for me but I want to automate this one. So once I enable my module with this custom operation I need to add this custom bulk operation to the existing view's "Selected bulk operations".

Is there any hooks or alters that do this?

hook_views_default_views_alter() is the sauce you're after


Changing menu paths for existing nodes in Drupal 7 So I have created around 100 articles of a specific content type and provided all of them a menu path under a specific menu.

Now the requirement is to alter these menu paths and give these nodes a new menu path under another menu. The longer and obvious way to go about doing this is to edit each of these content types manually and then edit the menu path to edit and point it to the new menu. This is a painstaking procedure that shall consume time. I am sure there are alternatives such as a Drupal module that let's you mass alter menu paths for a specific content type?

Alternately, is there a way for me to get into the drupal database and find out where these menu paths for a specific node/content type are stored? And I can simply execute a query that goes in and changes that?

Thanks!

Take a look at the Pathauto module. You can configure it to create paths automatically with a given pattern for individual content types. It also has options to bulk delete and update existing paths.


Choose multiple products with Commerce product bundle module I'm testing Commerce product bundle module to achieve my requirements. Is it possible to choose multiple products for the product reference of the product bundle ?

I created a product type with a product reference field, but in the node view I can only choose one product from a select box. I want to choose multiple products with chekboxes. Is that possible ? Where it can be configured ?

It's not possible, I've had to developed my own module to allow to choose the products contained in the bundle.

I created a product reference field in the product, from that set of products the user can choose his bundle.
I created a product reference field in the list_item type, where store which products has selected the user.

My module makes possible to show as I want the products in the product display and add to the cart


How to create a node and populate its fields with info from a completed goal? I need to create a node and populate its fields with data from a completed Goal (implemented via the Goals module) using Rules. The completed Goal info is fetched using the method from the question about "How to fetch the completed goal as an entity with the Rules module?".

The tokens are available for message display action and also for the node title, but I can't use them for any other fields for some reason. How can I use these tokens to populate the other node fields?

To populate some fields of the node to be created using some of the fields of the completed Goal, you need to make those fields (of the Goal) available as row variables in the Views loop of the rule you're using.

Have a look at this improved version of my rule that was included in my answer to your question about "How to fetch the completed goal as an entity with the Rules module?":

{ "rules_create_node_with_details_about_completed_goal" : {
    "LABEL" : "Create a node with details about completed goal",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "goals" ],
    "REQUIRES" : [ "rules", "goals" ],
    "ON" : { "goal_awarded" : [] },
    "DO" : [
      { "VIEW LOOP" : {
          "VIEW" : "goals_info_about_completed_goals",
          "DISPLAY" : "views_rules_1",
          "USING" : { "goal_completed_by_uid" : [ "awarded-user:uid" ] },
          "ROW VARIABLES" : {
            "goal_title" : { "goal_title" : "Title" },
            "goal_id" : { "goal_id" : "Goal ID" },
            "goal_userpoints" : { "goal_userpoints" : "User Points" },
            "field_goal_category" : { "field_goal_category" : "Goal Category" },
            "field_goal_level" : { "field_goal_level" : "Goal Level" }
          },
          "DO" : [
            { "entity_fetch" : {
                "USING" : { "type" : "goal", "id" : [ "goal-id" ] },
                "PROVIDE" : { "entity_fetched" : { "goal_completed" : "Completed goal" } }
              }
            },
            { "drupal_message" : { "message" : "Details about completed goal:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- Goal ID: [goal-completed:goal-id]\u003Cbr \/\u003E\r\n- Goal Title: [goal-completed:title]\u003Cbr \/\u003E\r\n- Goal Category: [goal-completed:field_goal_category]\u003Cbr \/\u003E\r\n- Goal Level: [goal-completed:field_goal_level]\u003Cbr \/\u003E" } },
            { "entity_create" : {
                "USING" : {
                  "type" : "node",
                  "param_type" : "article",
                  "param_title" : "[goal-completed:title]",
                  "param_author" : [ "awarded-user" ]
                },
                "PROVIDE" : { "entity_created" : { "node_created" : "Created entity" } }
              }
            },
            { "data_set" : {
                "data" : [ "node-created:field-free-format-text" ],
                "value" : "Goal category = [field-goal-category:value] \/ Goal level = [field-goal-level:value]"
              }
            },
            { "data_set" : {
                "data" : [ "node-created:field-free-format-nr" ],
                "value" : [ "goal-userpoints" ]
              }
            },
            { "entity_save" : { "data" : [ "node-created" ], "immediate" : "1" } }
          ]
        }
      }
    ]
  }
}

Some more details about the improvements in the above rule:

Note these additional row variables I added (in the Views loop), i.e.:

User Points (goal_userpoints), one of the fields that come with the Goals module.
Goal Category (field_goal_category), a custom field I added to my Goals entity (a single value text field, with values such as Contribution, Participation, Moderation, Privilege).
Goal Level (field_goal_level), a custom field I added to my Goals entity (a single value text field, with values such as Bronze, Silver, Gold).

After I added the extra Rules Action "Create a new entity" (to create the new node), I added these extra Rules Actions to set the values of some of the fields for the node to be created (= node-created):

node-created:field-free-format-text (of type text) is assigned the value of Goal category = [field-goal-category:value] / Goal level = [field-goal-level:value] (using 2 of the row variables I added in my view).
node-created:field-free-format-nr (of type integer) is assigned the value of goal-userpoints (using 1 of the row variables I added in my view).

With the above in mind, I think the real answer to your question (= "... I can't use them for any other fields for some reason") is that you need to pass the values of the fields you want to use as row variables also (and make sure the data types of those fields you pass along in your view are also matching with the node's field in which you want to use them).

BTW, make sure to understand the difference between:

"Goal completed by user", which is specific to a single user who completed a goal.
The actual configuration of a "Goal" itself, with fields such as User Points to be granted, or custom fields such as "Level" and "Category", which is identical for all users (and only changes if you change the configuration of a goal).


Does extending a class include the namespace of the extended class? For the following example, does ColourSprayTrap:timer() collide with the timer() function that exists in the weapons module?
More generally, does a namespace need to be re-declared for a class that extends a class with a namespace?

If I have a function declared somewhere in the code.

/* In weapons module. */
function timer() { /* Function definition. */ }

I have a class with a namespace.

/* In traps module */
namespace Traps;

class Trap { /* Some class definition. */ }

I extend that class.

class ColourSprayTrap extends Trap {
/* Start of class defnition. */
  public function timer($time) {
    /* Function defnition. */
  }
/* Rest of class defnition. */

To answer the question in the title: no, extending a class does not inherit the namespace of the extended class.

Your class namespace must be declared for each class or your class will be placed in the global namespace.

A little bit more on namespaces since if you don't declare one your code will be placed in the global namespace. Since PHP 5.3 if you don't declare a namespace then the class will belong to the global namespace. From the manual here:

  Without any namespace definition, all class and function definitions are placed into the global space - as it was in PHP before namespaces were supported. Prefixing a name with \ will specify that the name is required from the global space even in the context of the namespace.

As this applies to you, if you don't put a class in a namespace it will simply belong to the global namespace thus it wouldn't clash with a class with the same name in another namespace.

In general, functions without a class won't interfere with functions with the same name in a class. The reason being is that you need a class object to call a function declared inside a class.


How to remove paragraph tag from ckeditor? When we insert content into ckeditor field,suppose we write single line of text into ckeditor without any html tag, why its wrapping paragraph  tag automatically around the text .

I need to remove this paragraph tag because its breaking my page's structure.

In Drupal 8, you may need to implement hook_editor_js_settings_alter and set config.autoParagraph to false, as referenced here: CKEDITOR.config.autoParagraph

/**
 * Implements hook_editor_js_settings_alter().
 */
function MODULE_editor_js_settings_alter(array &$settings) {
  foreach ($settings['editor']['formats'] as $name => $value) {
    $settings['editor']['formats'][$name]['editorSettings']['autoParagraph'] = FALSE;
  }
}


How cache tables are different from other normal tables in database? I want to know, when all the cache tables are stored in database, then whats the logic behind keeping any data to cache, because whenever we query cache, it again hits the database, same as other normal tables exists in database do.

How cache tables are different from other normal tables in database? How cache boost performance when all cache tables also exists in database?

Cache tables contain the results of expensive queries. Often more than one query in a single cache row.

As a contrived example, take a node. When you load a node, you have to join in all of the single field tables containing it's data, plus make a bunch of separate queries for extra data. That's a lot of db load.

Wouldn't it be quicker if you could make just one, single, light query and get all of that information in one go?

That's what cache bins are for. There may well be scenarios where querying from cache is as/more expensive than the original operation, but they'd be rare.

Also don't forget your cache doesn't have to be in the database, you can get considerable improvements moving it into memory.


Linking to front page with current selected language <?php print $base_path; ?> Links to the front page with default language, So If site's default language is set to A and a user has selected language B, this code redirects user to the front page with language A.

Is there away to link to front page while keeping the current selected language?

Use the following code:

<?php print url('<front>', array('absolute' => TRUE)); ?>


How to limit the execution of a rule for sending an email to only run once in a day? I have a rule that sends an email out to subscribers on the 28th of each month. The rule is executed when cron is run, I have cron set to automatically run once a day.

I also use linkchecker, which uses cron to check the links on the site. Right now I have to remember on the 28th of the month not to run cron for the linkchecker, otherwise my subscribers will get multiple emails that day for each time cron was run.

How can I limit the rule to only run once in any specific day, so that I don't have the potential to accidentally run cron manually and spam my subscribers?

Have a look at the "Rules Once per Day" module. Here is how it works (as per the comment in issue 2495775, from the module owner):

You specify a trigger hour on the administration settings page for this module.
The Rule trigger will then run when cron tasks are first run after the start of that hour. The actual run time will depend on your cron task timings.

So this is another way to understand/Read this:

The "Event" will only be triggered when a cron job is run.
And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

With that, you should be able to adapt your "rule that sends an email" to run ... once a day, on any day, including the 28th of each month.


On Feed API, what does the setting "Delete news items older than:" mean? Using FeedAPI on a site I just started working on (but getting ready to get rid of it), and I don't understand this setting:

"Delete news items older than:"

Does that mean "delete unpublished items after a set time"? Or "delete published items we've turned into posts after a set time"? Or just "ignore items coming in from a given feed if they're older than this?"

Or something else altogether?

This setting does two things:

1) When reading from a feed, ignore items older than this setting.

2) On cron, delete all node feed items older than this setting.


How do I get the output of a single field? How do I get the output of a field of a node?
I have some weird subpage construct using entity references (one 'main' node and a few 'sub'-nodes).

Each of these nodes have a header image to be displayed above the content. What I am trying to do is for the sub-nodes to 'inherit' the header image of the main node.

I implemented hook_node_view and I have got the node, I just don't know how to build the renderable array for it.

function hook_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
  if($view_mode == 'full'){
    if((!isset($build['field_headerimage']) || !isset($build['field_headerimage'][0])) && $entity->hasField('field_location')){
      $location = $entity->get('field_location')->referencedEntities();
      if(is_array($location) && isset($location[0])) {
        $node = $location[0];
        dsm('yay, now what?');
        dsm($node->label());
      }
    }
  }
}

The answer to my own question seems to be like so:

$build['field_headerimage'] = $node->get('field_headerimage')->view();


installed drupal site locally but not working (XAMPP) I want to install the site from the server locally so I can test changes before performing them.

So:

I exported the database and installed it locally
I downloaded all the files that were inside the site root folder and put them in a root folder locally (but with another name)
I changed the parameter $db_url and $base_url

The problem is that the front page is shown correctly but when I click to go to another page from the menu it says:

[an error occurred while processing this directive] The requested URL was not found on this server. The link on the referring page seems to be wrong or outdated. Please inform the author of that page about the error. [an error occurred while processing this directive]

Anyone have any idea?

NOTE: I just noticed that the url is something like this: http://localhost/root//articles/article-one

Thank you

One reason for this can be 'the apache server's rewrite mod is not enabled'.

See if

  localhost/sitename/index.php?q=user/login

is working.

If that is working then try enabling Clean URL (sudo a2enmod rewrite for LAMP).

Few links that can be related to the problems.

http://drupal.org/node/1186762

http://drupal.org/node/333675


Where to write a jquery script for a registration form page which created using webform module in Drupal 7? I have created a registration form page using the webform module. The registration form page contains personal info and billing info groups with fisrtname, lastname, email, age fields and a check box saying "billing info same as personal info". Where should I write a jQuery script to put all the personal info in billing info fields when the check box is checked?

I have created a js folder/check_box.js file in the bartik theme folder which i am using
then made changes in bartik.info file as scripts[]=js/check_box.js
then added drupal_add_js in template.php
cleared all caches

but still I cannot execute my script which I have written for check box or the fields.

$("#checkbox_id").change(function() {
  if(this.checked){
    alert("checked");
    });
})(jQuery);

This is my code to check whether its working or not. Is it correct? If not please help me with the code.

First off, as rooby very accurately suggested in the comment section, you should not tamper with the Bartik theme directly. You have many possibilities on where to include a js script. You can read all of them in the relevant documentation in drupal.org.

The closest to what you describe is to subtheme Bartik and put all necessary js there, or even create a small custom module.

Apart from that, jQuery in Drupal uses the noconflict mode. Try to avoid the dollar sign but rather call jQuery. Although in your particular code should be ok as it is, there may be other instances in your script using $ that would prevent it from working. More on that here. Check your browser for js errors.

Last, there is no way for us to evaluate your jQuery code if it works properly or not as we do not have the produced HTML output nor the context of your provided js code.


How to set user search and filter preference on account registration I'm bulding a dating site, and I want users to have default search and filtering capabilities.

The field in question is gender.

I want users to be able to choose default search parameter to male or female. So when they access the view, it will only show them males or females, depending on their choice at registration and user account profile settings.

I'm pretty sure core functionality can do something like that, but I can't figure out what kind of settings to use...

I'm attaching the image to demonstrate what I am trying to acheive with an example from another website, the fields "I am a man" >> "I want to find a woman"

You need to use views global filter to achieve this functionality. What you set in profile2 field you will be get it globally in views too. In view you need to add only filter for that value.

Another way you can add relationship of user profile and add in contextual filer of logged in user value of interest in gender field.


Adding ASCII characters to HTML links in Drupal I've written the decimal HTML entry of the "Logical or" ASCII note in a menu-link and yet I don't see the character. What I do see is the decimal HTML entry... Why is that? Is this problem solvable without any modules? Thanks,

You can use the Menu HTML module for that.

It uses a bunch of alter hooks, which means you could theoretically reproduce the same functionality in a theme if you really want to. So yes, it's possible to solve without using a module per se.

Modules are the proper way to add such functionality, though, hacking this into a theme is bad application design in my opinion. Drupal is, intentionally, a modular system; don't be scared of installing modules to add functionality, that's what you're supposed to do :)


How do I make the file description field required? In Drupal 7, I need users to enter a file description, how do I make this field required?
Also on another note, I would love to make this field a select list, there's no clear way to do this aside writing a custom module. Any ideas?

Code snippet for making a file's description field required:

/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['field']['field_name'] == 'field_MYFIELD' && $context['instance']['widget']['type'] == 'file_generic') {
    $element_children = element_children($element, TRUE);
    foreach($element_children as $key) {
      $element[$key]['#process'][] = 'MYMODULE_file_field_description_required';
    }
  }
}

/**
 * Require description to be set.
 */
function MYMODULE_file_field_description_required($element, &$form_state, $form) {
  $element['description']['#required'] = TRUE;
  return $element;
}


Proper way to get the base path when including an image from a module? When using just drupal_get_path() to include an image from a module directory, this produces non-existent urls when using language prefixes.

I've seen a couple of modules prepend base_path() to deal with this, but on the api page for base_path() someone comments that you should use the DRUPAL_ROOT constant. What is the recommended way?

Drupal core uses file_create_url() for internal images like this (eg, the default favicon.ico handling in includes/theme.inc).

This ensures that hook_file_url_alter() gets called (the CDN module does this), that the basepath gets set, and that everything is escaped properly.

So, I would use

$path = drupal_get_path('module', 'mymodle');
$url = file_create_url($path . '/images/some.jpg');


How to enable module when there is a WSOD (blank page)? Use case: I enabled a module, without enabling the required module. I saved the configuration on the modules page and it showed me the following screen -

I clicked "Continue" and then I get the WSOD (blank page).

I added error reporting php code in my index.php in root directory. It showed a fatal error - Fatal error: Call to undefined function variable_realm_switch() in /mysite/sites/all/modules/i18n/i18n_variable/i18n_variable.module on line 54

I cannot go back to the admin pages to enable the required module, because of WSOD. Is there a way to enable the module from the code? I cannot delete the modules involved in this error, because I will end up losing the data associated with the modules.

Using phpMyAdmin or any other database management software (or via command line mysql if you are comfortable with that), find the name of the module you wish to enable or disable in the system table. Set the status for that module to 0 for disabled or 1 for enabled.

mysql command:

UPDATE  `database_name`.`system` SET  `status` =  '1' WHERE  `system`.`name` =  'module_name';

phpMyAdmin screenshot:

I also recommend installing Drush on your server. This will allow you to execute commands like enabling/disabling modules, clearing caches, etc. from the command line, which is very handy in situations where you cannot access the Drupal admin because of a WSOD.


How to Display Unique Values from database using db_select in Drupal i tried with following code but i cant get the attached output

$query = db_select('webform_submitted_data', 'u');
$query->fields('u', array('sid','nid','data'));
$query->condition('nid','49','=');
$results =$query->execute();

echo "
";
echo "
";
echo "Name ";
echo "Post ";
echo "
";
while($record = $results->fetchAssoc())
{
 $sid = $record['sid'];
 $nid = $record['nid'];
$submission = webform_get_submission($nid,$sid);
echo "
";
echo $submission->data[1][0];
echo $submission->data[2][0];
echo "
";
}
echo "
";
}

Try

$query = db_select('webform_submitted_data', 'u');
$query->fields('u', array('sid','nid')); $query->condition('nid','49','=');
$results =$query->distinct()->execute();

Api info about unique


How do I embed a view inside a node? In Drupal 6 a view can be embedded into a node as follows:

$viewName = 'LatestNews';
print views_embed_view($viewName);

This does not work for drupal 7.  What is the function to embed views in drupal 7?

In Drupal 7 you can use this code.

For a view page

print views_embed_view('name_of_view','page_1', $node->nid);

For a view block

print views_embed_view('faculty_core','block_1', $node->nid);


Node template suggestion stopped to work for new content types I experience the simmilar issue as asked here

I already have several template suggestions that are working properly following structure:

node--type.tpl.php

But for newly added content types, it does not work, whatever i do. I cleared cache, recreated content type, checked spelling.

How can i track in devel or in other way what is source of this error ?

This was due to the strange Caching issue, source of which is yet unknown to me. It may me somehow connected to APC caching, or to nodeaccess cache. I am not yet sure.

After nervous session of clearing different layers of cache, i somehow get it to work.


Display Content Type Field in region--footer.tpl.php First of all I am overriding the default footer template with my own using region--footer.tpl.php. In the footer I need to display the fields I have in a content type named 'footer'. Can anyone help me with this?

Like I said, fast and dirty:

$nid = XXX;
$node = node_load($nid);
print check_plain($node->field_name['und'][0]['value']);

Put this into your Template. I assume your field is not translated.


Translation of modules I am using Drupal 7.9 and Webform 3.15. I need to translate -select- option on top of list box. Also I have to translate in Captcha module (7.x-1.0-beta2), the text What code is in the image? and Enter the characters shown in the image. How can do this?

How can I translate modules to required language?

You have to switch on the Locale module, which is part of Drupal  core. There you can search for the strings you want to translate.

If you  want to translate an entire module from scratch, I suggest that you read about translation on drupal.org and make yourself familiar with the toolchain. It's fairly straightforward.


How do I exclude/blacklist admin paths? Is there still a way to exclude administrative paths from using the CDN module in Drupal 8?

It appears you have to use advanced mappings, but I don't understand how.

No, not currently. As the UI suggests, the complex mappings can be set in the module's install/config/cdn.settings.yml config file, but it only allows for segmenting traffic to different CDNs based their extension.

The FileUrlGenerator service object handling the file URL rewriting doesn't consider a path context while deciding when/when not to serve file from the CDN.

You could replace this service class via the ServiceModifierInterface and its ::alter() method with a custom service class that does consider the path context.


How can I have non-exact locations on a map? I'm using GMap to help users find other people in their area. But I'd like to let users have some privacy only making their city and zip code available in the map, but still have the full address in the database for mailing purposes. How can I do this? The position of the pin on the map should also be only based on city and zip, as obviously it could be pretty precise as to location.

For example, let's say the president registers on our site. He enters his full address, 1600 Pennsylvania Ave NW, Washington D.C., DC 20500. An administrator can now look that up and mail him our newsletter.

Another user in the D.C. area is looking for people to meet up with. They look and see a pin on the map for a user POTUS. The click on the pin and it only displays a partial address, Washington D.C., DC 20500. And the pin's location isn't exact, so the user can't tell from its placement the exact address of POTUS. But it is enough that the user knows they are nearby, so they send a user to user message to get in touch.

Any solutions for non-exact pin locations would be fine. If it was slightly randomized. Or perhaps all pins in a zip-code are grouped into one with a link for "# users in the 20500 area" which takes the user to a full list.

If this can be done with something other than GMap, that is fine.

I had a similar problem, and this is how I solved it:

Add another 'location' field to you content type; call it, e.g., 'public user location'.
Build up your custom module, and in the hook_form_alter() implementation, hide the new location field, so the user cant edit it.
Now you need to get the 'non-exact' location for the first location; I do this with a Google geocode.

It's up to you to do it via JavaScript when the first location is set (the way im doing it), or to do the geolocation when the form is submitted to 'manually' add the 'non-exact' location.

If you use a geocode on the partial address, Google Geocode will give you the coordinates in the middle of the area you searched.

Please note that, for more specific geocoding, you could even use the Geonames API.

If you choose the second way (create the 'non-exact' location when the form is submitted), maybe this can help you about the location creation: Creating nodes programmatically in Drupal (including cck and location fields).

As side note, I am not using the Gmap module anymore because my needs were a bit complex and were not fit by this module; if you'll find some trouble, I recommend you building your own small module using Google API v3.

This will let you, for example, show the 'public location' in the map with a circle around, as Google Latitude does.


How can we get Block Bundle Type for block in code? I am trying to override block content by using hook_preprocess_block(&$variables). I was expecting to find bundle type in $variable, but not getting anything related to this.

Here is kint display of $variable inside the function -

More Info - This is a block type (say content_slider) created from Drupal UI & a block (say content_slider_homepage) is added.

This is how I would do it:

use \Drupal\block_content\BlockContentInterface;

/**
 * Implements HOOK_preprocess_block().
 *
 * @param $variables
 */
function mymodule_preprocess_block(&$variables) {
  $content = $variables['elements']['content'];
  if (isset($content['#block_content']) && $content['#block_content'] instanceof BlockContentInterface) {

    if ($content['#block_content']->bundle() == 'xxx') {
      // ...
    }

  }
}


Restful web services Documentation I am looking for complete and updated documentation for Restful web services.

For example, for the user login, we have to post the following data.

POST: http://example.com/user/login?_format=json
Content-type: application/json
Data: { "name": "admin", "pass": "myPassword" }
Response: 200 OK

This will properly log in via cookie authentication, and return a result similar to this.

    {
      "current_user": {
        "uid":"1",
        "roles":["authenticated"],
        "name":"admin"
      },
      "csrf_token":"abc123",
      "logout_token":"def456"
    }

How do I log out the user I just logged in with?

I found RESTful Web Services module overview, but I still don't understand how to log out.

Using the following request gets back a 403 Forbidden error.

POST: http://example.com/user/logout?_format=json
Content-type: application/json
Data: { "name": "admin" }

What am I missing?

As per documentation you can do like this.

Logout

GET http://example.com/user/logout
Content-type: text/html
200 - OK

Note: Do not pass "?_format=json" it is not accepting.


Problem file to import not found or unreadable ../../variables/_colors.scss I'm currently using Omega 4 with Sass, compass, breakpoint, singularity.

When I run the command drush omega-guard, I have the error below.
Any body know what could be the problem.

It's like there is a problem with globbing.

I'am on Ubuntu 14.04

Thanks a lot

error sass/layouts/header/header.layout.scss (Line 1 of sass/variables/**/*: File to import not found or unreadable: ../../variables/_colors.scss.
    Load paths:
      /var/www/vhosts/nexera.linuxlocal.com/sites/all/themes/nexera/sass
      /home/beach/.rvm/gems/ruby-2.1.2/gems/compass-0.12.6/frameworks/blueprint/stylesheets
      /home/beach/.rvm/gems/ruby-2.1.2/gems/compass-0.12.6/frameworks/compass/stylesheets
      /home/beach/.rvm/gems/ruby-2.1.2/gems/compass-normalize-1.5/stylesheets
      /home/beach/.rvm/gems/ruby-2.1.2/gems/compass-rgbapng-0.2.1/lib/stylesheets
      /home/beach/.rvm/gems/ruby-2.1.2/gems/breakpoint-2.0.7/stylesheets
      /home/beach/.rvm/gems/ruby-2.1.2/gems/singularitygs-1.1.2/stylesheets
      /home/beach/.rvm/gems/ruby-2.1.2/gems/compass-blend-modes-0.0.2/stylesheets
      /home/beach/.rvm/gems/ruby-2.1.2/gems/color-schemer-0.2.8/stylesheets
      /home/beach/.rvm/gems/ruby-2.1.2/gems/toolkit-1.3.8/stylesheets
      /home/beach/.rvm/gems/ruby-2.1.2/gems/susy-1.0.9/sass
      /var/www/vhosts/nexera.linuxlocal.com/sites/all/themes/nexera/sass
      Compass::SpriteImporter
      Sass::Globbing::Importer)

Change gem 'sass-globbing' to gem 'sass-globbing', '1.1.0' in your Gemfile and then run bundle install


How to add a description to the Goals used by the Goals module? I'm using the Goals module in combination with Views. I'm now displaying all the Goals that were completed by a user on the profile pages in a table that contains the Goals' image and title.

Now, I'd like to explain a bit more what the user exactly achieved by adding an extra column with a description. Adding a direct description to the Goals would be a perfect solution, but as this isn't provided by the module's maintainers, I opened a feature request.

I know Drupal Answers isn't built to provide patches (although they're very welcome), so I'd like to ask whether there's perhaps another solution for my problem.

Goals used by the Goals module are implemented using fieldable entities. So you can customize goals by adding your own fields, such as:

descriptions.
images.
links to external resources.
etc.

Head over to its video tutorial, and have a look at what is shown starting from around 4:00 where you can see the typical tabs for Goals, such as:

Manage Fields.
Manage display.

For more details, refer to its Community Documentation also.

Disclosure: I'm the maintainer of this module.


How to make filter criteria fieldset in a view to be collapsible by clicking on a link using tpl file overriding default file? I am trying to create a collapsible fieldset of filter criteria on click of a link
the code I tried is as follows:
    ';
    ?>

<fieldset class="collapsible collapsed">
<legend class="collapse-processed">
Error : Uncaught TypeError: Object [object Object] has no method 'drupalGetSummary' jquery.min.js:16
Edit Search Criteria
</legend>
<fieldset>

But when I click on the link I dont get the collapsed or collapsible feature

The error I am getting is as follows:
Error : Uncaught TypeError: Object [object Object] has no method 'drupalGetSummary' jquery.min.js:16

In the resources of the page the collapse.js is present which indicates that the js  file is loaded.

After updating the jquery version from 1.5 to 1.7 the old error disappears and new error is displayed as follows: Uncaught TypeError: Object [object Object] has no method 'drupalGetSummary' collapse.js:70

I got the above working by writing a function in the module as shown in the link

/**
 * Implements hook_preprocess_views_view().
 */
function my_module_preprocess_views_view(&$vars) {
  if ($vars['view']->name === 'my_view') {
    // Wrap exposed filters in a fieldset.
    if ($vars['exposed']) {
      drupal_add_js('misc/form.js');
      drupal_add_js('misc/collapse.js');
      // Default collapsed
      $collapsed = TRUE;
      $class = array('collapsible', 'collapsed');
      if (count($_GET) > 1){
        // assume other get vars are exposed filters, so expand fieldset
        // to show applied filters
        $collapsed = FALSE;

    $class = array('collapsible');
  }
  $fieldset['element'] = array(
    '#title' => 'Refine your search',
    '#collapsible' => TRUE,
    '#collapsed' => $collapsed,
    '#attributes' => array('class' => $class),
    '#children' => $vars['exposed'],
  );
  $vars['exposed'] = theme('fieldset', $fieldset);
}
  }
}


Can you set the directory from which the Media module populates its Library tab? I would like to know if it is possible to set the directory from which the Media module populates its Library tab in the Media Browser.

For instance, when the newest version of the Media module is installed, the directory its Library tab is populated from seems to be /sites/default/files/field/image/. If another directory is already created on a server which contains a set of images I would like to choose from, is it possible to modify the Media module to look in that directory?

I've spent a fair amount of time digging through the module code and haven't found where the directory default is being set. Has anyone ever attempted this?

The Media Browser does not work with a physical path, but with the file managed table, and Drupal file system uses the uri of the file to get to the actual file.

Go to the views settings page admin/structure/views/settings and turn on 'Show the SQL query'.

Then open up the media browser and look at the SQL query. It starts of with

SELECT file_managed.timestamp AS file_managed_timestamp, file_managed.fid AS fid, SUM(file_usage.count) AS file_usage_count
FROM
{file_managed} file_managed

which means it is using the file_managed table as its base. That comes from the file module in Core. Looking at that table definition in PHPMyAdmin for instance will reveal a fid as the primary identifier, a filename, a uri, filemime and some other fields. The uri is the important part as it tells Drupal how to get to files. The uri is prefixed by the stream wrapper (PHP classes that provide a common interface for getting to resources) and the two common Drupal ones are public:// and private://.

The media module already provides a remote internet sources wrapper, and Remote stream wrapper module provides a Remote Url plugin for the media module.

You can also write your own. Writing stream wrappers


How to use set_items_per_page? Background

I'm having a go at porting the JavaScript random views module from 6 to 7.

Problem

One of functions I think is intended to override the default pager value to load extra rows per page. (i.e. pager says load 8. This overrides it and says load 20).

To accomplish this it uses hook_views_pre_execute

function views_javascript_random_views_pre_execute(&$view) {
  .....

  // Here it saves the current settings of the pager for use later
  .....

  // Set new settings
  $view->set_items_per_page($sorts['js_random']['client_node_count']);
}

Unfortunately the set_items_per_page function doesn't seem to work. While it still sets:

$view->items_per_page

This then seems to have no effect on how many rows are then loaded in:

function views_javascript_random_preprocess (&$vars, $hook) {
   ....
   dpm($vars);
}

In $vars->rows, it still only loads the number of rows set by the pager (i.e. 8 not 20)

The API function definitely still works in 7. Could someone explain why it's not working correctly in this case?

I have successfully used $view->set_items_per_page() in hook_views_pre_build(). The problem might be that in hook_views_pre_execute() the pager settings have already been built, so you might have to update those as well, with something like $view->display_handler->get_plugin('pager')->get_items_per_page().


How to add client side validation to form via FAPI? I can't figure what to add Client Side Validation for form fields.

'#element_validate' => array('_file_generic_settings_max_filesize'),

I also don't know which value to put for different types of validation such as digit, email etc.
    '#element_validate' => 'email',

Also if I use this documentation https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7.x/#element_validate:

'#element_validate' => array('email'),

it states that it needs to be string not an array.

And after all this documentation doesn't state that how to add validation instead just creating own validation:
https://www.drupal.org/node/1324788

Solution was to add following for each integer field with form alter:

['#rules'] = array('digit');

And perhaps it was also needed to set 'views_exposed_filters' as a custom form for validation in the settings of Client Side Validation module.


Ajax form - Multiple select elements I have a form with multiple select elements with an #ajax callback on change. The ajax is working but the problem is that I can't figure out how to find which select has triggered the ajax. All ajax callbacks point to the same function.

Any ideas on how to find which select was changed?

Thanks.

You should be able to make the distinction by checking $form_state['triggering_element']:

switch ($form_state['triggering_element']['#name']) {
  case 'select1':
    // Do something
    break;
  case 'select2':
    // Do something
    break;
  // ...
}


Load just one field from node I have x nodes with field named "thefield". My script is checking "thefield" and if he does so the right value is updated.

How can i get from node just one field for check and didnt load full entity (node_load)?

I would use a db_query to find all nodes that that field appears on and then update them with a node_load here is the code:

$result = db_query('SELECT f.entity_id FROM {field_data_field_thefield} f');
foreach ($result as $record) {
    $node = node_load($record->entity_id);
    // update node
}


Add weight parameter in a custom module I created a content type and it has many nodes. And I wrote a custom module to show nodes on the front page.

My nodes order:

 $themeurl = '/drupal/'.path_to_theme().'/images';
    $sql = "SELECT * FROM `node`
            LEFT JOIN `field_data_field_anasayfa_catwalk` ON `field_data_field_anasayfa_catwalk`.`entity_id` = `node`.`nid`
            WHERE type = 'designers_albums'
            AND `node`.`status` = 1
            AND `node`.`language` = '".$language->language."'
            AND `field_data_field_anasayfa_catwalk`.`field_anasayfa_catwalk_value` = 1
            ORDER BY `node`.`created` ASC";

But now, I installed the Weight module and want to sort by weight. How can I change this option?
Thank you.

You'll just have to add another JOIN to the weight_weights table on your query.

The weight_weights table stores the entity_id, entity_type and the weight value.

EDITED

Here goes an example:

$sql = "SELECT * FROM `node`
        LEFT JOIN `field_data_field_anasayfa_catwalk` ON `field_data_field_anasayfa_catwalk`.`entity_id` = `node`.`nid`
        LEFT JOIN `weight_weights` ON `weight_weights`.`entity_id` = `node`.`nid`
        WHERE type = 'designers_albums'
        AND `node`.`status` = 1
        AND `node`.`language` = '".$language->language."'
        AND `field_data_field_anasayfa_catwalk`.`field_anasayfa_catwalk_value` = 1
        ORDER BY `weight_weights`.`weight` ASC";


Using panels and panelizer with i18n I'm building a multilingual site with 4 different languages, using panels and panelizer, but am struggling to see how to have different panels for different languages.

The site has to be content-manageable by the client, so I need to provide panels that can be translated by them.

I've tried 2 routes - first of all using the i18n_panels submodule in panels. The readme.txt file suggests that I can create a custom pane which can be translated, which would be great, but it isn't very clear how to do this. The example doesn't work.

I've also tried adding a pane for each language and using visibility rules based on the node language. This doesn't work either.

Does anyone have an example of a custom pane that is multilingual using i18n_panels, or another way of achieving the same effect?

I couldn't get the i18n_panels module to work, but the Multilingual panels module works a treat.

https://www.drupal.org/project/mlpanels


Delete selected comments of a particular node? Is there any module in Drupal 7 for deleting selected comments at one go for a particular node?

You can do this with Views Bulk Operation module. Follow the steps:

Install Views and Views Bulk Operation modules and enable these modules.
Create a View of Type "Comment".
Change the Views Format show from 'Comment' to 'Fields' under Format section.
Change the Views Format from 'Unformatted list' to 'Table'.
Add Bulk Operation:Comment, Comment:Title and Content:title fields under Fields section.
In step 5 When you chose Bulk Operation: Comment select Delete Item under SELECTED BULK OPERATIONS setting.
Add Content: Title filter criteria and expose this filter So that you can filter comments of a particular node.


How to get drush to list ONLY parent folders on module list command? I use this command to get a list of contrib enabled modules:

drush pm-list --type=module --status=enabled --no-core --format=list

Problem is, it also lists submodules, for example:

admin_menu
admin_menu_toolbar

So if I use this to reinstall the modules on another site:

Drush dl admin_menu admin_menu_toolbar

It causes errors. So I need to drush only:

Drush dl admin_menu

So how can I get the list of ONLY parent modules?

My goal is to get drush to display list of modules on the source site, but only folder names, not subfolders

You are looking for the pm-projectinfo command.  See: http://drushcommands.com/drush-8x/pm/pm-projectinfo/

In Drupal, "projects" contain "extensions". An "extension" can be either a module or a theme.  drush pm-list will show a list of modules and themes; drush pm-projectinfo shows a list of projects.

UPDATE: If you want to convert an existing site into a reproducible, buildable script, you might also be interested in using Composer.  See https://github.com/drupal-composer/drupal-project and https://www.drupal.org/project/composer_generate


Non-CRUD resource action with Drupal 7 / Services 3 I can't get this simple example working with a custom action.

I had to move it form here How can I create a simple non-CRUD resource action with Drupal 7 / Services 3? to an own question.

The example looks like this for CRUD retrieve:

function mymod_services_resources() {
 $api = array(
   'test' => array(
     'operations' => array(
       'retrieve' => array(
         'help' => 'Drupal 7 Services 3 test',
         'callback' => '_mymod_test',
         'access callback' => 'user_access',
         'access arguments' => array('access content'),
         'access arguments append' => FALSE,
         'args' => array(
           array(
             'name' => 'fn',
             'type' => 'string',
             'description' => 'Function to perform',
             'source' => array('path' => '0'),
             'optional' => TRUE,
             'default' => '0',
           ),
         ),
       ),
     ),
   ),
 );
  return $api;
}

function _mymod_test($fn) {
  return "Test is working";
}

This works fine and returns for http://myhost.dev/endpoint/test/retrieve

Test is working

But when i try a custom action like this

function mymod_services_resources() {
 $api = array(
   'test' => array(
     'actions' => array(
       'custom' => array(
         'help' => 'Drupal 7 Services 3 test',
         'callback' => '_mymod_test',
         'access callback' => 'user_access',
         'access arguments' => array('access content'),
         'access arguments append' => FALSE,
         'args' => array(
           array(
             'name' => 'fn',
             'type' => 'string',
             'description' => 'Function to perform',
             'source' => array('path' => '0'),
             'optional' => TRUE,
             'default' => '0',
           ),
         ),
       ),
     ),
   ),
 );
  return $api;
}

function _mymod_test($fn) {
  return "Test is working";
}

http://myhost.dev/endpoint/test/custom returns just a 404

When i try it like this

function mymod_services_resources() {
 $api = array(
     'actions' => array(
       'custom' => array(
       ...

It is not shown in the Services list.

@Clive
Yes, i tried to GET that resource. But when i try to POST

curl -i -X POST --header "X-CSRFToken: p2BMMItuM6QD9HvdPulxS5IBnXDBnczT46VoLLSqJLM" http://myhost.dev/endpoint/test/custom

i get a
    HTTP/1.1 404 Not found: Could not find the controller.

But this solution - see the comments new user have to last 8 hours to answer own question :)
yields to an other question.

How can i get the whole path, not just index 0
    'source' => array('path' => '0'),

I like to get all path segments after the controller. in my case

myhost.dev/endpoint/test/foo/bar/1/2/3

i liked to get foo/bar/1/2/3 with index 0 i can get just foo.

I got it. I don't have to use myhost.dev/endpoint/test/retrieve in the first example. It is posible to use myhost.dev/endpoint/test/Whateveryouwant. So i understand, i can use the retrieve action and it is not mandatory part of the resource path.


Add a popup text link to a specific "create content" page I've looked everywhere and can't find an answer to my problem. I'm trying to do something that seems like it would be relatively simple, but I keep coming up empty: add a pop-up text link to the "node/add/content" form for just one of my content types.

I've figured out how to use the popup module (https://www.drupal.org/project/popup) to make pop-up text elements using blocks, but that won't help me when it comes to the add content page. The idea here is to give users instructions on how to fill out the "add content" form on the form itself. Since I'm using an overlay screen, it makes the most sense to include the link directly on the form itself.

I've seen many places where people suggest a variation on this: Base tpl file for "add content" page?. In other words, copying the node file contents to a new file called page--node--add--my-content-type.tpl.php in the base theme directory, but this has no effect for me.

Also, I've tried to use the Theme Developer module to figure out what the page is called, but enabling this module just breaks the form for me, rendering Devel useless.

Do I need to somehow manipulate the template.php file in my theme? Any direction anyone can give me would be great. Thank you in advance.

Have you considered hook_form_alter and the usage of either of these 2 modules:

BeautyTips, which allows:

  The Beautytips module provides ballon-help style tooltips for any page
  element by integrating the BeautyTips jQuery Tooltip plugin by Jeff
  Robbins with Drupal. It provides an API for adding custom beautytips
  as well as some built-in features. Admins can enable rollover
  balloon-help style tooltips for text fields within forms. It also
  supplies hover tips for Drupal help links and advanced help links.

  Most importantly, it allows developers to add their own custom
  beautytips popups to their site without having to delve into jQuery.

Guided Tours, which allows:

  Gives content creators the ability to build tours on their sites which
  allow users to better understand complex workflows on the site and be
  guided through those workflows. The main advantage of this module is
  that you can build tours leading the user through multiple different
  pages with multiple tooltips on one page/step. This module uses qTip
  and jgrowl_d7.

EDIT

As an example for /node/add/page the recipe would be:

Implement hook_form_alter in a custom module for this pages $form.
For any form item of the form you want to add a beauty tip for add a class so you can find it easily using beauty tips.
For instance then at the end of your hook_form_alter function you then can add the beauty tips calls following the documentation. You can use your helper CSS classes to make your life somewhat easier.
repeat (1) thru (3) as necessary ...

# in file mymodule.module

// This is step #1.
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  // This is step #1. Or target 'page_node_form', or use a Regex for certain forms.
  if ($form_id == 'student_blog_node_form') {
    // This is step #2. See https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#attributes
    $form['field_survey_program']['#attributes']['class'][] = 'my-beauty-tip';
  }

  // This is step #3. See: http://cgit.drupalcode.org/beautytips/tree/README.txt?id=HEAD
  $options['bt_drupal_help_page'] = array(
      // what selects the content from the page using css selectors.
      'cssSelect' => '.my-beauty-tip',
      // what to show in the tooltip.
      'text' => 'This is my tooltip!',
      'trigger' => array(0 => 'mouseover', 1 => 'click'),
      'width' => 350,
    );
    beautytips_add_beautytips($options);
}


How to store form in order I have customers filling out an entry form before sending them to checkout.  Is it possible to store, or serialize, the $form_state array in the order?  There is a 'data' field in the order.  Is it simple as me calling:

$order->data = serialize($form_state);
commerce_order_save($order);

EDIT:

The data field in the order is an array that gets serialized.  So, it looks like I can do:

$order->data['myform'] = $form_state;

There is the data attribute on entities, which you cannot access through Entity Metadata Wrappers (per previous answer.)

Do you need the full form state or just values? Also, you do not need to serialize the data, as the entity controller will do this for you.

I would do something like:

form_state_values_clean($form_state);
$order->data['myform_values'] = $form_state['values'];

form_state_values_clean() will remove build IDs and such.


Programatically untick generate automatic URL alias for new node I am creating a new node and then adding a new menu link. I have the code to correctly add the new node and menu link (below).

$node = Node::create([
              'type' => 'standard_page',
              'langcode' => 'en',
              'created' => REQUEST_TIME,
              'changed' => REQUEST_TIME,
              'uid' => 1,
              'title' => 'new_node',
              'body' => [
                'summary' => 'new_node',
                'value' => 'new_node',
                'format' => 'full_html',
              ]
          ]);

  $node->save();

$source = '/node/' . $node->get('nid')->value;  \Drupal::service('path.alias_storage')->save($source, '/new_node', 'en');

$link = MenuLinkContent::create([
      'title'      => $title,
      'link'       => ['uri' => 'internal:/new_node'],
      'menu_name'  => 'main',
      'weight'     => 10,
    ]);

The problem is that when I go to edit the node, "generate automatic url alias" is always ticked. So whenever I go to update the node, it destroys the alias that I have already created.

I have tried the following code.

$node->path['pathauto'] = FALSE;
$node->save();

This doesn't seem to work in Drupal 8 as I get the following error:

  InvalidArgumentException: Unable to set a value with a non-numeric delta in a list. in Drupal\Core\TypedData\Plugin\DataType\ItemList->set() (line 112 of core\lib\Drupal\Core\TypedData\Plugin\DataType\ItemList.php).

Hoe do I programatically untick the "Generate automatic URL alias" option in Drupal 8?

Save your node twice, once to generate the alias and the second time to turn off that option for the node.

 // Save node to generate alias
 $node->save();
 // Turn off pathauto
 $node->path->pathauto = 0;
 // Save again.
 $node->save();

Then open edit form and " Generate automatic URL alias" will be unchecked.


How to add classes to every menu block placed within in a specific region? How do I add classes to menus but only when they appear within a certain region? Is there a way to do this in a theme?

you can augment the variables collection available to any twig file by tweaking the appropriate preprocess ... for example ... if you create the following function within your $THEME$.theme file:

function $THEME$_preprocess_block(&$variables) {
  $block_id = $variables['elements']['#id'];
  $block = \Drupal\block\Entity\Block::load($block_id);
  $variables['region'] = $block->getRegion();
}

you can then access the newly defined region variable from within:

{{ region }}

you could then add your desired classes to menus but only when they appear within a certain regions:

{% set classes = 'menu' ~ ((region == 'header') ? ' menu-header') %}
{% block content %}
    <nav {{ content_attributes.addClass(classes) }}>
        {{ content }}
    </nav>
{% endblock %}

that would add the class menu to all blocks and additionally would add the class menu-header to any block within the header region

hope that helps!


View with 2 taxonomy term in url I a new Drupal 8 user :) and I have a problem with my view !

The context: I have a content type Car with Brand (Taxonomy term ) and Color (Taxo term)

I want to know if it's possible to have this url:

mywebsite/ => view with all cars

mywebsite/brand => view with all cars for the brand

mywebsite/brand/color => view with all cars for the brand with the color

This is my view

I don't know if it's possbile but I try :)

Thx for you help
And see you soon

Set the path to:

cars/%taxonomy_term/%taxonomy_term

Then add two relations in the advanced section:

Taxonomy term referenced from field_brand
Taxonomy term referenced from field_color

Then add two times the following context filter:

Name (Taxonomy Term)

Select in the first context filter the relationship field_brand and in the second context filter the field_color:

now it should work as expected.


How to declare a click on a particular tab to be a new event for use with Rules? I want to declare a click on a particular quicktab or any other tab as a new event for use in a rule. For example, when the user clicks that specific tab, an e-mail is sent to an admin. How can I make this click trigger a new event?

Possible lead? The Rules Link module. The JavaScript option may be what you're after.
Here is a quote about it (from the module's project page):

... lets you create links which trigger arbitrary functionality with the help of Rules.
Example use cases:

Publish/Unpublish content
Subcribe users to current group
Mark nodes, comments (as Spam), unpublish it and block the author.
Batch functions like, delete all comment for a node

And many more...
Features:

Attach the link to any entities.
Show the link only for certain bundles.
Narrow the entities on which the link will be shown using the visibility conditions.
The links are usually displayed using Views.
For entities that can be displayed, the links can be shown on node view.
Supports an arbitrary number of additional Rules parameters for passing context via Views.
3 types of links: Javascript, Normal and Confirmation form links.
Use individual permissions for each link.

Usages:
There are three types of links:

Javascript - Links that will trigger the rules using Ajax.
Token - This are basic links, that will reload the page after calling them.
Confirmation link - Show a confirmation form before executing the rule.


What is the default value for $operator in condition()? Looking at the documentation for QueryConditionInterface::condition(), the default value for $operation is reported to be NULL, while Conditional clauses reports the default value is '='.

What is the default value?
Does it change basing on the datatype of $value? For example, when $value is an array, then the default value is 'IN'; when it's a string or an integer, then the default value is '='.

QueryConditionInterface is just that, an interface. The actual class used is DatabaseCondition.

In DatabaseCondition:condition(), it does set the default operator:

if (!isset($operator)) {
  if (is_array($value)) {
    $operator = 'IN';
  }
  elseif (!isset($value)) {
    $operator = 'IS NULL';
  }
  else {
    $operator = '=';
  }
}


override variable in template.php with variable from module_preproccess_node I create custom template for node, and put variable in template.php

$colors = array('black', 'white');
$variables['group']['color'] = $colors;
$variables['size'] = 'double';

then i also create module and want to do hook to node template.

mymodule_preproccess_node() {
$colors = array('blue', 'red', 'green');
$variables['group']['color'] = $colors;
$variables['size'] = 'regular';
}

i want to show in my result:

//colors are blue, red, green instead of black, white
foreach ($group['color'] as $color) {
print $color.', ';
}
//and size is regular instead of double
print $size;

am i right? i want to override variables in template.php with variables from my module. then if i disable my module color will back from template.php.

If I am understanding/reverse engineering your question correctly, in your module, you can do something like this:

function YOURMODULE_preprocess_node(&$variables) {

  if ( // whatever logic ) {

    $colors = array('blue', 'red', 'green');
    $variables['group']['color'] = $colors;
    $variables['size'] = 'regular';

  }

}

This will create variables that can be accessed inside node.tpl.php and its variants.

In template.php you can then do something like this:

function YOURTHEME_preprocess_node(&$variables) {

  if (!isset($variables['size'])) {
    $variables['size'] = 'double';
  }

  if (!isset($variables['group']['color'])) {
    $colors = array('black', 'white');
    $variables['group']['color'] = $colors;
  }

}

which will set them to your defaults if they haven't already been set.

Then you can do whatever you want with them in node.tpl.php.


Error when using hook_form_comment_form_alter() I am using the following function in template.php to modify the comment form to remove the form title and add a default value inside the form:

/**
* Implements hook_form_comment_form_alter().
*/
function mytheme_form_comment_form_alter(&$form, &$form_state, $form_id) {

    $form['subject'] = array(
      '#type' => 'textfield',
      '#maxlength' => 255,
      '#attributes' =>array('placeholder' => t('subject')),
      '#required' => FALSE,
    );

    $form['comment_body'] = array(
      '#type' => 'textarea',
      '#maxlength' => 255,
      '#attributes' =>array('placeholder' => t('comment')),
      '#required' => TRUE,
    );

}

It does the desired task but it causes an error where the form will submit but the contents entered into the body are not submitted and will not display. The following error gets generated:

Notice: Undefined property: stdClass::$comment_body in comment_submit()

Am I missing something within the function so the text inputed is actually submitted when saving the form?

Turns out the correct way to add the placeholder was:

$form['comment_body'][LANGUAGE_NONE][0]['#attributes']['placeholder'] = t( 'comment' );


How to investigate arrayFlip errors in Commerce I get periodic errors telling me that something expects a parameter to be an array. But the messages are too vague, and don't tell me which piece of code is feeding that information to Drupal. Here's an example:

Warning: array_keys() expects parameter 1 to be array, null given in inline_conditions_field_widget_form_validate() (line 353 of /Users/newman/Sites/visionart/sites/all/modules/inline_conditions/inline_conditions.field.inc).
Warning: array_filter() expects parameter 1 to be array, null given in inline_conditions_field_widget_form_validate() (line 353 of /Users/newman/Sites/visionart/sites/all/modules/inline_conditions/inline_conditions.field.inc).
Warning: array_flip() expects parameter 1 to be array, null given in inline_conditions_field_widget_form_validate() (line 353 of /Users/newman/Sites/visionart/sites/all/modules/inline_conditions/inline_conditions.field.inc).
Warning: array_intersect_key(): Argument #1 is not an array in inline_conditions_field_widget_form_validate() (line 353 of /Users/newman/Sites/visionart/sites/all/modules/inline_conditions/inline_conditions.field.inc).

Most of these are in connection with array_flip(). I can see that this one in particular is being flagged but inline_conditions, bit it's such a core module that it's impossible to find out what's triggering it. How can I do that and how can I fix?

BTW, I think you're mistaken, inline conditions isn't a core module. In fact looks like the latest version is 7.x-1.0-alpha7. Also, notice that these are warnings, not errors. It's likely that they won't effect a site set up with production error handling.

The way I've dealt with that is through debugging on copy of the site running in a local environment with xdebug. If you haven't set that up yet there are a bunch of ways you can do it, here's a few:

Here's a link for how to do it using Homebrew. That's my reply but read the others there, they've got good info.
you can sign up for a free account on Acquia and use their dev desktop software. Here's some info on doing that. (Seems like I'm plugging my own posts, but thats what I know.) I've gotten
There's a similar app from Kalamuna called Kalabox that specifically is set up to work with Pantheon, but I was able to get to work standalone. Let me know if you need help with this, I'll try to get time to put more details up.

Be ready to be frustrated getting a local environment with debugging up and running, it takes some doing, but it's well worth the effort.

Once you've got debugging happening, you can put a breakpoint on line line 353 of
/sites/all/modules/inline_conditions/inline_conditions.field.inc. If you can reproduce the error, then just hit continue until just before you expect the error to occur. (If you can't, you'll have to do this each time it breakpoint is reached.) From the breakpoint, you'll be able to look at the parameters that are referenced on that line and see what's expected to be an array that isn't. My setup using Netbeans allows me to hop to earlier parts of the code by checking the stack. This will allow you to see just where the parameter was originally set.

Sorry this isn't just an easy answer, but getting yourself set up will be worth it in the long run.


How to filter only first level menu links using views? I have created the menu with the below structure,

A

Link A1
List A2

Link A21
List A22

B

Link B1

Link B11
List B12

List B2

Now my requirement is to get only first level menu links i.e A and B only using views module.

I found the answer by adding Filter criteria as given below in views. Please improve this answer if I am not correct.

Parent plugin ID (not_begins menu)


When viewing a product node, how to show/ enable the original node title? I am using commerce in my drupal site, but the node title is not there. Debugging it in the page.tpl.php returns an empty string ''. I know you can enable the title in the display settings of the content type and product variation, but this is rather a field within the node article, that has no influence of the title not being shown within the page template.

Obviously, the title is being set to '' somehow, but I cant figure out where this happens or, even more importantly, how to change this with my custom module.

Any help is greatly appreciated.

I found out that within the commerce_kickstart_product_ui_preprocess_page function the node title of product nodes is being set to '', for what reason ever. I wrote a custom module with weight higher than 50 and re-enabled the title:

function mymodule_preprocess_page(&$vars) {
  // make the title display available again
  $product_display_types = commerce_product_reference_node_types();
  if (isset($vars['node']->type) && isset($product_display_types[$vars['node']->type])) {
    $vars['title'] = $vars['node']->title;
  }
}


Is the Drush backend API a web-accessible API? How does one install it? I've successfully configured Drush 4.5 to work agains my Drupal 6 site from the command line using site aliases.  I am doing things like sql-sync and rsync successfully from the command line.  What I'd like to do now is expose these functions over the web, through an API.  The Drush documentation leads me to believe I can do this, however it is somewhat lacking in details on how to accomplish this, or indeed whether it's even part of the intended design.

There is a very high chance that I have completely misunderstood the documentation and have assumed a CLI-only API was designed to be available through the web.  However, the backend.inc file talks about a REST API accessible over HTTP and is ambiguous about what this API actually does.

  This is nearly a RESTful API. @see htp://en.wikipedia.org/wiki/REST
  Instead of "http://[server]/[apipath]/[command]?[arg1]=[value1],[arg2]=[value2]"
  it will call "[apipath] [command] --[arg1]=[value1] --[arg2]=[value2] --backend"

It's not clear to me what this actually means, because it says "instead of" the web call, but then goes on to describe how GET and POST arguments differ and how they are passed in from a web call.

  If the Drush API is meant to be called over the web, e.g. http://server.com/drush/drush.php/drupal-directory?argv1=@staging how do I enable this, given that Drush is in a separate PHP source tree?  Do I symlink to it from my Drupal directory?  Do I copy or symlink an include file and expect Drupal to pick it up?

As the previous respondents said, drush is a cli tool.  If you would like to invoke Drupal functions via web services, try the services module.  If you would like to manage multiple Drupal sites via a web ui, try aegir.

If you would like to call drush functions remotely from php:

$values = drush_invoke_process('@alias', 'drush-command', $args_array, $options_array);

See examples/example.aliases.drushrc.php for examples on how to make an alias record.  Instead of '@alias', you can also pass in an array containing the site record definition, or you can use username@myserver.com/path/to/drupal#mysite.com.  See the source code comments in drush for an explanation of drush_invoke_process, and the contents of the $values array.


Load all nodes from content type on front page without views I want to create a one-page website. What I hope to be able to do is load all the created pages from one content type under each other, prefably in a for each loop.

So in page.tpl.php it would be something like:

foreach($pages as $page){
    print $title;
    print render($page['content']);
}

This way I could also bind views/blocks to certain pieces of the page. The reason I'm looking for this kind of approach is to keep the website manageable.

The structure would be as follows:

home
about
 - slide one (view)
 - slide two (view)
 - slide three (view)
other page
 - slide one (view)
 - slide two (view)

So the mentioned slides are items from a different content type, loaded from a view.

If someone can point me in the right direction, or if some pieces of the question need clearing up, please let me know.

If people are still interested in this, I will give my solution here:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('status', 1) /* Status to make sure it is published */
  ->propertyCondition('type', array('page', 'webform')) /* get pages and webforms */
  ->fieldOrderBy('field_volgorde', 'value', 'ASC') /* a custom field to set the order */
  ->range(0, 9999); /* amount of pages to get */
$result = $query->execute();
$nodes = node_load_multiple(array_keys($result['node']));

foreach($nodes as $node):
    // Do your code magic
endforeach;

Within the foreach, fields can be echoed by using the following code examples:

echo $node->title;
echo $node->body['und'][0]['value'];
// ['und'] = language undefined

If there are any questions, feel free to let me know.

I use the following code to retrieve all nodes of a type:

$type = 'example';
$query = db_select('node', 'n')
  ->fields('n', array('nid'))
  ->condition('type', $type)
  ->condition('status', 1);
$nids = $query->execute()->fetchCol();
$nodes = node_load_multiple($nids);


Module version is not available in the list of the installed modules I was using Drupal 6 and 7 before. I'm now trying with Drupal 8, but in admin/modules I don't see the module version.

Why don't I see the module version? Is that information that Drupal doesn't show anymore, do I need to change settings, or is there any other reason?

On admin/modules, I can see the version of Drupal core modules, and third-party modules.

For third-party modules, Drupal will show the version only if it finds the necessary information in the .info.yml file of the module. In the case of the Honeypot module, this is what Drupal finds.

# Information added by Drupal.org packaging script on 2016-03-11
version: '8.x-1.23'
core: '8.x'
project: 'honeypot'
datestamp: 1457671749

Without that, Drupal doesn't show the module version. For example, this is what Drupal shows for my custom module, which is not hosted on drupal.org.

If you are using modules that aren't hosted on drupal.org, or you don't use Drush to download the modules, you will not see the module version. This also happens if you clone the module repository with Git instead of downloading the module archive from drupal.org.


Get select field value inside of a module I have a taxonomy reference field field_location_type with terms: Term A, Term B.

Inside of my custom module, I'm setting up a presave function that will set a hidden field value depending on the term selected in field_location_type.

I'm trying to log the current value of the field just to confirm i'm getting the right one, but there are no values displaying, like ...

function general_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
    \Drupal::logger('general')->notice('here: ' . $entity->field_location_type->value);
}

How do i get the value of the select field field_location_type?

Update as @berdir suggested in the comments, the best way to get a field value is:

$node->get('field_location_type')->target_id

In addition, you could also use Field::getValue method if you want an array representation.  Something like:

$entity->field_location_type->getValue()[0]['target_id']);

In addition if you need the term name (Option A ) from the id you can do this:

  $tid = $entity->get('field_location_type')->target_id;
  $term = \Drupal\taxonomy\Entity\Term::load($tid);
  // $name should have 'option A' or 'option b'
  $name = $term->getName();

Update: one way to figure out what methods are available  to you is to use xdebug in PhpStorm. If you set a break point after $field = $entity->field_location_type; you can then type $field-> and then hit ctrl and space the editor will provide suggestions based on the type of $field Here is a screen shot:


How do I translate the tab menu of a view? I cannot translate the tabs menu shown in a view. Does anyone know how to do it?

Go to admin/config/regional/translate/translate and search for the tab titles you want to translate. Since you have the required modules installed you should be able to find them there.


How do you print View fields on Twig? I have a view and added the title as a field.
For example: How do I print the title?

In Drupal 7 it was as simple as
views-view-fields--[viewname].tpl.php
<?php print $fields["title"]->content; ?>

How do we do this in Drupal 8?
I have created views-view-fields--[viewname].html.twig
I thought it might be {{ fields.title }} but I get the classic error message like so:

The website encountered an unexpected error. Please try again later.

I then tried {{ field.title }}, {{ title }} and {{ content.title }} but nothing prints.

After eating dinner, washing the dishes, playing around with it and reading the comments in views-view-fields.html.twig located in core\modules\views\templates

/**
 * @file
 * Theme override to display all the fields in a row.
 *
 * Available variables:
 * - view: The view in use.
 * - fields: A list of fields, each one contains:
 *   - content: The output of the field.
 *   - raw: The raw data for the field, if it exists. This is NOT output safe.
 *   - class: The safe class ID to use.
 *   - handler: The Views field handler controlling this field.
 *   - inline: Whether or not the field should be inline.
 *   - wrapper_element: An HTML element for a wrapper.
 *   - wrapper_attributes: List of attributes for wrapper element.
 *   - separator: An optional separator that may appear before a field.
 *   - label: The field's label text.
 *   - label_element: An HTML element for a label wrapper.
 *   - label_attributes: List of attributes for label wrapper.
 *   - label_suffix: Colon after the label.
 *   - element_type: An HTML element for the field content.
 *   - element_attributes: List of attributes for HTML element for field content.
 *   - has_label_colon: A boolean indicating whether to display a colon after
 *     the label.
 *   - element_type: An HTML element for the field content.
 *   - element_attributes: List of attributes for HTML element for field content.
 * - row: The raw result from the query, with all data it fetched.
 *
 * @see template_preprocess_views_view_fields()
 */

{{ fields.title.content }} worked for me. In hindsight it's very similar to the D7 code, duh, lol.

For other fields:

{{ fields.machine_name.content }} What's the machine name? You can find them under the Machine Name column in the Manage Fields of your content type or block.


Converting a page created with panel into PDF I'm working on D7 Panels and I created few pages using panel. I have a use case to generate the pdf for the data existed in the panel rather than the whole page with header and footer. Are there any recommendations to implement this.

Yes, you can, dowload Printer, email and PDF versions, patch module with Can Panel pages be sent to PDF for rendering?, download wkhtmltopdf libary, place it under /sites/all/libraries, and configure your module like: , and inside panels add print PDF widget like:, done!.
EDIT: today 7/7/2020 panles 7 had an upgrade, be carefull, i think patch apply to an older version in panels.


Using template on subsite for certain node type I am using a custom Theme in a multisite setting. With the help of @leymannx I implemented
hook_theme_suggestion_HOOK_alter to insert a page Template with the following naming convention:
page--NAMEOFSUBSITE.html.twig

See here

If I try to do the same for the node of my content type, which is using a template named node--CONTENTTYPENAME.html.twig at the moment, I can insert a name suggestion node--NAMEOFSUBSITE.html.twig, which will then be used for ALL nodes. I'd like to insert a suggestion such as
node--CONTENTYPENAME--NAMEOFSUBSITE.html.twig, for only this one nodetype.

How can I do that?

Thanx in advance!!

Activate twig debug and use the browser inspector to see the template precise name available for your content-type
Do a cache rebuild when the temaplte is created to make it happen.


How to optimise views with multiple field collection? I created a views reports page with multiple field collections (10), I added the field collection in relationships in advanced option to get the fields inside the field collection. this works great I get all the data that I need.
but here's the problem. If the page have the data on it, it takes time to load the page.

Example: If I have thousands of data in views reports page, it takes time to load the page, almost 1 minute(some times it keeps on loading). though I only display 10 items on each row using pagination/views lightpager but stills the page loading is slow,

My question: is how can I optimise my views reports page with multiple field collection relationships in my current setup, any suggestions will be appreciated.

Note: The data should always up to date. that's why I don't cache the views.

Thank you!

As per your reply, you dont want to use Cache, so I can suggest a module for this, Views Accelerator. It increases the performance of the view.

  Views Accelerator can bring about significant speed improvements on
  sites with views that cannot be cached normally, for instance because
  the views depend on an aspect of the visitor's session, like their
  location. Views Accelerator serves up two modes of operation.

  Analysis mode: Switched on from the module's configuration page,
  admin/config/system/views-accelerator, this displays at the top of the
  screen a performance summary for each view on the page. If performance
  is already great, tell your boss or customer. If it isn't, take a
  screenshot of the performance summary and proceed with the Accelerator
  mode: On views that could do with a boost, find and click the Caching
  option link in the Advanced section of the Views UI. It will reveal a
  new pseudo-caching option: None. Post-execution optimized by Views
  Accelerator. Select that. Revisit the page with the view(s) and
  compare performance stats to the screenshot you took earlier. Win?
  Then tell your boss or customer.


CSS changes not updating Basic caching settings all off:

settings.local.php is loaded:

Bottom of settings.php:

if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
   include $app_root . '/' . $site_path . '/settings.local.php';
}

And it contains:

$config['system.performance']['css']['preprocess'] = FALSE;

Issue: Add any changes to bootstrap subtheme at themes/contrib/tekatheme/css/style.css and save. Refresh page, no change. Has to run drush cr each time.

Running drush cr for each CSS edit is not a solution, it's impossible to work like that.

Have you tried setting up development.services.yml?

Put this next to your sites.php.

development.services.yml:

# Local development services.
#
# Place this file in the /sites/ directory.
#
# To activate this feature, follow the instructions at the top of the
# 'example.settings.local.php' file, which sits next to this file.
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory
parameters:
  http.response.debug_cacheability_headers: true
  twig.config:
    # Twig debugging:
    #
    # When debugging is enabled:
    # - The markup of each Twig template is surrounded by HTML comments that
    #   contain theming information, such as template file name suggestions.
    # - Note that this debugging markup will cause automated tests that directly
    #   check rendered HTML to fail. When running automated tests, 'debug'
    #   should be set to FALSE.
    # - The dump() function can be used in Twig templates to output information
    #   about template variables.
    # - Twig templates are automatically recompiled whenever the source code
    #   changes (see auto_reload below).
    #
    # For more information about debugging Twig templates, see
    # https://www.drupal.org/node/1906392.
    #
    # Not recommended in production environments
    # @default false
    debug: true
    # Twig auto-reload:
    #
    # Automatically recompile Twig templates whenever the source code changes.
    # If you don't provide a value for auto_reload, it will be determined
    # based on the value of debug.
    #
    # Not recommended in production environments
    # @default null
    auto_reload: auto_reload
    # Twig cache:
    #
    # By default, Twig templates will be compiled and stored in the filesystem
    # to increase performance. Disabling the Twig cache will recompile the
    # templates from source each time they are used. In most cases the
    # auto_reload setting above should be enabled rather than disabling the
    # Twig cache.
    #
    # Not recommended in production environments
    # @default true
    cache: false

Then in your settings.php, or preferrably your settings.local.php add this line:

$settings['container_yamls'][] = DRUPAL_ROOT . '/sites/development.services.yml';


Create dynamic external link URL without filtering or stripping protocol In my module I'm creating a dynamic external link to launch a local FileMaker database client and run a FileMaker script that finds a record like so:

FMP://192.168.123.123/DatabaseName.fmp12?script=FindRecord&RecordID=12345

The problem is no matter whether I use the Drupal 7 link l() function with attribute array absolute = true or external = true or if I assemble the link markup myself, either the anchor's href attribute gets stripped entirely or the protocol of FMP gets replaced with HTTP.

What do I need to do to let Drupal know this URL is safe to be outputted unmolested in outgoing emails?

I realised it's not Drupal changing the URL but GMail that doesn't like the protocol.

So I created a simple PHP redirect script and link from my Drupal module to that instead e.g.

<?php

header("Location: FMP://192.168.123.123/DatabaseName.fmp12?" . $_SERVER['QUERY_STRING']);
exit;

?>


where is the fault in my join? $query = db_select('watchdog', 'wa');
$query->join('distinct', 'di', 'di.wid == wa.wid')
  ->orderBy('wid')
  ->fields('wa', array('variables', 'type', 'severity', 'message', 'wid',
    'timestamp'))
  ->range(0, 20);
$result = $query->execute();

It shows me the error: Call to a member function orderBy() on a non-object in

You have join the distinct table with watchdog. So the all result of watchdog will be displayed and the matching record of distinct table. So try changing query like :

$query = db_select('distinct', 'di');
$query->join('watchdog', 'wa', 'di.wid == wa.wid')
  ->orderBy('wid')
  ->fields('wa', array('variables', 'type', 'severity', 'message', 'wid',
    'timestamp'))
  ->range(0, 20);
$result = $query->execute();


Drupal Views adding a view to node-customcontenttype.tpl.php I've created a "homepage" content type, and I've created the node-homepage.tpl.php template file, but it doesn't seem it is used, even after I cleared the cache about 10 times.

I am also trying to display a view in this custom template file. How can I achieve this?

In Drupal 7 you should use two dashes : node--content-type.tpl.php.

Embeding view:

<?php print views_embed_view('articles','block', $node->nid); ?>

articles - name of view, block - type of view, $node->nid - argument.


Use different indexes for Solr searches on local dev environment I'm using the Search API Solr module for search on my Pantheon site.  Pantheon's Solr module automatically sets the search index for the dev, staging, and live environments.

But now I want to install Solr locally and I want to use that index instead on my local dev environment.  I know I can change the environment settings in settings.php-- I have already done this for some things on my local environment.

I defined the Server for my local copy of Solr at
admin/config/search/search_api.  I have two different Indexes on this page, and these default to the Pantheon Server.  I can easily switch them to the local solr Server, but I don't want to do this every time I reset my dev environment.

What variable can I set to force the Indexes to use my local Solr Server?

Sadly, Solr servers and their settings are not variables. They're not entities, nor anything else Drupal would know about, and subsequently be able to effect.

The settings for the server host/path are stored in a serialised PHP string in the search_api_server table. (the options column).

The best I think you'll be able to do is to add a step to your pull-from-pantheon process to run a script after the database has been updated. The script would perhaps delete all existing servers and add a new record with only the known good configuration for your local host.

Or you could have a module enabled locally only that checks for the host on each request, something like that. I don't think there's a way to do it without altering the database manually, or at least by using one of the API functions provided by search_api_solr.


Node content versioning and compare tool I already know that node content versioning is supported in drupal, what I want to know is how much?

I for instance create a content type 'article' and add some extra text fields to it, The article content should have the capability to be reviewed and altered by many authors/reviewers and their changes will be saved as seperate records not impacting the real article record, only if I approve their changes will they be reflected on main article record.

Which of the functionality is currently supported and what is not?

Thanks

You can use Revisioning module for comparisons of different revisions:

  Revisioning is a module for the configuration of workflows to create,
  moderate and publish content revisions.

or you can use Diff module:

  This module adds a tab for sufficiently permissioned users. The tab
  shows all revisions like standard Drupal but it also allows pretty
  viewing of all added/changed/deleted words between revisions.


Filter criteria are not working with featured content blocks I am trying to create a featured content block for my front page. To start I have set up a "featured" vocabulary with the two terms 'featured', and 'not featured'. I have then added that field to all my content types that I use.

Now when constructing the view to get all content that has the 'featured' term works if in the filter criteria it has only one content type.
For example if I put the filter criteria to only check against the book term, then it brings back all book pages with the featured term.  However, if I set up the filter criteria to check for book page feature, or article page feature, no content is found.

Is there a limitation on mixing content filtering in this way?

First of all, in this case you don't need to add your filters to a new filter group, because views will use AND by default.

I don't see a filter for your taxonomy term. You should add one (see in the attached images).

For the content types you need just one filter, you can select which content types to filter on inside the filter.