How send argument to Services Module (Views+Contextual filters) I'm using the Services Module to make a request from one website to a drupal website (The services module calls a view).

For this I'm using jQuery:

$.ajax({
    url: 'http://test.url/rest/viewname',
    success: function(){ alert('hi'); }
});

This works FINE !

Now I added a "Contextual Filter" to the View, to show only nodes of a specific user. My question: How can I send the uid with jquery?? I tried a lot of ways:

$.ajax({
        url: 'http://test.url/rest/viewname/555',
        ...
    });

Error 404!

$.ajax({
        url: 'http://test.url/rest/viewname?args[uid]=555',
        ...
    });

Argument ignored!

$.ajax({
        url: 'http://test.url/rest/viewname?arguments[0]=555',
        ...
    });

Argument ignored!

$.ajax({
        url: 'http://test.url/rest/viewname',
        data: { uid: '1' }
        ...
    });

Argument ignored!

... and much more :D

Can somebody helo me?

When making a jQuery ajax request to a Drupal Services 3.x module REST API endpoint, define the request type of your ajax request like this.

(function ($) {
  var request = $.ajax({
    "url" : "http://test.url/rest/viewname/555",
    "type" : "GET"
  });
}(jQuery));

Usually a RETRIEVE request would be done using the request type GET, but for an ACTION, like the taxonomy_term Resource action selectNodes (This method returns all nodes with provided taxonomy id.), provided in Services 3.x, you would set the request type to POST. All RESTful services use POST for ACTIONs. In this case, your jQuery Ajax request would look like this:

(function ($) {
  var request = $.ajax({
    "url" : "http://test.url/rest/taxonomy_term/selectNodes",
    "type" : "POST",
    "dataType" : "json",
    "data" : { "tid" : 555, "pager" : 0 }
  });
}(jQuery));

Each of the resource operations in a REST API use a specific HTTP Method or request type  (e.g., GET, PUT, POST, or DELETE). You need to use the correct one or it wont work. The Drupal Services 3.x module adheres to these strictly.

To learn more about REST API request methods and how they relate to resource operations, take a look at the Using HTTP Methods for RESTful Services on the REST API Tutorial site.


How to alter add content form to include a new setting panel? Here is the code for creating a new Tab in the settings panel on "Add article" node.
But it is not displaying.. what could be the errors ?

function mltag_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'article_node_form') {
drupal_set_message('Editing a node');
$form['mltag'] = array(
    '#type' => 'fieldset',
    '#title' => t('MLTag settings'),
    '#access' => TRUE,
    '#collapsible' => TRUE,
    '#group' => 'additional_settings',
    //'#attached' => array(
    //        'js' => array(drupal_get_path('module', 'autordf').'/autordf.js'),
    //),
    '#tree' => TRUE,
    '#weight' => -2,
    '#attributes' => array('class' => array('mltag-settings')),
);
$form['mltag']['enabled'] = array(
    '#type' => 'checkbox',
    '#title' => t('Generate tags use Mltag'),
    //'#default_value' => (empty($form['nid']['#value'])),
);
}
}

Your code works perfectly for me; dropped straight into a form alter hook I get the following on the article add page:

There are 3 reasons I can think of that might explain why you're not seeing the new tab:

You haven't cleared Drupal's caches since implementing the new hook (probably the most common cause for problems like this).
Your module isn't actually called "mltag", in which case your form alter hook will never actually be run.
Your code is in a file other than the main .module file. Hooks declared in files that are not explicitly included from the .module file will not necessarily be found when Drupal is updating the module_implements cache.


How to determine if the current page is a search results page? How can I determine from within a module or theme if the current page is an Apache solr search results page?

If you're trying to determine from a module then you can check if the page is the search results page via the path arguments using the arg() function.

if (arg(0) == 'search') {
  TRUE
}
else {
  FALSE
}


Can't get url from internal uri in twig template file I have tried every suggestion I could find and nothing is working. I need to get the actual path or url since I am adding some specific classes to the link. The array is below

I got to this from the following

{% set link = paragraph.field_link.value.0 %}
{{ kint(link) }}

I understand that I need to use the url() or path() function but these require 2 parameters and I am unsure where to get these from.

You can try to do like this

{{ content.field_link.0['#url'] }}

That should do it.

This is another possible way of diong it

{{paragraph.field_link.uri }}


Getting started with the Form API and Ajax framework I'm really struggling to understand how to use Drupal 7's Form API in conjunction with its Ajax framework. I'd like to accomplish the following:

On certain pages, multiple nodes may appear. Each one of these nodes should have a comment form appear right below it. When the user submits a comment, it should be done via Ajax and the resulting comment should then appear under the node in question.

Can someone give me an overview of the steps that are required to do this?

There is a module for submitting forms with Ajax.

  Provides AJAX comments to Drupal sites. Features:

  Makes AJAX submits
  Allows replies to comments on the actual thread page
  AJAX comments deleting
  Works with CAPTCHA
  Cool jQuery sliding


DrupalDatabaseCache::set Devel Module I seem to be getting slow speeds with
DrupalDatabaseCache::set and DrupalDatabaseCache::getMultiple

i am using drupal 7 and am on a Virtual Private Server on Dreamhost which is running Fast CGI and xchache

Any tips on how to get these requests (40+ milliseconds) down under 5mills?

there are some other querries that are above 5 milliseconds
user_roles, menu_get_item, menu_item_visibility_load etc..

any tips for overall improvement in the time querries take to load?

Best Option: Use a non DB cache backend like Memcache
Next Best: Use a MySQL derivative that supports blob columns in a memory table and convert all cache tables to be of the type memory. Be sure to rebuild the indexes as BTREE's instead of HASH after converting to MEMORY. More details on this can be seen in this presentation: http://www.percona.com/resources/technical-presentations/drupal-and-mysql-performance-percona-live-mysql-webinar
Still good: Follow the directions here: Drupal 7: Database select query FROM cache_bootstrap brings server down

Note that all 3 of the above options are independent from each other; so you can do all 3. Also noted that the answer in #3, his database server was configured reasonably well; you might need to tune InnoDB in order to get better performance out of your's.

EDIT:
Also checkout my guide on tuning D7 https://docs.google.com/presentation/d/1AgnurTWsWdMAFjfFmSU7mk2zfJu8jG_KmVdZ7-o6Pok/edit#slide=id.p


Will importing a View that already exists merge with what isn't there in Drupal 7? I have a dev and prod instance of my site. I cloned my Prod to my Dev server. Now I created a new display block inside an existing view on Dev. I tested it and it works. Now i want to export it to my Prod, but it has the same View name. I can manually create it on prod, but thats the slow way of doing it. If i export the view code and paste it to my prod, would it throw an error saying that view exist? Or would it just merge the changes and add in the new display i created?

WHOA STOP. haha

Install the Features module and create a feature with this View in it and deploy (git/sftp) the Feature up to production. then revert feature and boom. latest view is there.

Download, enable Features on Dev
Create a new Feature
Add your View to this Feature
Save the exported feature into your file system for Drupal
Enable on Dev and verify that it is in the default state (it should be)
Download, enable Features on Prod (or use git to merge you dev branch into prod)
Place this new Feature onto prod (either using git or SFTP)
Enable this feature on prod. Since you have the View already, it will probably be Overridden. You can simply view differences (using Diff module) or revert it.

Note: I highly recommend a staging environment between development and production so you can test these types of reverts and adjustments prior to making changes on a production site.


Use custom module template for content type page? I'm finding lots of examples for theming the node template of a content type, but I can't figure out how to use a template from my module as the page template for a custom node type.

page.tpl.php doesn't know, by itself, anything about node types so you'll have to make your module preprocess the page with hook_preprocess_HOOK() to add an alternative theme hook suggestion.

function MYMODULE_preprocess_page(&$variables) {
   if (isset($variables['node']->type)) {
     $variables['theme_hook_suggestions'][] = 'page__' . $variables['node']->type;
    }
}

Once done, you can have your module evoke hook_theme() to advertise processing for your custom page node type template and its location. For example:

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {
  $theme = array();
  $theme['page__mynodetype'] = array(
    'path' => drupal_get_path('module', 'MYMODULE') . '/templates',
    'template' => 'page--mynodetype',
  );
  return $theme;
}

When the module is enabled (and theme registry cache cleared), the theme engine will look for page--mynodetype.tpl.php within the templates directory of your module.


New e-commerce site: stuck with D6 Ubercart for now? Client needs a shopping cart in a hurry. The spec is fairly straightforward, but will need weight categories for shipping and payments through Worldpay.

I'd love to do this with D7 and excited about Drupal Commerce, but I don't think it's there yet. I spent today playing with D7 Ubercart, and while it felt quite stable I don't think many contrib modules have been upgraded and I'm going to struggle.

So my instinct says build the thing in D6 Ubercart for now, then look to upgrade to Drupal Commerce further down the line. Sound like a plan?

I would agree. I have too researched this and have come to the same conclusion. We are still starting all Drupal ecommerce projects on Ubercart and D6 (Looking forward to Drupal Commerce though)


How can I insert search box in front html page? I tried to show the search box in a custom front page, which is a regular HTML page.

How can I achieve it?

I'm not sure if this is exactly what you're asking, but if you want to output a block directly in code you can use module_invoke().

IE.

Drupal 7

$block = module_invoke('block', 'block_view', 'current_search');

Drupal 6

$block = module_invoke('block', 'block', 'view', 'current_search');

Then render the contents of $block.


Field in custom node tpl - Simple issue that this newb can't figure out I have been trying to learn the ins and outs of hooks and basic theming in Drupal.

I currently have a template file for one of my content type (node--opportunities.tpl.php). Everything has been going great theming with this except for a field collection that I am now stuck on. I know there are a multiple ways of theming a field collection and this is the worse. But I can't figure it out when the array is perfectly right in front of me.

field_services is the field name. When I dsm($content) on the node you can see it perfectly. So I'm using a foreach to loop through the items, pull them out and load them. Then print their values with my markup. But it will not render. Even when I 'dsm' the final array, it shows me my fields perfectly. But when I try to render them, nothing happens.

Can anyone help me understand what I am doing wrong? I am more interested in why my investigative attempts to print the values of this array are fruitless than I am interested in actually theming the field collection.

    hide($content['field_services']);
    //horizontal radios
    print '
';
      print render($content['field_opportunity_type']);
    print '
';

    //if (!empty($content['field_services'])) {

        print '
';

         foreach ($content['field_services']['#items'] as $entity_uri) {

          $a_field_collection_item = entity_load('field_collection_item',                 $entity_uri);

            foreach ($a_field_collection_item as $a_field_collection_item_object ) {

              dsm($a_field_collection_item_object);

              print render($a_field_collection_item->field_service);
              print render($a_field_collection_item_object->field_service_multiplier);
              print render($a_field_collection_item_object->field_extend_service_total);

              //print render($a_field_collection_item_object->field_service['und'][0]);
              //$...->field_service['und'][0]['entity']->field_unit_price
              //->field_service['und'][0]
            }
        }
        print '
' . "\n";
    //}

I've also tried these as suggested with no luck. Here is also a printscreen of the dpm:

DPM PS http://ecteam.net/Untitled.png

    dpm($a_field_collection_item_object);

    print 'test';
    print $a_field_collection_item->field_service['und'][0];
    print $a_field_collection_item->field_service['und'][0]['entity']->title;
    print $a_field_collection_item->field_service['und'][0]['target_id'];
    print $a_field_collection_item->field_service_multiplier['und'][0]['value'];
    print $a_field_collection_item->field_service_multiplier['und'][0]['value'];
    print $a_field_collection_item->field_extend_service_total['und'][0]['value'];

Note: field_services is the parent field collection, field_service is the individual field that contains the service title that I am trying to render from it.

Arpitr was correct but I was also referencing the wrong variable.

The foreach loops states
        foreach ($a_field_collection_item as $a_field_collection_item_object ) {

I guess I just wasnt paying attention. I used this:

    print render($a_field_collection_item->field_service);

but I should have used this:

    print render($a_field_collection_item_object ->field_service);

Final solution for how to theme a field collection in a node template

My content is called opportunities. So in my node--opportunities.tpl.php I put:

    if (!empty($content['MY_FIELD_COLLECTION'])) {
      hide($content['MY_FIELD_COLLECTION']);

      print '
';

      foreach ($content['MY_FIELD_COLLECTION']['#items'] as $entity_uri) {

        $a_field_collection_item = entity_load('field_collection_item', $entity_uri);

            foreach ($a_field_collection_item as $a_field_collection_item_object ) {

                print $a_field_collection_item_object->field_service['und'][0]['entity']->title;
                print $a_field_collection_item_object->field_service_multiplier['und'][0]['value'];
                print $a_field_collection_item_object->field_extend_service_total['und'][0]['value'];

            }
    }
   print '
' . "\n";
   }


Is there an Input Filter without built-in restrictions? Is there an Input Filter without built-in restrictions? The built-in Drupal filters and some of the other filters I have checked seem to come with their built-in restrictions, eg

The Drupal's own HTML Filter format has its own built in restrictions; a list of HTML tags that can be used. JavaScript event attributes, JavaScript URLs, and CSS are always stripped.

The WYSIWYG Filter has built-in restrictions; the following elements cannot be whitelisted due to security reasons, to prevent users from breaking site layout and/or to avoid posting invalid HTML: applet, area, base, basefont, body, button, embed, form, frame, frameset, head, html, iframe, input, isindex, label, link, map, meta, noframes, noscript, object, optgroup, option, param, script, select, style, textarea, title.`

Is there any input filter module without built-in set of restrictions, or that allows the administrator to override them, for use with the Full HTML text format?

You can always just make your own text filter through the admin.

If you head to /admin/config/content/formats and click "+ Add text format," you'll be able to customize your own text format, which includes the roles who can use it, what filters you would like to use (using none should allow for any html tag to get through).

If there are some html tags you don't want showing up in your text format, use "limit allowed HTML" tag, and list the tags you want, like this:

<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <blink>

You could event throw (as your example) a  tag in there to let it through. There is however, one big warning I need to leave you with:

====================WARNING ========================

Allowing users to place javascript on your page is a huge, huge security threat. If you decide to give users this privilege, make sure it's only with people you absolutely trust. If a text field allows JS to be placed in it, your basicly opening a door for a cross site scripting atttack.

Same holds true for the PHP filter, in fact the php filter is going away in D8, so I would really advise against using that.


How can I hide node titles only for displayed nodes, and not node edit forms? I have a little function to hide my node titles via template.php:

function mytheme_alpha_preprocess_page(&$vars) {
  if (isset($vars['node']) && $vars['node']->type == 'episode') {
    $vars['title_hidden'] = TRUE;
  }}

This function hides the title on the node edit form too, but for that form I need a title.

How can I avoid changing the node edit form in my function?

You could add a check to see if you are editing the node, like

function mytheme_alpha_preprocess_page(&$vars) {
  if (isset($vars['node']) && $vars['node']->type == 'episode') {
    if(arg(2) != 'edit') {
        $vars['title_hidden'] = TRUE;
    }
  }
}


How to add content-language How can i add this meta tag in my website :

<meta http-equiv=“content-language” content=“en-us”>     ?

I am using metatags module but i dont see any option about this. Is there any other way to do it?

Thank you

Hope this will help you,

In Drupal 7, you can achieve it using template_page_alter

    function THEME_NAME_page_alter($page) {
        global $language;
        $lang_name = $language->language;
        $meta_language = array(
          '#type' => 'html_tag',
          '#tag' => 'meta',
          '#attributes' => array(
            'http-equiv' => 'content-language',
            'content' => $lang_name
          )
        );
        $meta_content_language = array(
          '#type' => 'html_tag',
          '#tag' => 'meta',
          '#attributes' => array(
            'http-equiv' => 'language',
            'content' => $lang_name
          )
        );
        drupal_add_html_head($meta_language, 'content-language');
        drupal_add_html_head($meta_content_language, 'language');
    }

Folder listing of active theme folder

template_page_alter inside template.php file

Source


How to create a custom event in rules? I need to create an custom event for an action to be triggered in the Rules module.

Custom event is after completing the checkout process the page will be redirected to confirmation page. I need to trigger an action if the page is redirected to the confirmation page.

I need to check if the user has on the confirmation page like /payment-confirmation then i need to trigger an action.

Let's assume that the Rules action that you want to trigger is to just set a Drupal message like "Rules action related to payment confirmation". But this action should only be triggered when "Viewing the content" located at your confirmation page, which has a path like "/payment-confirmation".

To get this to work, use the rule below (in Rules export format, just import it in your site and check the results of it):

{ "rules_extra_action_about_payment_confirmation" : {
    "LABEL" : "Extra action about payment confirmation",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "site:current-page:path" ], "value" : "/payment-confirmation" } }
    ],
    "DO" : [ { "drupal_message" : { "message" : "Rules action related to payment confirmation" } } ]
  }
}

The rule above should be close to what you're looking for, except from these further refinements:

Replace the rules Action by your own rules "action" (which you didn't specify).
If you want your Rules Action to be performed before your confirmation page is actually shown, then replace the Rules Event (= "ON" : { "node_view" : [] },) with "ON" : { "init" : [] }, (= "Drupal is initializing").


Warnings after installation I have installed the Recruiter distro.
I have also installed the Respond and Selectivizr libraries under site/all/libraries.
However I still take these messages:
Warning: file_get_contents(sites/all/libraries/selectivizr/selectivizr.min.js): failed to open stream: No such file or directory in omega_build_js_cache() (line 388 of /var/www/html/recruiter/profiles/recruiter/themes/omega/omega/includes/scripts.inc).

and

Warning: file_get_contents(sites/all/libraries/respond/respond.min.js): failed to open stream: No such file or directory in omega_build_js_cache() (line 388 of /var/www/html/recruiter/profiles/recruiter/themes/omega/omega/includes/scripts.inc).

How can this be fixed?
thanks

Please check:

Folder and file names if they match the directory structure in the warning message
/var/www/html/recruiter/profiles/recruiter/themes/omega/omega/includes/scripts.inc if the selectivizer and respond directory is included or correct
The permissions of the folder and file


How can I get the file id if I use the file_save_data function? I will be adding new media files in D8 programmatically, how do I determine what the fid should be for each one? also how do i put the actual file contents into the media type?
this is my code

$file_name=$file_info['file_name'];
  $file = file_get_contents($fullpath."/".$file_name); // string
 $filesaved = file_save_data($file, 'public://'.$file_directory_name."/".$file_info['file_name')',FILE_EXISTS_REPLACE);
  $fid = ???;
  $static_media = Media::create([
      'bundle' => 'document',
      'uid' => '1',
      'langcode' => Language::LANGCODE_DEFAULT,
      'status' => Media::PUBLISHED,
      'your_image_field_name_here' => [
        'target_id' => $fid,
        'alt' => t('foo'),
        'title' => t('bar'),
      ],
    ]);
    $static_media->save();

Try

$filesaved = file_save_data($file, 'public://'.$file_directory_name."/".$file_info['file_name']), 'FILE_EXISTS_REPLACE');
$fid = $filesaved->id;

file->id is the id if file that you can use it as entity reference target_id (I mean file field).

and a good example how save and attach file to Node

use \Drupal\node\Entity\Node;

// Create file object from remote URL.
$data = file_get_contents('https://www.drupal.org/files/druplicon.small_.png');
$file = file_save_data($data, 'public://druplicon.png', FILE_EXISTS_REPLACE);

// Create node object with attached file.
$node = Node::create([
  'type'        => 'article',
  'title'       => 'Druplicon test',
  'field_image' => [
    'target_id' => $file->id(),
  ],
]);
$node->save();

What if the file is already present in your local file system and you want to attach it to an existing node? Here's an example for that too:

use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;

// Create file object from a locally copied file.
$uri  = file_unmanaged_copy('public://source.jpg', 'public://destination.jpg', FILE_EXISTS_REPLACE);
$file = File::Create([
  'uri' => $uri,
]);
$file->save();

// Load existing node and attach file.
$node = Node::load(1);
$node->field_image->setValue([
  'target_id' => $file->id(),
]);
$node->save();

And lastly, what if you want to stick a placeholder file to a node? Thanks to Drupal 8, this is too easy:

use \Drupal\node\Entity\Node;

$node = Node::create([
  'type'  => 'article',
  'title' => 'Generated image test',
]);
$node->field_image->generateSampleItems();
$node->save();


Menus and mobile sites We're using a theme based off Adaptive Theme, but even dropping columns below the main content still has undesired rendering outcome. When region-sidebar-first drops below content-inner there is a problem -- since the link colors contained within sidebar first and the body background color are both white.

What I'd like to have happen is that for mobile devices or when the browser size is under a certain width, I'd like to remove region-sidebar-first and region-sidebar-second and move the menu into another field that into another collapisable region to function as a 'mobile menu'.

Question: Could context handle this? Is there a mobile to handle such logic?

Current our setting appear as follows

This is more a CSS question I think. I solved this problem already for various sites using another menu block, with its own css markup, or using a jump menu.

Using media queries you will have to set the threshold on where to break:

@media all and (max-width: 370px) {
    .default-menu-region {
        display:none;
    }
    .mobile-menu {
        display:block;
    }
}

@media all and (min-width: 371px) {
    .mobile-menu {
        display:none;
    }
}

Adaptive theme provides files for those media queries already, you can just drop your custom content in there instead of writing new media queries like in this example.


How to change the hyper link to checkbox link? I'm using Node Compare module to compare products, it showing the Add to Compare as link, You can see the DEMO here, but I want to show as checkbox link

  .

I have no idea on how to achieve this, any pointer would be helpful!

You can save checkbox image from here.

a.compare-toggle {
    background-image: url("/path_to_image/checkboxes.png");
    background-repeat: no-repeat;
    color: #000000;
    height: 16px;
    padding-left: 20px;
    text-decoration: none;
}
a.compare-toggle.add {
    background-position: 0 0;
}
a.compare-toggle.remove {
    background-position: 0 -16px;
}

Let me know if you face any further query/concern regarding this.


Why am I getting "Your browser does not support iframes" in multiple browsers? I want to display a third party page within my theme and thought an <iframe> should do. However, I added the <iframe> to my basic page, selectingFull HTML but all I'm getting is Your browser does not support iframes with multiple browsers while I can use the iframe on the W3School website just fine. Why is this?

The link: http://spabc.com/drupal/content/store

I figured out that it's because I'm using CKEditor.

When editing the page, I had to click on Switch to plain text editor in order to get the iframe to load. CKEditor would convert that HTML into a misleading string of Your browser does not support iframes.


Display related nodes with taxonomy hierarchy in a View MY taxonomy is set up like:

* Parent term
    * Child term

I have a content type with a term reference so they can select the term it is associated with.

And I need a view that displays a result like:

* Parent term
    * Child term
        - Related node
        - Related node
        - Related node
* Parent term
    * Child term
        - Related node

Is this possible with drupal 7 Views 3?
I am able to relate nodes with only one level of taxonomy hierarchy, but not two. Every example I have come accross does not display related nodes with children terms, only with parent terms.
Any help would be appreicated!

I was able to accomplish this functionality through the use of two separate views combined into one. I could not find a way for Drupal to handle this out of the box. Essentially I am using one view to show the nodes related to the child terms, and using another view to bring in the View displaying child related nodes and sort it under the parent term.
The modules I used were: Views PHP, entity reference
Create your taxonomy vocabulary:

 * Parent term
     * Child term1
     * Child term2

Create a content type
Once created add a Entity Reference field of type Term Reference referencing your taxonomy vocabulary's children terms you have created. Create a handful of nodes.
Create a View Block displaying content (related Nodes)
After creating the View Block of content (the content type with the reference, show fields, HTML list), include the fields you want to show for the related node and give that view a contextual filter of the Entity reference field you used for the content type. Simply set the settings of the contextual filter under When the filter value is NOT available to Hide View. You can optionally set the no results behavior as well.
Create a view displaying taxonomy terms (Master view)
Create a view of taxonomy (HTML List, Show fields), add a relationship of Taxonomy term: Parent term and require this relationship. Add field Taxonomy term: Term ID and hide from display. Add field taxonomy term: Name and under the field setttings, set the relationship to Parent, then hide from display. Add field Taxonomy term: Name to display the name of the term. Finally add a Global: PHP field and under the Output code provide the following snippet:
<?php
   $viewNodeDetail = views_get_view('YOUR_VIEW_BLOCK_MACHINE_NAME');
   $viewNodeDetail->set_arguments(array($row->tid));
   print $viewNodeDetail->preview('BLOCK_MACHINE_NAME');
?>

Under the view format settings set the Grouping field Nr.1 to the (Parent) Taxonomy term: Name.
This will treat the view block as a field (the view block is the child term + node and the master view sorts by the parent term). This will give you an end result of:

Parent term

Child term

Related node
Related node
Related node

Parent term

Child term

Related node


Finding a node with a time closest to the current time without being past I am working on a site which has a Class (ECK) entity type. Each Class may have 0+ "Class Offerings," which are instances of a class at a specific date. I am trying to create a view listing a class and the next upcoming Offering for each class (if one exists). If there is no upcoming Offering, I would still like to list the Class. How could I accomplish this?

Absolutely!

Add a filter to your view, that is based on your date field and choose the operator as 'Is greater than or equal to'.

You have as an option to enter a relative date for the comparison and then enter in any variety of relative times and dates.  For your purpose just choose 'now' as the comparison.

That will pull up all nodes with a date field that is greater than or equal to now: i.e. all the future ones!

============= EDIT ===============

If you don't need all of the future ones, just limit the results to 1 and order by the date.  That will give you just the next one coming up.

Let us know if that works for you!


Tags won't show on Advanced Forum Module I am using Drupal 7. I'm struggling to get the tags to show on my forums within the Advanced Forum module.

I have configured them within the manage fields settings

but they will not show anywhere else on my forum pages.
I have checked the Drupal listing here and tested both suggestions, still no change (even after clearing cache.)

What am I doing wrong or missing?

FYI: Please before suggesting any other tag modules, please help me with my current setup and Advanced Forum module. Thank you.

Dev error: They weren't showing on any of the posts, because it was a new field, hence once you make the new post and select tags for them, then post, then they show just fine.


Form is not being rendered in template file I have tried drupal_render,drupal_get_form etc for rendering the form,but the form is not being rendered. Is there any error in code or else what else should i add to the code so that it works.

function questionnaire_template_form($form, &$form_state, $question) {
 print_r("in template function");

 $form_build = unserialize($question->criteria_data);

 foreach ($form_build as $key => $value) {

  $options = ($form_build[$key]['1']);
   $list = explode("\n", $options);

   $list = array_map('trim', $list);

   $list = array_filter($list, 'strlen');

   foreach ($list as $key => $value) {

    $new = explode('|',$value);
    $new_key = reset($new);
    $new_value = end($new);
    $new_list = array($new_key => $new_value);
    dsm($new_list);
   }
dsm('next');

   $fb = explode("_",$key);
   $type =reset($fb);

  if($type == 'radio') {

    if($form_build[$key]['0']) {
      $form['radio_form'] = array(
        '#type' => 'radios',
        '#options' => $list,
      );
    }
  }
   elseif($type == 'checkbox') {
    if($form_build[$key]['0']) {
     $form['checkbox_form'] = array(
       '#type' => 'checkboxes',
       '#options' => $list,
      );
    }
   }
   elseif($type == 'selectlist') {
    if($form_build[$key]['0']) {
      $form['selectlist_form'] = array(
        '#type' => 'select',
        '#options' => $list,
        );
   }
  }

}
return $form;
}

Above code is my form.

<?php
//print_r($variables['entity']->qid);?>
<?php
print_r($variables['entity']->title);?>
<?php
print_r($variables['entity']->text);?>
<?php
?>
<?php
?>
<?php
if($variables['entity']->criteria) {
  ?>
<?php
  $form_template = drupal_get_form('questionnaire_template_form' , $variables['entity']);
  print(drupal_render($form_template));

}
?>
<?php

print_r(l( t("Yes"), 'questionnaire/' . $variables['entity']->yes_quid));?>
<?php
print_r(l( t("No"), 'questionnaire/' . $variables['entity']->no_quid));?>
<?php

?>

And this is the template where I am rendering the form.
I am getting the form if I dsm the form

Drupal render will return the html

drupal_render(drupal_get_form('form_id'));

you have to print the returned html as well.

print drupal_render(drupal_get_form('form_id'));

in your case

$form_template = drupal_get_form('questionnaire_template_form' , $variables['entity']);
drupal_render($form_template);

change it to

$form_template = drupal_get_form('questionnaire_template_form' , $variables['entity']);
print drupal_render($form_template);


How to arrange two blocks horizontally? I am going to create this, But I really don't know how to do it.

and I want to create one view with two blocks.

what Format of view should be? (HTML list, Grid, Table, ...)

I don't know theming, How can I do this and arrange these blocks horizontally beside each other?

You can do this by using Panel module.

How can you use so I refer to Link1 & Link2


Count number of values within a field that accepts unlimited values I have an image field which can contain unlimited values. How can I display the number of image values contained within this field in views?

I'm using Drupal 7.

There is a way of doing this natively in Drupal 7.

Set 'Use aggregation' to Yes
Add a field that contains multiple values, such as a file field
Set the aggregation settings for it to COUNT DISTINCT

Simple. This will however enable aggregation for all fields, but the default settings for other fields will make them behave normally.


drupal_http_request redirect is not a fully qualified uri. Throws missing schema error 1002 I am trying to authorise with an Viagogo API using oauth in my custom module (i have my credentials from Viagogo). I can construct the initial URL OK but the redirect response from the API is a relative reference with an absolute path i.e. /Public/SimpleOAuthAccessRequest/Authorize?oauth_token=Y%34hg5k34jhg5%3D

Which in turn is throwing a missing schema error using drupal_http_request.

  object(stdClass)#466 (4) { ["error"]=> string(14) "missing schema"
  ["code"]=> int(-1002) ["redirect_code"]=> string(3) "302"
  ["redirect_url"]=> string(87)
  "/Public/SimpleOAuthAccessRequest/Authorize?oauth_token=Y%2Fbm9asdfasdfdsfjJfdd3D"

How can i get around this?

Is there a simpler way my custom module can authorise with oauth and access this API instead of my having to write this connector? The PHP code sample provided by Viagogo is using CURL and works fine outside of Drupal but once I bring the functions inside my custom module it doesn't work hence me using drupal_http_request.

I was trying to dump out the results coming back from my API call one step too early  and before the redirect (to present the token) had taken place so inside Drupal it didn't appear as if anything was happening.


How do you use hook_query_alter to get inside a query's creation? I'm getting no love from hook_query_alter.  I have a simple query to which I want to add a tag, while also adding a node_access tag.  Thus the whole query looks like this:

$the_nodes = db_select('node', 'n')
     ->condition('n.type', 'some_node_type')
     ->fields('n', array('nid', 'title'))
     ->addTag('node_access')
     ->addTag('my_custom_tag')
     ->execute()->fetchAll();

I then define a handler in one of my modules and litter it with debugging statements, hoping something will happen:

function mymodule_query_alter(QueryAlterableInterface $the_query) {
    dsm("inside mymodule_query_alter");
    dsm($the_query);
    if ($the_query->hasTag('my_custom_tag')) {
        dsm('Found it!');
        // do real work here
    }
}

I then clear the system cache.  Once I've done this, the following things happen:

My handler is running, and reports a number of invocations from
various system calls.
The objects being dumped by the dsm calls are all very much alike --
they contain only an alterTags array, which typically has entries
for either node_load_multiple or file_load_multiple, but nothing else -- certainly nothing like a full Query object.
None of the alterTags arrays have an entry for my_custom_tag.
The inner "Found it!" message never fires.

Arggh.  This is my first encounter with hook_query_alter(), and I'm probably just missing something basic about its use.  Can anybody clue me in?  (BTW, based on some browsing around, I've also tried defining handlers for my_module_query_my_custom_tag_alter and my_module_query_node_access_alter, but never see anything from them.)

Just to close this item out: It appears that my definition of hook_query_alter was, in fact, working correctly.  My problem was in assuming that I would be able to do things like  dsm($the_query) and see the components of the query object in preparation for doing stuff with them.  This doesn't seem to be the case -- dsm() wasn't returning anything of real use other than alterTags, but the orderby() (and other similar actions) did in fact alter the query.  So, I'd argue that it's a bit confusing, but works-as-designed, I guess...


Permissions for adding bundles to custom entities I've made some custom entities using the Entity API and I would like to give some users the ability to add bundles to them.

However it seems that in order to add bundles they have to have the "Administer site configuration" permission. I am a bit concerned about giving users that, especially as we might be doing a multisite system where different organisations will own different sites. I'm worried that they might be able configure directories and file paths and end up getting access to things on the other sites.

There is a special permission for creating content types, so I wonder whether there could also be one for creating bundles of other kinds of entities. It seems an oversight that there is not.

Writing in here, since its a faux paux to link to blog articles.

In your permissions.yml file of your module, you can define a permissions callback like so:

permission_callbacks:
  - Drupal\mymodule\MyModulePermissions::permissions

Then in your MyModulePermissions class:

namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MyModulePermissions implements ContainerInjectionInterface {

  use StringTranslationTrait;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructor for MyModulePermissions.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container->get('entity_type.manager'));
  }

  /**
   * Get permissions for MyModule.
   *
   * @return array
   *   Permissions array.
   */
  public function permissions() {
    $permissions = [];

    foreach ($this->entityTypeManager->getStorage('myentity')->loadMultiple() as $type) {
      $permissions += [
        'create ... ' . $type->bundle() => [
          'title' => $this->t('Allow creation of %type', array('%type' => $type->label())),
        ]
      ];

      $permissions += [
        'update ... ' . $type->bundle() => [
          'title' => $this->t('Allow update of %type', array('%type' => $type->label())),
        ]
      ];

      $permissions += [
        'delete ... ' . $type->bundle() => [
          'title' => $this->t('Allow deletion of %type', array('%type' => $type->label())),
        ]
      ];
    }

    return $permissions;
  }
}

Something like that. Code is untested. This will loop through and create CRUD permissions for each bundle.


Select Panel Node Layout on Node edit form I have multiple different layout variations all for the same node type, is it possible to select which one will be used from the node edit form?

For example I have a node type of product which has the following layout variations:

2 Column
3 Column
2 Column Hybrid

On the node edit for I would have then have a drop down (or something else) which allows me to select one of the variations listed above. Is this possible?

It sounds like you are using Panels (presumption based on the column names), so this is very easy to achieve.

In Page Manager, enable and edit node_view. Create a new panel variant. Enable Selection Rules for the variant. Add the selection rules "node_type = product" and "field_layout = 2 column".

Then carry on through the rest of the config, ie choose 2 column layout and put in your fields/blocks/etc. You will then have to create 2 more variants (or clone and edit the current variant), changing the selections rules and layout to suit.


One node for every referenced node in views I have a view that uses the table display mode. I want to show up the last created node for every referenced node; for example, I have two users, and I want to show the last post for both users.

  user number 1    |   last post title
     user number 2    |   last post title

You can also use View Field View module and create a view named Content View in which you may have:

Fields

Content: Title

Sort criteria

Content: Post date: Sort ascending or Sort descending

Filter criteria

Content: Type (or anything else to filter only certain posts)

Pager

Use pager: Display a specified number of items | 1 items

Contextual filters

Content: Author uid

Now create another page view or a block view (whatever you want) named User View

Relationships

Content: Author

Fields

User: title
Global: View (in this field select the view: Content View)

User View passes arguments in every raw to the Content View and thus it filters content by user id.


Can I programmatically add a string to the translation interface? I have used t() to translate a string value. To translate it from the user interface, I first need to view the page on which this string is displayed in a different language. Only then, the string is added to the translate interface.

I want to be able to translate the string before doing that. Can I programmatically add the string to the translation interface?

Assuming that your question is in regard to translating a (custom) module or theme. In that case, I'm using the Translation template extractor to get all strings of a module/theme that are used in the t() functions. For more information about using this module, look at this discussion. Though a pretty old discussion, it's still very useful.


Drupal 7 custom submit handler not getting triggered I am having a problem connecting a custom submit handler to a form. I am trying to switch off redirecting after the save of an eck entity on edit form. But i am not getting that far as my submit handler is not getting called.

The first debug log is as you would expect original handler and my custom one returned (so the alter part seems fine), but my on submit debug is never displayed on submission. I have switched the same code to the user_profile_form and it works fine, both debug logs coming through as expected. Why would this form be different??

Code:

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'eck__entity__form_edit_myentity') {
    $form['#submit'][] = 'mymodule_eck_ent_submit';
    dd($form['#submit']);
  }
}
function mymodule_eck_ent_submit($form, &$form_state)
{
    dd("smashed in !!");
}

Many Thanks
Mathew

Another form alter may affect this form and maybe detach your sumbit handler.

Try

$form['#submit'] = array('mymodule_eck_ent_submit');

And see if it fires.


View of nodes grouped by tag including not tagged elements My feature includes custom code, some views, content types and a taxonomy vocabulary.
An overview page should list all contents grouped by their taxonomy term (tag). The first group should be "not tagged".

How do I add the "not tagged" group?

not really sure how you're getting your lists, you mention custom code, and views.... if you just need a list of nodes that have no taxonomy term:

$nodes=db_query('SELECT * FROM node AS n LEFT JOIN taxonomy_index AS ti ON n.nid=ti.nid WHERE ti.nid IS NULL')

will give you that.

you could add a join to the taxonomy_term_hierarchy table and a WHERE clause to determine if the node has a term associated that is part of your vocabulary


Show total count of items on page created by views What is it right way to show total count on views?

I found this print count($view->results);

You could add an element on Header, from the interface.
CLick "Add" in header section and then add a "Global: Result summary" field.

If you have to do it by code, the right variable should be:

$view->total_rows


Adding a join in a Views field handler class constructor? In a Views field handler, one can define additional fields to accompany the base field defined in hook_field_data. These field values are based on database columns on the same row, and they can be used in the render function. Somewhat like this:

my_views_field_handler extends views_handler_field {

  function construct() {
    parent::construct();
    $this->additional_fields['property2'] = 'property2';
  }

  function render($values) {
    return $this->get_value($values) . $this->get_value($values, 'property2');
  }

}

But is it also possible to define a join in the constructor? One of my database columns is an id of another entity. I have been using it somewhat like this, but this generates quite a lot of overhead (loading an entire entity for each row).

  function render($values) {
    $id = $this->get_value($values, 'property2');
    $entity = entity_load_single('my_type', $id);

    if ($entity->some_other_field == TRUE) {
      return $this->get_value($values);
    }
    else {
      return 'none';
    }
  }

So is there something like a join I can use in the constuctor, so I can query the other entity table directly instead of having to load the entity?

Yes, but you need to have already defined that relationship in the view. Per the docs for views_handler_field::add_additional_fields($fields):

  @param $fields
  An array of fields. The key is an identifier
  used to later find the field alias used. The value is either a
  string in which case it's assumed to be a field on this handler's
  table; or it's an array in the form of
  @code array('table'
  => $tablename, 'field' => $fieldname) @endcode

Thus, say you had a field handler for a field on the node table with a defined author relationship to the users table. You could do this:

  function construct() {
    parent::construct();
    $this->additional_fields['mail'] = array(
      'table' => 'users',
      'field' => 'mail',
    );
  }

Which would allow you to do this:

function render($values) {
  //Get the mail column from the users table.
  $this->get_value($values, 'mail');
}

For your case, you'll need to define the entity relationship to your base table before you can do this.


Create an XML page by a custom module I need to create an XML page. I created a page with my custom module, and I tried to display it, but it showed as a normal Drupal page with blocks.

function my_custom_function_name_xml_list() {
  $output = '<?xml version="1.0" encoding="UTF-8">';

  return $output;
}

How do I avoid Drupal adds its own content to the output of my function?

Instead of returning the string you want to use as output, print it using code similar to the following one.

print $output;
module_invoke_all('exit');
exit();

$output is the variable containing the output you want to show.
While the module_invoke_all('exit') call is not strictly necessary, it notifies other modules that Drupal is terminating. There are modules that implement hook_exit() to do their job, and they will not work, without that call; their purpose is to write something in a Drupal variable, or in a database table, and they don't interfere with the output your are producing.

The reason why it is necessary to do this is the code used by index.php, which contains the following:

$return = menu_execute_active_handler();

// Menu status constants are integers; page content is a string.
if (is_int($return)) {
  switch ($return) {
    case MENU_NOT_FOUND:
      drupal_not_found();
      break;
    case MENU_ACCESS_DENIED:
      drupal_access_denied();
      break;
    case MENU_SITE_OFFLINE:
      drupal_site_offline();
      break;
  }
}
elseif (isset($return)) {
  // Print any value (including an empty string) except NULL or undefined:
  print theme('page', $return);
}

drupal_page_footer();

If you return a string, it is passed to theme('page'), which renders the page as you are noticing; if you return nothing, then both is_int($return) and isset($return) are FALSE, and the relative code is not executed.

The equivalent for Drupal 7 for the code I wrote for Drupal 6 would be the following one:

print $output;
drupal_exit();

drupal_exit() contains already the call to module_invoke_all('exit').


Why table creation on module install doesn't work? I need to create custom table for module, but after module install table is not created.

module.install file:

function bip_content_migration_schema() {

    $schema['bip_migrate'] = array(

            'description' => 'Storing content migration info from Joomla.',
            'fields' => array(

                    'id' => array(
                            'description' => 'id',
                            'type' => 'serial',
                    ),
                    'content_type' => array(
                            'description' => 'content type',
                            'type' => 'varchar',
                            'not null' => TRUE,
                            'length' => 255,
                    ),
                    'imported_count' => array(
                            'description' => 'imported count',
                            'type' => 'int',
                            'not null' => TRUE,
                            'default' => 0,
                    ),
                    'to_import_count' => array(
                            'description' => 'to import count',
                            'type' => 'int',
                            'not_null' => TRUE,
                    ),
                    'is_imported' => array(
                            'description' => 'is imported',
                            'type' => 'int',
                            'default' => 0,
                    ),
            ),
            'primary key' => array('id'),
            'indexes' => array(
                    'id' => array('id'),
            ),
    );
    return $schema;

}

What am I doing wrong?

EDIT

I added functions to my .install file (thought that I can ommit theme)

function bip_content_migration_install() {
    drupal_install_schema('bip_content_migration');
}

function bip_content_migration_uninstall() {
    drupal_uninstall_schema('bip_content_migration');
}

But again table is not created.

In Drupal 7, it is not necessary to call drupal_install_schema(), or drupal_uninstall_schema(); that is automatically done from Drupal. It is enough to implement hook_schema(), and the database table is created. There are many modules for Drupal 7 implementing that hook, and their database tables are created.

I can think of two possible causes for the database table not being created:

The short name of the module is not bip_content_migration
You added the hook_schema() implementation on an already installed module

If you installed the module, disabled it, changed the code, and re-enabled it, the database table would not be created. Disabling a module is different from uninstalling it. Uninstalling is done when a module is disabled, and then uninstalled from the "Uninstall" tab in admin/modules.

I didn't considered the following two cases, as Drupal should have given you some errors:

The schema is not correct
Drupal is not able to connect to the database, while installing the module.

If there are more databases, be sure you are looking at the right database.


Can add the new variable in the existing node--contenttype.tpl.tpl? I have written the query in .Module file and stored the output in a variable.

Now, I want to pass this new variable in existing node--contenttype.tpl.php

My idea is to pass the variable for the existing node.tpl.php using hook_theme function

Is that a good way to achieve it or anyone has a better way for it ?

You'd be better off doing in here:
https://api.drupal.org/api/drupal/modules%21node%21node.module/function/template_preprocess_node/7.x

"Processes variables for node.tpl.php" so should be ideal for what you need


How to Save a Node Object reached from another Server? I'm implementing the Node Object passing one Site to another. I am now able to send the $node object across the sites. But the problem now again is i can NOT do node_save($node) simply.

I can NOT get the object as Drupal valid $node

Are you working on a multilingual site?
Trying to save a node that have different language than expected, for example "it" instead of "und" fails, event if the node is cloned from another site in which is working well.

You could also try to
unset($node->nid)
unset($node->vid)

they are not required in order to create a new node.


How to add a jQuizzy? I've been searching and trying for two days to add the jQuizzy engine to my site with no luck!
I've successfully added some jQuery plugins to my site, but I can't seem to be add this one?!

I created a block. In the block is a link that calls a menu item. The menu item gets a drupal form. In the form I added all the JS and CSS ... Nothing is happening?!

Help!!!

Are you retrieving that form via AJAX ? Then you get the HTML, but in your page is not present the JavaScript/CSS files. You need to add them before, so they are ALREADY present in whatever page the block is placed.


My Menu Will Only Semi Translate I have created a menu on my site and have used features to export it. The first 2 menu items are translating to different languages but the third is not.

The third word is Contact. I have gone to /admin/config/regional/translate/translate and searched for Contact. I get the following.

At the bottom of my features it has

  // Translatables
  // Included for use with string extractors like potx.
  t('Contact');

So we can see that is there OK.
When looking at my menu at /admin/structure/menu/manage/menu-example it is all in English. If I go to /fr/admin/structure/menu/manage/menu-example Contact remains in English and the other words change.

Contact is a mailto:link if that makes any difference.

  $menu_links['menu-teleplan_contact:mailto:a@a.com'] = array(
    'menu_name' => 'menu-example',
    'link_path' => 'mailto:a@a.com',
    'router_path' => '',
    'link_title' => 'Contact',
    'options' => array(
      'attributes' => array(
        'title' => '',
      ),
      'identifier' => 'menu-example_contact:mailto:a@a.com',
    ),
    'module' => 'menu',
    'hidden' => 0,
    'external' => 1,
    'has_children' => 0,
    'expanded' => 0,
    'weight' => -48,
    'customized' => 1,
  );

Why is the word in my menu not translating?

I think you will find there is a conflict somewhere that is preventing the specific word (as it is a link) from being translated, and this submodule should overcome the conflict. I would utilise the "Menu Translation" submodule as it will specifically achieve what you are attempting above, and hopefully make it simpler! I would use the Translate and Localize Menus option (a detailed guide of how to do that is here)

If you are still stuck, and are using SuperFish for your menus (even though this is supported in i18n), there is a work around here and this may overcome the problem also.

Lastly, just in case, ensure you have this update, the most recent version, installed also.


How to use unique taxonomy term for nodes in Drupal 7? I have unique categories assigned to nodes via taxonomy module. now I want the path to be something like this:

root/taxonomy-vocabulary/taxonomy-term/node-titel

Any ideas?

This question has already been asked for Drupal 8 but I am running Drupal 7. So there might be a module or setting for this?

You can install Pathauto module and set template for your node's path as you want on page admin/config/search/path/patterns

In this case You can use all this tokens with taxonomy term names, something like that:
[node:taxonomy-vocabulary-1:name] etc. List with all this tokens is on admin/config/search/path/patterns page


Show hook_form on specific content type Drupal 7 Programmaticaly How can show a form that is created with the drupal _hook form api, on a specific content type? So, as example:

I created new content for the content type 'outside' when I click on save I see the content type like this:

Titel
Date
Description

What I want is a form below this. I created one with a _hook form and it is working an saves data to my database but I have no idea, how can I show them on the same page as my content. It may not show on the content type 'inside'! Now it's a other page the link is /outside-form and only the form shows up there, no content type.

How can I get them below my content on every page that has the content type 'outside'? I have written a own module, but only this is not working/showing up on specific content(type).

Can someone explain it to me?

You need to create a block that's content contains following code:

$form = drupal_get_form('YOUR_FORM_ID');
print drupal_render($form);

Set the block visiblity only on content type 'outside' & place this block in any region as per your suits.


Drush: How do I change the Drupal root My Drush commands doesn't work because my Drupal files are in another directory than the one set in Drush. Everything is set up to this path so I can't just change the folder name.

Drush status
  [..]
  Drupal root   : /Users/nicklas/Documents/SourceTree/Drupal/web

How can I change the path to /docroot instead of /web?

  /Users/nicklas/Documents/SourceTree/Drupal/docroot

You can pass it in via the --root argument

drush status --root=/Users/nicklas/Documents/SourceTree/Drupal/docroot


Update report / drush up issue I'm experiencing some odd behavior with D7's update report. When I view the update report it can only determine the status of roughly 5 or so modules/themes. The ones that it finds are random and each refresh reveals a different list of statuses that it can determine. The list reveals all enabled modules but majority of them are grey with "No release found" for the status. Drush up behaves the same, except that it only returns the random 5 or so modules that it can find a status for.

Has anyone experienced this issue? Could it be that drupal.org is not responding and the issue is with drupal.org? It's really painful because the elegance and ease of drush up is no longer relevant when you have to run it 20 or so times to update modules.

When the update manager reports 'no release found', it typically means you installed from a git (formerly CVS) checkout. If you did do this, you'll need to run the Git deploy module to properly track module versions.

If you didn't use direct git checkouts, but rather, downloaded normal releases from Drupal.org, it may be a bug, which should be reported with as much detail about your setup as possible in the Drupal 7 issue queue.

Edit: you may also be experiencing this Drush issue.


Views promoted/sticky items I have a view of all content, of all types, listed by date order. Paginated of course (with load more).

I want to find the latest piece of content of type X, and promote it/make it stick to the first result.

I was initially just going to use an attachment, but this comes with 2 problems.

The item ideally won't repeat
If it is already the first item, or in the first few results, there will be 2 right next to each other.

The item should not persist as the first item on each page, it should just be moved/re-ordered.

I feel like this should be very straight forward, but I am drawing a blank.

Any help most appreciated!

One thing you can do is set up a "sticky" view which pulls out the node you're looking for and then store the nid of the node.  You could do this using hook_views_post_execute() in a custom module like so:

function MYMODULE_views_post_execute(&$view) {
  $nid = &drupal_static('MYMODULE_sticky_node_id');
  if(!empty($view->result)) {
    $nid = $view->result[0]->nid; // (or similar)
  }
}

(Replace all instances of "MYMODULE" with your module name)

Now if there is a result then it's nid should be stored in a static variable called 'MYMODULE_sticky_node_id'.

Next add a contextual filter of NID to the main view, leave "When the filter value is NOT in the URL" as "Display all results for the specified field", and under the "More" fieldset, tick "Exclude".

Next implement something like hook_views_pre_view():

function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'your_main_view_name') { // If need be add "&& $display_id == 'your_main_view_display_name'
    if ($nid = drupal_static('MYMODULE_sticky_node_id')) {
      $view->set_arguments(array($nid));
    }
  }
}

This will pull out the nid you saved while processing the sticky view and set it as the argument of the main view, therefore excluding it from that view.

You'll need to make sure that the sticky view is rendered before the main view for this to work.

Bear in mind that I haven't tested this exact code so it might need some tweaking to get it to work in context.


Adding content to a page through a module I just want to echo some words when a certain node comes up.

Currently however it doesn't echo within the content section, but above the header.

How do I get my module to echo the words at the top of the content section?

If the content is always static then you can look into adding it to a theme template file (by creating a subtheme).

Or you could add some php as part of preprocess_node in template.php to append/prepend the text to the content/body array.


Updated drush, but status shows old version I have a D7 site running in a Vagrant VM.

I was getting the following error when attempting to run drush updb from the site folder:

  Command updatedb needs a higher bootstrap level to run - you will need
  to invoke drush from a more functional Drupal environment to run this
  command.

  The drush command 'updb' could not be executed.

I simply couldn't figure out why this won't run, so I thought I'd update drush. It was on 8.0.0-rc4.

I updated via composer on my local machine, and when I type drush --version it shows 8.1.12.

But, when I run drush status it still shows 8.0.0-rc4, and to top it off, I still cannot run drush updb

What is going on here?

I have tried running drush --uri=mysite.local updb but that doesn't help either.

In Vagrant, you need to SSH to the machine and run Drush from there.


Convert Existing Body Fields To CCK Text Fields Hello i have a Content Type that has been using a body field. Now i was wanting to use a CCK text field instead. Is there a way i can convert existing node body fields for this content type to my new cck field?

Thanks

(drupal 6)

Three options spring to mind:

Views Bulk Operations. Safest if the amount of nodes to convert is manageable. You'll probably need to use custom PHP to make the conversion happen though, as the ready-made functionality won't cut your demands.
Custom script where you load each node to be converted, modify the structure and run node_save().
SQL query, either pure SQL or by custom Drupal (Drush) script. First create your content type, then see the database structure. Then select the body text from the table node_revisions and insert it into your field value column for each node.


How to change my base URL I have built a website using drupal. Now, the base URL is http://xxx.xxx.xxx.xxx/drupal.
But I want to change base URL as http://xxx.xxx.xxx.xxx
How do I do?

Thanks.

go to yousite/sites/default and open the settings.php file and find $base_url and change it to the new value (somewhere around line 270).

NOTE : settings.php is a read-only file, you need to clear the read-only flag first to make the changes. You'll need to restart the server to update the changes.


How can I have different templates for newly created content? I am using Drupal 7 and I need to show a different content for a custom entity depending on if the recently created content is being shown after submitting the form or if I visit the URL afterwards.

Is there a way to have different templates or is there a variable to check that tells you if it's newly created content?

I need this because I'm going to let the user share the page on social networks from that page, and I need to show a different content when people visit it afterwards.

Here's one way to solve this. In a nutshell:

Create a custom view for your entity using Display Suite or Entity View Modes.  Display Suite is preferred, as it allows you to also create custom fields and custom layouts for your entity display. This is the custom view your authors will see when they submit the entity create form.
Alter the entity creation form and add a new submit handler (be sure not to delete the default submit handler, as that will take care of creating and saving the entity before your custom handler is called).
In the new submit handler, create a form_state['redirect'] to a custom menu item
Create a custom menu item (with hook_menu) that will load your entity and pass it to a page callback
The page callback will build and return the entity custom view you defined in step 1.

Here's the code for all this (except step 1). PLEASE NOTE: since I don't know what custom entity you are using, this example uses Basic page node (content) type. You will need to adapt to your custom entity. All this code goes in a custom module called my_custom_view.module.

Also note: the custom view I created in Display Suite is called custom (see node_view() in the page callback).

<?php

function my_custom_view_form_page_node_form_alter(&$form, $form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'my_custom_view_form_submit';
}

function my_custom_view_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'custom-node-view/'.$form_state['nid'];
}

function my_custom_view_menu() {
  $item = array();
  $item['custom-node-view/%node'] = array(
    'page callback' => 'my_custom_view_page',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
  );
  return $item;
}

function my_custom_view_page($node) {
  return node_view($node, 'custom');
}


How to alter view query to display only 5 top records I couldn't find a similar problem on the forum so I am asking. I created a view with exposed filters but when I visit the view page I am going display 5 top recent record for specific content type. When I click search button the result changes of course and result with a pager shows up. How can I display 5 top recent records before I click search button for the first time when I visit page with the view? I thought to use hook_views_query_alter to add limit to the query but I don't know how. Any ideas how to achieve that?

Thank you!

If within the Views Pager options, you select "Display a specified number of items" and set "Items to display" to 5, you will get the behavior you are desiring.  You just need to make sure your sort criteria provides whatever "top" means on your site.  What I think you are doing instead is selecting "Use Pager" with 5 items.


How can I redirect the user to my view? I made a view ("exampleview") that needs an argument: myarg. I can load my page at "exampleview/myarg" and at "exampleview".

When I call drupal_goto(exampleview/myarg), the destination is only "exampleview".

I get the same result with $arr = array('exampleview','myarg');.

Can anybody help me?

This is from drupal_goto

  Usually the redirected URL is constructed from this function's input parameters. However you may override that behavior by setting a destination in either the $_REQUEST-array (i.e. by using the query string of an URI) This is used to direct the user back to the proper page after completing a form. For example, after editing a post on the 'admin/content'-page or after having logged on using the 'user login'-block in a sidebar. The function drupal_get_destination() can be used to help set the destination URL.

It seems like your destination parameter is set so you have to clear destination parameter or use header function


How can I programatically select the node template to render a node in Drupal 7 I have a node--mynodetype.tpl.php, the problem that I have is that I have a module to show public contents.

In this module I need to render something completely different to what is in node--mynodetype.tpl.php.

So I was thinking to create a file named, for example, node--mynodetype-public.tpl.php but I was googling and I can't find a function to select one node template or other node tpl.

Is this any function to select wich node template to render?

Thanks in advance.

Unless I am missing something here, this is a classic job for hook_preprocess_node(), eg...

function YOURMODULEORTHEME_preprocess_node(&variables) {

  if ( /* whatever logic */ ) {
    $variables['theme_hook_suggestions'][] = 'node__YOURNODETYPE_public';
  }

  // other preprocessing here

}

...which would cause Drupal to look for a node--YOURNODETYPE-public.tpl.php template when whatever logic was true.

Read Working with Template Suggestions and Theme Suggestions for a lot more info on all of this.


How to use composer for installation profile? I have a Drupal 8 installation profile with custom modules and themes and I am wondering how should I use composer so that I can run it and drupal core and other dependencies(like contrib modules) would get properly downloaded(and also Drupal's cusom composer stuff would get properly applied as well)?

Is this possible at this time or the composer approach is still not complete?

You need to use the Composer Manager, which search the composer.json file in any module add the dependency on the core composer.json

How to handle the dependency ? By writing a composer.json file that contains all the php libraries that are been load it.

Here is an example of a good composer.json

{
  "name": "drupal/mobile_detect",
  "description": "Mobile_Detect is a lightweight PHP class for detecting mobile devices.",
  "type": "drupal-module",
  "homepage": "http://drupal.org/project/mobile_detect",
  "authors": [
    {
      "name": "Matthew Donadio (mpdonadio)",
      "homepage": "https://www.drupal.org/u/mpdonadio",
      "role": "Maintainer"
    },
    {
      "name": "Darryl Norris (darol100)",
      "email": "admin@darrylnorris.com",
      "homepage": "https://www.drupal.org/u/darol100",
      "role": "Co-maintainer"
    }
  ],
  "support": {
    "issues": "http://drupal.org/project/mobile_detect",
    "irc": "irc://irc.freenode.org/drupal-contribute",
    "source": "http://cgit.drupalcode.org/mobile_detect"
  },
  "license": "GPL-2.0+",
  "minimum-stability": "dev",
  "require": {
    "mobiledetect/mobiledetectlib": "~2.8"
  }
}

This composer.json is for the mobile_detect drupal module. Once you run the core composer.json this will download the mobile_detect library into the vendor directory and support autoload. And you can do the same thing with your libraries.

For more information about D8 and composer I will recommend reading this article - https://bojanz.wordpress.com/2015/09/18/d8-composer-definitive-intro/


Reference View in Entity Reference field I have a content type that has an entity reference field allowing you to link to other pages and add a custom image, for nice big CTAs.

However, it's come to light that some of the links may need to be to Views that show content as a list or map.

The ER field has autocomplete enabled and it can't find the view by its URL e.g /my-view

Is there a plugin that would allow the field to find Views? Or do I have to change the content type and add a Link field instead?

Views are config entities so you can target them to be referenced (see screenshots) and check this post.

The caveat is you can only point to a given entity type when using ER fields so you cannot have an ER field targeting content and config alike.

On the other hand almost any market solution referencing views aim to render it not just displaying a link pointing the view.

As you suggest using a link field can work around with your use case but the link form element only autocompletes content entities, you cannot type your views' display title and wait for it to get the proper URL for you. For that I'm afraid you need to provide your own widget/form element (and controller). Check this and this about how to build your own autocomplete widget/form element for a text field and this post from Drupal.org docs on how to build your own field formatter.

Also worth noticing that Views URL's are used on limited display types (Page, Feeds, possibly 2 more but I'm not quite sure) and is considered a route, not a path or link like when building a menu link item.

Hope this points you in the right direction.


Add class to Previous / Next Button In Webform 7 I was able to add classes to the Previous / Next Page button but can't seem to be able to do this with Webform 8.

Is there a way to do this?

You need to 'Customize' your submit buttons via the button/link at the bottom of the form builder.


Profile field create and set default value programmatically I need the checkbox to be checked by default.  Below is my code, notice the 'default_value' under the settings array.

$field_instance = array(
    'field_name'    => $fielddef['field_name'],
    'type'          => 'list_boolean',
    'entity_type'   => 'user',
    'bundle'        => 'user',
    'label'         => t($opts['label']),
    'description'   => t($opts['description']),
    'required'      => FALSE,
    'widget'        => array(
        'type'      => 'options_onoff',
        'weight'    => 10,
    ),
    'settings'      => array(
        'allowed_values' => drupal_map_assoc(range(0,1)),
        'default_value' => array(array('value' => 1))
    )
);
field_create_instance($field_instance);

I have tried using 'default_value' in the $field_instance array, I've also tried 'default_value_function' without success.  I feel like I'm close on this, what am I missing? Thanks!

Also, I am running Drupal 7.23 as shown on my Status Report.
I asked this question earlier on SO, but no reply so I moved it here: https://stackoverflow.com/q/19772646/988355

Try with this

$field_instance = array(
'field_name'    => $fielddef['field_name'],
'type'          => 'list_boolean',
'entity_type'   => 'user',
'bundle'        => 'user',
'label'         => t($opts['label']),
'description'   => t($opts['description']),
'required'      => FALSE,
'widget'        => array(
    'type'      => 'options_onoff',
    'weight'    => 10,
),
'settings'      => array(
    'allowed_values' => drupal_map_assoc(range(0,1)),
    'default_value' => array(1),
)

);


How can I execute a JavaScript function before the form submission handler is called? I was trying to save an image in the database using the following code.

function myid_user_page_form() {
  $form = array();
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Save',
    '#attributes' => array(
      'id' => 'myid_save',
    ),
    '#submit' => array('formsave_action'),
  );

  return $form;
}

function formsave_action($form,&$form_state) {
  $save  = db_update('student',array('target' => 'import'))
    ->fields(array('id_status' => '1'))
    ->condition('stud-id', '101-03043', '=')
    ->execute();

  if ($save) {
    drupal_set_message("Successfully saved.");
  }
  else {
    drupal_set_message("Unsuccessfully save.");
  }
}

The JavaScript file content is the following.

 $('#myid_save').on('click', function(e) {
   myid_save_signature();
   myid_save_photo();
 });

In my case, the two JavaScript functions aren't called; the page refreshes before they are executed. I want to run those functions before formsave_action() is called.
How can I achieve this?

Remove #submit.

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => 'Save',
  '#attributes' => array(
    'id' => 'myid_save',
  ),
);

Your submit function should be myid_user_page_form_submit rather than formsave_action. If your form's function name is myform_form, then you just need to write the submit handler like myform_form_submit. It will consider it automatically.

Now change your js to :

$('#myid_save').on('click', function(e) {
    myid_save_signature();
    myid_save_photo();
    $('#myid_save').submit(); // Add this line
});

It will submit your form using jquery.


Disable select drop-downs, display names only I am looking for a way to remove the select drop-downs from the datepicker popup and display only months (and the year). As for the appearance, it can be altered in datepicker.1.7.css.

How do I disable the select drop-downs and show only the names?

As of date_popup 7.x-2.9, you can do this in your theme or custom module, implementing hook_element_info_alter(&$type).

function mytheme_element_info_alter(&$type) {
  $type['date_popup']['#datepicker_options'] += array(
    'changeMonth' => FALSE,
    'changeYear' => FALSE,
  );
}


Views Json Source data Cached I'm using the Views Json Source module to load information from a Views Rest Export page on an other website into another website.
But for some reason the view is stuck with old information. I'm pulling in a calendar from the source site. But even though the data from the source site is changing the data in the other site is not.
To solve this I disabled cache for both views but without success When clearing cache on the source site and then the other site the data is changed.
What can I do to make the view look at the rest export on every load of the block?

To fix this I uninstalled the module and created my own javascript function. Here I had the same problem. Making me realize the problem was caching in some form. The answer to the question was simply adding a query of the current date to the url.
For more informatie: Views rest export does not update


How to set up content writers to produce articles in their own languages After spending hours on the Entity Translation and Fields modules I still can't configure a Drupal site, how do I achieve this:

When a content writer logs in and create a node and drops down to their language, it automatically puts their country prefix in front of it: th/this-is-my-article. Currently it allows the drop down, but when created seems to be in English

Tried this through path auto, doesn't let me add the 'th' bit on

Translate all nodes automatically - surely I don't have to physically click each node after I've created it to add another language? This cannot be correct?

Any help welcome.

I manage multilanguage sites with lingotek module, but it can be with other modules,to prevent a user to upload a node in a wrong language, with rules module add a rule, event: Drupal is initializing, condition: compare user language with current language, action: page redirect, change language or whatever to prevent it to be in wrong language. once uploaded you can translat it. with lingotek configure your contentype to be auto-translated when uploaded.


t() function - get specific language As twig does render templates in the UI language instead of the content language, all the t() functions deliver the default language. In my case this is wrong as the ui language is german but the content language can vary.

Can I tell the t() function to deliver the translation for Spanish for example?

You can choose the target language, see more information in the API.

In code it would look like this.

$variables['string_in_spanish'] = t(
  'Hello World',
  [], // (The args in the string)
  ['langcode' => 'es'] //  The options
);

note that when using the t() function, the source language has to be English.


Is it possible to create a graph out of collected information stored in a Drupal database? I am new to Drupal. As a beginner I want to create a website which needs to store lots of information. And from the collected information (statistics), I want to map a graph (or chart) out of it.

My Question: Can it be done using Drupal?

You can use Charts & Graphs, Charts or View Charts module. Through this you can show information in the form of graph.


How do I display a username on their profile pages? Using Drupal 8, I simply want a user's profile (or account) page to show its username, like so:

For username "bob":

Username: bob

Do I add a computed field? What's a line of code would I use?

Do I add a computed field?

No

  What's a line of code would I use?

In your theme's .theme file add:

/**
 * Implements hook_preprocess_HOOK().
 */
function THEMENAME_preprocess_page_title(&$variables) { // your theme might already have this function/hook.
  $user = \Drupal::request()->attributes->get('user');
  if ($user instanceof \Drupal\user\UserInterface) {
    $variables['title'] = t('Username') . ': ' . $user->getAccountName();
  }
}

Note: Clear/flush the cache for changes to kick in.


How to backtrace a variable in php template Currently I am in a .tpl.php file, and have the following piece of code:

  <?php if ($rows): ?>

    <?php print $rows; ?>

  <?php elseif ($empty): ?>

    <?php print $empty; ?>

  <?php endif; ?>

It seems extremely difficult to figure where the $rows variable comes from. Any good idea?

You can do it using devel module and ddebug_backtrace() api function exposed by devel..

Below is the function call stack for page.tpl.php executed using below command..

<?php dpm(ddebug_backtrace());?>

I believe above tpl is related to views module... $rows are generated dynamically by views module based on your views settings...


run-tests.sh error: Test class not found Hi and thanks in advance for your patience - I really appreciate the patience this community has shown me despite my silly questions. I'm using Drupal 9 and have just read this tutorial on unit testing in Drupal 7, but it doesn't seem to be working for me. It's unclear to me whether I'm doing something wrong or the instructions simply aren't valid anymore:
www-data@fa5bab330dc3:/opt/drupal/web$ php core/scripts/run-tests.sh --verbose --url http://example.com/ --class "Drupal\Tests\rsvplist\Unit\RSVPListServiceTest"
  ERROR: Test class not found: Drupal\Tests\rsvplist\Unit\RSVPListServiceTest

I have tried pointing run-tests.php to a specific directory but that doesn't seem to work either:
www-data@fa5bab330dc3:/opt/drupal/web$ php core/scripts/run-tests.sh --verbose --url http://example.com/ --directory modules/custom/
  ERROR: No valid tests were specified.

I tried the above with variations on the directory, including modules/custom/rsvplist and /opt/drupal/web/modules/custom/rsvplist/tests/src/unit/ (the location of the test file itself), but always got the same error.
When running unit tests via phpunit directly I seem to be able to get it to work:
www-data@fa5bab330dc3:/opt/drupal/web/core$ phpunit ../modules/custom/rsvplist
PHPUnit 8.0.0 by Sebastian Bergmann and contributors.

Testing ../modules/custom/rsvplist
R                                                                   1 / 1 (100%)

Time: 123 ms, Memory: 6.00 MB

There was 1 risky test:

1) Drupal\Tests\rsvplist\Unit\RSVPListServiceTest::testSomething
This test did not perform any assertions

/opt/drupal/web/modules/custom/rsvplist/tests/src/unit/EnablerServiceTest.php:14

/opt/drupal/vendor/phpunit/phpunit/src/Framework/TestResult.php:860
/opt/drupal/vendor/phpunit/phpunit/src/Framework/TestSuite.php:761
/opt/drupal/vendor/phpunit/phpunit/src/Framework/TestSuite.php:761
/opt/drupal/vendor/phpunit/phpunit/src/TextUI/TestRunner.php:632
/opt/drupal/vendor/phpunit/phpunit/src/TextUI/Command.php:208
/opt/drupal/vendor/phpunit/phpunit/src/TextUI/Command.php:164

OK, but incomplete, skipped, or risky tests!
Tests: 1, Assertions: 0, Risky: 1.

I'd like to run my tests via run-tests.sh as I'd like to use the Drupal\KernelTests\KernelTestBase class so that I can mock out database connections, and as I understand it this should be done via run-tests.sh and not phpunit. Obviously I'd like to resolve the errors above but I'm also happy to be shown a different / better way of achieving what I'm trying to do.
Here is my test class, located in modules/custom/rsvplist/tests/src/unit/EnablerServiceTest.php:
<?php

namespace Drupal\Tests\rsvplist\Unit;

use Drupal\Tests\UnitTestCase;

class RSVPListServiceTest extends UnitTestCase {
  public function testSomething() {
  }
}

The solution ended up being:

Make sure the test file is named as the test class, in this case RSVPListServiceTest.php.
Make sure my unit tests are placed in the correct directory structure, in my case my RSVPListServiceTest.php file had to be in modules/custom/rsvplist/tests/src/Unit/EnablerServiceTest.php (as opposed to unit with a lowercase u)

The ERROR: No valid tests were specified. message ended up being a bit of a red herring, and I've submitted a patch to drupal to make this message clearer: https://www.drupal.org/project/drupal/issues/3170651


How do I print a value from a custom user field on page.tpl? I have a integer field connected to my users that I would like to print out in the header of my site. I would like to display the value of the field for the user that is currently logged in. When I do print dpm($user) it shows me information about the currently logged in user, but not any of the custom profile fields associated with them.

First I want to thank @mototribe and @Kimi for helping me figure this out.  I was able to get access to my field by putting

<?php
global $user;
$user_fields = user_load($user->uid);
$MYVARIABLE = $user_fields->field_MYFIELD;
?>

at the start of my page.tpl.  Then I had to print it out by adding this to my page  <?php print $MYVARIABLE['und'][0]['value'];?>


How to access a contributed module Information from drupal.org Is there any API to access Information about a contributed module
from drupal.org site?
How does Update Manager access information
from drupal.org?

By finding this I think I too could access other data similarly and I also need Hook API documents to be accessed from drupal.org in my site.

Did anyone do this before? If so please guide me.

An update URL is formatted as:

http://updates.drupal.org/release-history/[project-name]/[api-version]

So for Views v7, for example, that would be:

http://updates.drupal.org/release-history/views/7.x

I think that's as much information as Drupal.org makes available about modules via its API. You won't find a structured way to query information about hooks, for the same reasons we talked about in your similar recent question


How do I make a multi item table order list for Drupal Commerce? I have several items that should be allowed to be ordered on one page using Drupal Commerce. Take the example of dairy products. There should be a table of dairy items a person can purchase such as milk, cream, butter, and cream cheese. Each of these items should be viewed as a row of a table in the dairy page. The customer should be able to mark the number of each item they want to purchase and submit the form using a purchase button at the bottom of the table. How is this done using Drupal Commerce? The checkout view does just this. Is it possible to create views that do this too?

Here is an image of the checkout form that does this.

I think you're looking for the Commerce Add to Cart Extras module. You can use this with Views to build your own lists of products and add multiple quantities of multiple products with one click.


Enable CKEditor on a field with a custom widget I have a custom widget for a field that hides the field if certain conditions are not met. My custom widget field extends the StringTextareaWidget class as a base. When it renders, my widget never displays ckeditor.

If I change the display widget to "Text Area (multiple rows)" ckeditor displays as expected.

To test my code, I commended out everything except the class declaration that extends StringTextAreaWidget, and this also prevents the ckeditor from displaying when the widget is rendered. How do I get my custom field widget to display with ckeditor?

I was extending the wrong class from my field widget. The proper class to extend if you're looking to use CKEditor is TextareaWidget


Which IPs/hosts does Drupal query for updates? I recently migrated a Drupal 7 installation from my own development server to a hosted solution, which runs all nice and dandy, however Drupal now can't load the data anymore to check for available updates.

It says,

  Fehler beim Abrufen der Daten über verfügbare Aktualisierungen.

Or in English, I think the translation is:

  No available update data

I asked the technical support of the web hoster if they could remove any kind of firewall or filter that'd block Drupal's external requests, and they replied to me that they needed to know which URLs / IPs or hosts are called so they could whitelist them.

What are these URLs?

From update.module:

/**
 * URL to check for updates, if a given project doesn't define its own.
 */
define('UPDATE_DEFAULT_URL', 'http://updates.drupal.org/release-history');

Each module and theme is allowed to define it's own URL, it'll be in it's info file, but this one will cover most cases.

Note you need an access to all paths under this one, ie for Views updates Drupal will query http://updates.drupal.org/release-history/views/7.x


files[] not working on module_name.info I am having problems making my module work.

module_name.info

...

files[] = module_name.module
files[] = module_name.pages.inc
files[] = module_name.admin.inc
files[] = module_name.install
files[] = module_name.controller.inc

...

But when the module should access to functions stored on module_name.module I get this error, saying the function has not been found.

Warning: call_user_func_array() expects parameter 1 to be a valid callback....not found or invalid function name in call_user_func_array() (line 517 of /path_to_modules/module_name/includes/menu.inc). =>

If I put the functions on the module_name.module file, everything works fine. Apparently is not loading the files[]

Update: I've followed this example:
https://github.com/LearningDrupal7Development/artwork

Any idea?

files[] is only used to register files containing classes or interfaces, not functions. The docs explain it well:

  Drupal now supports a dynamic-loading code registry. To support it, all modules must now declare any code files containing class or interface declarations in the .info file, like so:

name = Really Neat Widget
...
files[] = example.test

  When a module is enabled, Drupal will rescan all declared files and index all the classes and interfaces that it finds. Classes will be loaded automatically by PHP when they are first accessed.

emphasis mine. Unless you have classes in any of those files (including the .module and .install file) that you want to be auto-loaded, you don't need an entry for them in the .info file; it just won't do anything.

If you need to pull other files in you can use module_load_include(), e.g.

module_load_include('inc', 'module_name', 'module_name.controller');


How do I check the access to every node? I need a quick solution to restrict access to nodes based on the contents of field. I've built the skeleton of a module and managed to restrict access to a custom route.
Now, the service that redirects to access check is this:

services:
  access_check.untitled_check:
    class: Drupal\untitled\Access\UntitledAccessCheck
    tags:
      - { name: access_check, applies_to: _access_untitled_check }

This only applies to routes with _access_untitled_check in the requirements array.

How can I have all nodes  checked?
Can I add _access_untitled_check to nodes' requirements array?

There are several ways to do alter or hook into node access. You can find out more by reading the Node Access Rights page on api.drupal.org.

Briefly node access works like this (paraphrasing from the aforementioned documentation page):

Users with 'bypass node access' are granted access.
Invoke implementations of hook_node_access
Invoke implementations of hook_node_grants

Finally,

  To see how to write a node access module of your own, see node_access_example.module.


Drush on windows - Command pm-enable needs a higher bootstrap level to run I installed aquia drupal and added a core drupal folder into the sites list.

I also installed the windows installer of drush, it works ok for downloading modules but when I try to enable them I get this screen:

C:\Documents and Settings\Administrator\Desktop\drupal>drush en ctools
Command pm-enable needs a higher bootstrap level to run - you will       [error]

need invoke drush from a more functional Drupal environment to run
this command.
The drush command 'en ctools' could not be executed.                     [error]

Drush was not able to start (bootstrap) the Drupal database.             [error]

Hint: This error often occurs when Drush is trying to bootstrap a
site that has not been installed or does not have a configured
database.

Drush was attempting to connect to :
  Drupal version    : 7.9
  Site URI          : http://default
  Default theme     : garland
  Administration theme: garland
  PHP configuration : C:\Program Files\Propeople\Drush\Php\php.ini
  Drush version     : 5.0-dev
  Drush configuration:
  Drush alias files :
  Drupal root       : C:/Documents and
Settings/Administrator/Desktop/drupal
  Site path         : sites/default
  Modules path      : sites/all/modules
  Themes path       : sites/all/themes
  File directory path: sites/default/files
  %paths            : Array

You can select another site with a working database setup by
specifying the URI to use with the --uri parameter on the command
line or $options['uri'] in your drushrc.php file.

Anyone know how to solve this?

As a side note, whats the easiest way to get drush with the bash working on windows? Any good tuts?

This particular error happens when drush cannot find the settings.php file to read in and "bootstrap" itself.

You need to cd into the drupal directory (Document root) of your drupal install in order for it to read in a settings.php file.

Looks like your pwd (present working directory) is on your desktop. Which i'm going to make a quick assumption that that directory isn't where your drupal install is located at.

  As a side note, whats the easiest way to get drush with the bash
  working on windows? Any good tuts?

I highly recommend looking into installing/using Cygwin on windows; as it's a slight improvement.

From there you'll be able to do more things with Drush. The sql-sync and several other functions i hear don't totally work reliably. For even more bonus points you may want to move to a linux or mac environment (something that has a terminal built in).

If you must stay with windows, please consider a drupal project called, quickstart, that creates a virtual machine that allows you to run ubuntu through a remote desktop terminal.


How to customize drupal node using 'PANELS' I am trying to implement the "PANELS" module in drupal 7.31 to customize a page display.

Panels Module : 7.x-3.4

Drupal version : 7.31

I have created courses(as a product) using "COMMERCE" module. I am able to display the LIST Courses
using Panels. But I am also want to customize the course detail page(User click on course and then redirect to detail page).

You can see list of courses using Panels on here:

Now I want to customize the detail page where all details show from Database using Panels.

You can also see Course Detail page here:

You can't customize the node detail page with panels. You will have to use display suite. DS allows you to do a lot of things, and one of them is "Display Suite allows you to take full control over how your content is displayed using a drag and drop interface."

Hope this helps