How to print Promoted to front page to new block? I have article,news,video types for content. Now I checked Promoted to front page for print article/news/video, etc content to any block. Now, how to print 10 result Promoted to front page article/news/video to new block of index using views Module?

If I understood you correctly, you want to show 10 posts promoted to the front page in a block.

The Views module comes with a "Front page" view. By default, it is disabled, and you need to enable it. Once you did it, you can edit it: Click on edit.

On the next page, click on the "Add" button you see on the top left, and select Block.

On the next page, select "Access: None" under Block settings. (The link is just the None word.) Change the access to Permission (first page), and View published content (second page). (To pass to the second page, click on Apply.)

Save the view. (The button is on the top.)

On admin/structure/block, select the block you just created, and assign it a region where it should appear. Its name is View: Front page, if you didn't change the default one, which is None.

This is the result.

I changed the access settings because I enabled the view which was not enabled, yet. If you are already using the Front page view is not necessary to change the access settings, if not in the case you want the access settings for the block to be different from the page settings. In this case, be sure to select "This block (override) as in the fourth screenshot.


How should I define a MENU_LOCAL_ACTION menu item, and which is the involved page callback? Looking at user_menu() to check the answer for another question, I noticed the function contains the following definition.

  $items['admin/people/create'] = array(
    'title' => 'Add user',
    'page arguments' => array('create'),
    'access arguments' => array('administer users'),
    'type' => MENU_LOCAL_ACTION,
  );

The page callback is not explicitly defined.

Reading the definition of MENU_LOCAL_ACTION given in hook_menu(), I read  the following:

  MENU_LOCAL_ACTION: Local actions are menu items that describe actions on the parent item such as adding a new user or block, and are rendered in the action-links list in your theme.

That doesn't explain which is the involved page callback that is called to handle that menu item.

Which is the page callback that is called to handle a MENU_LOCAL_ACTION menu item? Is there any other property that is necessary to define such menu items?

Router items can inherit properties from parent paths.

In this case, the page callback is inherited from the 'admin/people' path:

$items['admin/people'] = array(
  'title' => 'People',
  'description' => 'Manage user accounts, roles, and permissions.',
  'page callback' => 'user_admin',
  'page arguments' => array('list'),
  'access arguments' => array('administer users'),
  'position' => 'left',
  'weight' => -4,
  'file' => 'user.admin.inc',
);

The fact that the menu item is a MENU_LOCAL_ACTION doesn't actually come into it, the same is true of any type of item.

So if you define a router item like this:

$items['mymodule/path'] = array(
  'title' => 'Something',
  'page callback' => 'mymodule_page_callback',
  'access callback' => 'mymodule_access_callback',
);

And then define one like this:

$items['mymodule/path/sub-path'] = array(
  'title' => 'Something',
  'type' => MENU_LOCAL_ACTION,
  'access callback' => 'mymodule_access_callback',
);

The page callback will be inherited from the 'parent' item.


Rebuild the entity field maps After deleting some fields and paragraph types, I have stale values in the entity field map - these cause notice-level errors in the /admin/reports/fields page, and seem to occasionally trigger weird exceptions.

I've tracked the stale data to entity.definitions.bundle_field_map entries in the {key_value} table. Unfortunately, neither running cron nor synchronizing the configuration nor clearing the cache seems to update this.

I've deleted the entries from the table entirely, but they just stay gone. Is there a way to completely rebuild the map from the active configuration?

Update: For future reference, this problem (and similar entity schema corruption) was a likely consequence of mucking around with unalterable internals (type, machine name, etc) of existing fields. Never do that; this system is complex, easy to break, and basically impossible to get back into a consistent state without reinstalling or reverting to backup.

Any changes to the storage of a field should be done by creating a new field, copying data, and deleting the old field. Even if you want to retain the existing machine name, it is easier to follow these steps twice (using a temporary field) than to try to touch the internals.

(Also, some aspects of the schema seem to be updated by cron, so before reusing a deleted field's machine name, make sure to run cron to let it perform cleanup.)

Update: It seems this data is never rebuilt in full, but is only updated by a field definition listener.

One possible solution is to remove all fields and bundles from the site (by deleting the configuration from the sync folder and importing), then re-creating them (by reverting the deletions and importing again). This will obviously delete any content that may have been created.


How to fetch HTML created via a Forena report and store it as a node? I'd like to automatically (Rules) copy some HTML into a node . The HTML comes from a Forena report (already as an HTML document), created by the Forena module. In the Rules module I couldn't find anything exactly fitting.

It might be possible to develop a small module that fetches the Forena report (using some of the available Forena hooks) and create a node from it.

But is this the easiest way to go? It feels a bit like a detour, maybe I'm just overlooking some module or feature which can do that task?

You can have a look to the module "Feeds". It's aim is to provide a way to import content (node, term...) from CSV File, XML...

You can also specify interval between two importation. So you won't need rules.


How to sort views table columns alphabetically with exposed filters? I'm working on a table view that will be populated with five columns and many rows of data. I would like to be able to sort the table by selecting a column and then sorting it alphabetically. Ideally, I should be able to sort the table based on any of the columns. Is this possible with views exposed filters? If so, how would I approach this?

Install and configure DataTable module.

Please follow the steps given below:

Create a new view at admin/build/views/add
Add fields to show in the table.
Select DataTables as the view style.

  The DataTables module integrates the jQuery plugin DataTables into
  Drupal as a views style and a callable theme function.


WSOD on administration pages Here are the facts:

Made a clean install of Drupal 6.20
Installed and enabled Admin Menu module

From this point on I can't access any admin/* page however I can access to both node/* and user/*...

PHP log:

No entries

Apache error log:

No entries

Apache access log:

127.0.0.1 - - [10/Mar/2011:16:22:16 +0000] "GET /drupal_testes/ HTTP/1.0" 200 5771
127.0.0.1 - - [10/Mar/2011:16:22:14 +0000] "GET /drupal_testes/admin HTTP/1.1" 200 -

DB table watchdog:

Nothing serious...

And that's all, for a single access to /drupal_testes/admin...
Disabling admin_menu (at the system table) does work. Also, as a side note, when I go to admin/build/modules and try to enable Admin Menu again the page will take forever to load and end in a WSOD.
After that if I go to drupal_testes/node the admin_menu is active and working, except for the admin/* pages.

I'm aware of WSOD Walkthrough but none of the reasons seems to apply this case..
Any idea why can this be happening?

Edit #4

Exactly the same behaviour when installing Token

Edit #5

Installing CCK, which in theory is much heavier than Token or Admin Menu, presents no problems.
Flushing the cache_* tables changes nothing.
Increasing php.ini memory_limit didn't make any difference...

Although the problem is solved by disabling the offending modules, the goal is to have them active and working properly...

If you just started a new site / doesn't contain any data yet as you seem to indicate in your question, it may be faster to reinstall Drupal than search for the source of the WSOD.

Otherwise, you could have a look in the database directly:

first, check the watchdog table: it may have error messages that don't show up in Apache and PHP logs
then, empty the caches by truncating every table named cache_something
then if you're sure this module is the one that caused the problem, you can edit the list of enabled modules in table system: find the module in the list and change its status to "0"

But if you make any modification directly in the database, make sure to save a backup first, just in case ;-)


How to do OR operation on one filter's options of Views 3 I have two content-types Courses and Groups. Courses is added as entity reference field in Group content-type.
One category field is added in courses content-type.

View is created for list of all courses. Category is added as filter. This category has terms. AND operation is applied as default. Like if user has selected term1 and term2 as filters then courses who has both terms selected are only listed. But I want courses who has either term1 or term2 should be listed.
I am using better exposed filter module and checkboxes for category filter options.

Group filter is created for category where I have added terms as :

term1, is equal to, term_id
term2, is equal to, term_Id

Other options are less than or equal to, greater or equal to, greater than, less than, in between, is empty etc. But no any setting using which I can apply OR operation on single field options.

How can I resolve this issue ? Any help would be appreciated.

Thanks in advance.

You should be able to click the arrow next to the criteria and select "And/Or" to change this setting. Here I've added two criteria and set them to "or"


Mobile CSS and media queries? What is the easiest way to create a mobile stylesheet for a Drupal 6 site? Is there a simple way to just create a css file, declare it in the info file add a viewport meta tag to your templates and have it all be automatically recognized by the site pages? Based on my own attempts, I'm thinking it's a little more complicated than that, but maybe someone has a fairly simple solution...?

Take a look at the Omega base theme.  I haven't used this with D6, but the D7 version handles all of the media queries and makes it pretty easy to customize them via the UI settings page.


Views Slideshow with jCycle - Making it 100% flexible repsonsive Currently I have the following in my views:

Title
Image (size original)

I also currently have my image set at width: 100% via my css file. Now, how do I go about configuring the slideshow to take up 100% width to make the slideshow responsive? I installed the json2.js file to enable the advanced features and I see that there is a "fit" and a "width" option.

Do I set "fit" to 1 or true?

As for the width option, it seem to only take px values only. 100% just gets ignored.

Sure I can go and override this via the css file, but i was wondering if there is a more elegant way of doing it via the provided options in views.

An easy way of making the slideshow responsive is by overriding the css something like below:

.views_slideshow_cycle_main {
  width: 100%;
  float: left;
}
.views_slideshow_cycle_main .views-slideshow-cycle-main-frame {
  width: 100% !important;
  height: auto;
}
.views_slideshow_cycle_main .views-slideshow-cycle-main-frame-row {
  width: 100% !important;
  height: auto;
}
.views_slideshow_cycle_main .field-content {
  max-width: 100%;
  width: 100%;
}
.views_slideshow_cycle_main .field-content img {
  max-width: 100%;
  width: 100%;
  height: auto;
  margin: 0;
  padding: 0;
}

The changes you where doing might be getting overriden by default styles as those were taking the precedence.

Reference: views Slideshow for Responsive design

Alternate solution:
Give a try to Flexislider module: Flex Slider module integrates the Flex Slider library with Drupal and several contributed modules which allows you to build responsive, resizable slideshows. Meaning the slideshows automatically adapt to the size of the browser window or device.

Some features of FlexSlider slideshows include:

Touch enabled nagivation
Keyboard navigation
Configurable slide animations
Multiple sliders per page


How to bypass Drupal page cache if a certain cookie is set on a shared domain? I have a drupal web site that lives on the same domain as another non-drupal website.For instance, The site is a.example.com. When my users logs in example.com a certain authentication cookie is set. However, when the user hit a.example.com, the user gets a cache hit. I know that hook_boot is invoked on all pages, however, how do I tell Drupal to bypass cache? Should I set a certain cookie?
I would like to now what is the proper way of doing something like this.

I would suggest looked at the Single Sign options of Drupal or implement some code that logs you into Drupal when they login to the non-Drupal site.

EDIT: first, boostrap Drupal and then run this function:

function drupal_user_login($username, $password)
{
    $uid = user_authenticate($username, $password);
    if($uid)
    {
        $form_state = array();
        $form_state['uid'] = $uid;
        user_login_submit(array(), $form_state);

        return true;
    }
    else
    {
        return false;
    }
}


db_or() returns a SelectQuery-object In my module, I was trying to make use of db_or() in this way...

$filterSparten = db_select($this->tbl_hat_sparte, 'hs')
  ->fields('hs', array('hat_AID'));

$or = db_or();

foreach($_GET['tags'] as $tag) {
  $or->condition('hat_KID', $tag);
 }

 $filterSparten->condition($or)
  ->execute()
  ->fetchAssoc();

...which, unfortunately, only returns a SelectQuery-object:

SelectQuery Object
(
    [fields:protected] => Array
        (
            [hat_AID] => Array
                (...

Why doesn't my code return a fetched results-object? I have compared it several times with the examples on the Drupal-pages, but I can't help myself with it.

Assuming an unchanged core codebase, and assuming you mean that your final line is returning a SelectQuery (not the db_or(), which returns a DatabaseCondition), the only way you could be seeing a SelectQuery is if you're inspecting the wrong variable, i.e. $filterSparten. The query will remain a query, you need to assign the results to something else:

$results = $filterSparten->condition($or)
  ->execute()
  ->fetchAssoc();

Inspecting $results should give you what you're expecting.


"true" 'first' 'last' classes in menus I am building a zen subtheme in which I try to adjust my menus from:

            ...

            ...

too:

 <----- mark the very first

            ...

            ...

 <----- mark the very last li element

another example:

 <----- mark the very first

            ...

I know I can handle each menu item with theme_preprocess_menu_link but I didn't find a solution to have the very first and last item marked as I need to? Any suggestions?

I am not sure that i fully understood what you want; but if what you need is to give special attributes(ID, class etc.) to menu items, Menu attributes module may help. You also could use CSS3 :nth-child() selector.


Sending email notifications to webform submissions I am trying to create a rule that will send an email to a list of webform submissions, notifying them when new content is created. So far, here's what I have:

Event: after saving new content of type [type]

Conditions: content is of type

Actions: Using a Rules view display, I'm grabbing the webform submissions, and then looping through to send mail to the value of the webform submissions.

All works well, until I need to send the mail. Rather than looping through and sending to the email addresses that I'm trying to get from the webform submissions, it appears to be sending to the submission ID instead.

I'm sure there's something I'm missing in either my rules view display, or the rule itself, but I've hit a wall. Anyone know what I might be doing wrong?

To make this work, you should process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions:

load the VBO list of webform submissions that you want to be processed.
add a loop to perform a Rules Action, for each webform submissions contained in your Views results.

Since you want this Rules Action to be "... sending to the email addresses ...", you need to make sure that these email addresses are contained in the Views result (if needed enhance you view to have them included).

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".


Undefined function json_decode() When attempting to update a Drupal 7 site through the UI or Drush, I get Error: Call to undefined function json_decode() in home/xxxxx/drush/includes/output.inc, line 403 , code: 255)

The server is running PHP 7.3 with json enabled - I've verified this with phpinfo(). I'm at a loss here, and even if I apply updates by ftp, I still can't run database updates. Shared hosting without root access.

PHP 7.3.13
Drush 5.9
Drupal 7.x

So I finally found the culprit. A php symlink in the bin directory linking to an old version of php. I guess even though drush showed it was using version 7.3, those scripts used that symlink and was pulling in an older php version. Error is gone and I can finally update through drush.


How do I automatically assign a node to a term? When an user role changes and becomes "writer", there is a rule that creates a new entity type "taxonomy term" name "user name" and assign it to vocabulary "writers". This works.

Now, the user can create stories. When this user creates stories, this content type should be assigned to term "author name" to vocabulary writers.

It is possible without using PHP, simply adding some actions?

If it was me, I would add a term reference field to user, then when the user becomes "writer" and the related term was created I just added that term to user,

Then using rules, when the user creates a story, I would need to attach term to node, likely I have the term Id attached to user so it could be simply attached to node.

in this way no php code is needed.


Drupal Commerce add to cart form alter I'm dipping my toe into modifying a Drupal Commerce form. I want to change a few things with the hook they provide. The form id is: commerce-cart-add-to-cart-form-626 and the id of the submit button is edit-submit.

I created a Drupal module called jch_test

function jch_test_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  $line_item = $form_state['line_item'];
  $product = commerce_product_load($line_item->commerce_product[LANGUAGE_NONE]  [0]['product_id']);
  if ($product->type == 'product') {
    $form['submit']['#value'] = t('Test');
  }
}

...the module loads, but the code does not fire. What am I doing wrong? I'm sure this is a total noob mistake.

Try something like this:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MY_MODULE_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state, $form_id) {

  //drupal_set_message($form_id);

  $form['submit']['#attributes']['value'] = t('Buy Now');

  /*
  $current_product = $form_state['default_product'];
  if ($current_product->type == 'product') {
    // Make alternations for products...
  }
  */

}

You can use the $form_id and/or $current_product to make custom alterations for a specific product(s) and/or product type(s).

Flush Drupal's caches so your custom form alteration hook will be recognized.

Note, I'd also like to point out that once a user changes a value on the add to cart form, and the form is reloaded via AJAX, MY_MODULE_form_commerce_cart_add_to_cart_form_alter() will be called again, which is good.

However, it appears the $form_state['default_product']->language value may only be present the first time the page is loaded. Once the form is reloaded via AJAX, the language value may be empty in this hook, so watch out if your code is depending on it being there!


Custom Block Twig: File field how to get direct link to file? How can I get the direct URL to a file field in twig? I am able to do this for images, but with a file field, it comes up blank.

WORKS

{% set media_img_url = file_url(content.field_background_image.0['#item'].entity.uri.value) %}

DOESN't WORK

{% set media_file_url = file_url(content.field_cta_file.0['#item'].entity.uri.value) %}

#item is as far as I know only added by the image field formatter, so it's unlikely you'll find it in other field types.

Instead you can use the block content entity to get field values, for example:

{{ elements.content['#block_content'].field_file.0.entity.uri.value }}

This works independently of field formatters and as commented by @Kevin also when a field is hidden.


Can a form submit handler return results without using the $_GET array? It looks like the default method for passing the result of handling a form submit is GET.

The following statement will redirect to form/result, where a page callback function will extract $content (the result form processing the form) from the query string (attached to the URL) using the $_GET array:

$form_state['redirect'] = array('form/result', array('query' => array('text' => $content)));

This works, but I do not want $content to be a query string (where it can be edited by the user).

Is there an alternative method (e.g. POST) for passing the value of $content to the page callback?

You can save $content in a session variable, and then redirect the users to a new page. The page callback of that page will then extract the data from the session data.

$_SESSION['mymodule_content'] = $content;
$form_state['redirect'] = 'form/result';

// The page callback then will execute the following code.
$content = $_SESSION['mymodule_content'];

The pros of using session data are:

There isn't the length limit GET data has
The data will not be visible in the browser address bar
The data can be complex like an array, or an object


How to display the input box next to the label in a form? My objective is to improve the look and feel of a form developed in Drupal 7.

By default, I have (as an example):

Name (label)
BLANK INPUT box (below the label)

How to display the label and input box as inline ?

you can do this with css float

A more difficult ways that render the items via php preprocessing before css adjusts the layout) would be to create a php template file and use theme functions for the form in your theme

Here is tutorial that uses both methods http://www.jaypan.com/tutorial/themeing-drupal-7-forms-including-css-and-js

also, it depends on what kind of form you are theming. Here is another example for webforms https://drupal.org/node/1157306


override date module function for label strings changes I configured a exposed filter for a shipping date field on myview with operator "Is between".
I saw two labels,"Start date" and "End date" in myview form.
I wanna change these strings to "From Date: " and "To Date: ".

I have checked the file sites/all/modules/date/date_views/includes/date_views_filter_handler_simple.inc
This file includes the

function date_parts_form()

that includes the codes:

$label = t('Start date');

and

$label = t('End date');

But I don't want to modify this file directly for further maintenance.
I am not certain how to override this function with keeping an original module file.
Please show me the way with circumstantial directory path and file name.

Now I use an Omega sub theme, mytheme. I added to a CSS file, mytheme-alpha-default.css, some styles such as the following:

label {display:none;}
div.some:before {content:"To Date: "; display:block; margin-left: 2.0em;}


Ubercart hook_order and delete So I am wanting to execute some code when an order is deleted in Ubercart. In order to test hooks, I have the following code:

function loaner_uc_order ($op, &$arg1, $arg2) {

  if ($op == 'delete') {
    $sql = "INSERT INTO {testing} (text) VALUES ('you deleted order number')";
    db_query($sql);
  }

}

The problem is it is just not firing. Am I doing this right? I know the query works because I copy/pasted it into a separate area, and it worked fine. I am honestly stumped.

The syntax is ubercart hook order

hook_uc_order($op, $order, $arg2)

Clear your site cache from performance page, The hook is fired for me after clearing the cache.


Inventory or Quantity field TL;TR: Like there is no module like this for D8, how can I create a plugin wich has two fields: one to reference content and onther one to store a number, so I can emulate an inventory.

Hi, I'm using Drupal 8. Is there any module that let me put just a simple number for a node reference? something like an inventory or quantity field.

I've checked for an inventory field on drupal.org but seems to be pretty outdated (drupal 5)

Like an example just image you are going to make an inventory of the animals and plants in a given area; so there is a content type for "animals" and there is a content type for plants (every one with it's own atributes)... and there is a content type "country". So when I'm creating a country I'll like to specify how many dogs, cats, mules, cows, pines, etc does it have. Note that the country has a field that references to the animal or plant node. Using D8, pointing me to an API that let me store and correlate the information can also help me.

This solved my question: https://www.lullabot.com/articles/extending-a-field-type-in-drupal-8

It is an example of how to extend the reference field and also associate a quantity with the reference. It was what I was looking for.


How do I add the file size to a view? After reading and searching through related topics, I have not seen any clear answer about how to show the file size in a Views created file list. Im using Drupal 7 and having File 7.14 field installed.

I was expecting to select a field in Views in order to show it as a third column in a list of files that can be downloaded (after Title and File).

I am not a programmer, and the only related issues I've seen so far is about editing php files.

Currently, as administrator, I see the file size when I edit the node containing the file. Why can this value not be used other than in edit mode?

To be complete I've added the query how it is now:

SELECT node.title AS node_title, node.nid AS nid, node.language AS node_language,   file_managed_file_usage.filesize AS file_managed_file_usage_filesize, 'node' AS  field_data_field_file_node_entity_type
FROM
{node} node
LEFT JOIN {file_usage} file_usage ON node.nid = file_usage.id AND file_usage.type = 'node'
LEFT JOIN {file_managed} file_managed_file_usage ON file_usage.fid = file_managed_file_usage.fid
WHERE (((node.status = '1') AND (node.type IN  ('file'))))
ORDER BY node_title ASC
LIMIT 50 OFFSET 0

Try creating a reference to the file.

Under Advanced in your View, and add a relationship (select File Usage: File).  If you now go to add a new field in your view, you should see a few more options under File, one of them being File: Size.


Drupal, how to display only specific content I'm on Drupal 7, I have a menu like :

HOME
NEWS
BLOG

For now, when I click on HOME, i can see all contents.

I want, when I click on NEWS, redirect the user to /news and only display contents of type NEWS. I want exactly the same for BLOG

I have no idea how can I do that.

Thanks !

If you have used Blog modules to create you blog content type, you would be able to use the default View from blog.

Otherwise you can create your own view and add Filter Criteria: Type.
You can do this using the module Views You can give the path blog to the view.

  You need Views if

  You like the default front page view, but you find you want to sort    it differently.
  You like the default taxonomy/term view, but you find you want to    sort it differently; for example, alphabetically.
  You use /tracker, but you want to restrict it to posts of a certain    type.
  You like the idea of the 'article' module, but it doesn't display    articles the way you like.
  You want a way to display a block with the 5 most recent posts of    some particular type.
  You want to provide 'unread forum posts'.
  You want a monthly archive similar to the typical Movable    Type/Wordpress archives that displays a link to the in the form of
  "Month, YYYY (X)" where X is the number of posts that month, and
  displays them in a block. The links lead to a simple list of posts
  for that month.

  Views can do a lot more than that, but those are some of the obvious
  uses of Views.


Automatic nodetitles and location tokens? In a Drupal 7 site, I want to have automatic node titles taken from user contributed content.

I have Location 7.x-3.x-dev (enabled Location and Location CCK) and Automatic Nodetitles 7.x-1.x-dev.

The problem is location tokens in the automatic title generation tab of the content type are returning empty input. I have tried [node:location:city:?], [node:location:city:0] and [node:location:city], but all three return nothing.

Tokens from the other fields are showing their input properlu.

Any help will be greatly appreciated.

I have taken some good looks at your issue.
At the moment I find that the code for Location CCK is problematic, I managed to make it work with the following modification:

diff --git a/contrib/location_cck/location_cck.module b/contrib/location_cck/location_cck.module
index b302960..443b6a0 100644
--- a/contrib/location_cck/location_cck.module
+++ b/contrib/location_cck/location_cck.module
@@ -657,9 +657,9 @@ function location_cck_tokens($type, $tokens, array $data = array(), array $optio
   $replacements = array();

   // Make sure we have a node.
-  if (isset($data['entity_type']) && $data['entity_type'] == 'node') {
+  if ($type == 'node') {

-    $node = $data['entity'];
+    $node = $data['node'];

     // Get the available fields from the location module.
     $available = location_field_names(TRUE);

The token that worked after this patching was specific to the CCK field I added to my content type:

[node:field_my_location_field:city]

Alternatively, for your goal "...to have automatic node titles taken from user contributed content...", you can use the Node Locations submodule, this works as expected out of the box. The following tokens

[node:location:city]
and
[node:location:city:0]

both worked fine in combination with Automatic Nodetitles.

Hope this helps!


How do I programmatically create a new content type? I'm building a module (my_module) in Drupal 7. It has some functionality and also
will create a new content type. In my_module.install, I implemented hook_install() (my_module_install()).

Can I use more hook_install() to create a new content type (my_module_install()) in this module?
If the answer is yes, how should I do this? Otherwise, should I do this in another module?

If I were you, I would consider using the Features module. The module enables exporting a subset of websites structure into a single feature to facilitate re-using this feature elsewhere.

Also, Features module enabled exporting content types/fields easily, you would just tick a certain content type and Voila! The Features module will generate Drupal hooks for you, and also export the code into a module.


How can users share entities if they have a relation? Im setting up a pretty complicated website, where users are going to have access to a certain nodes depending on which entities the user of the relation has.

with profile 2, i did add an entity reference field, which displays the nodes im going to grant / restrict permissions on the profile registration.

Its going to be something like this:

Me (admin) is going to create a SUB ADMIN user, i set which nodes is he / she going to be able to access.

The SUB ADMIN user, creates users with the role of normal users. The user itself is going to have less privileges than the SUB ADMIN user, and is going to have the same restrictions on the nodes than the SUB ADMIN user.

... i know its a bit complicated, but i would love to know if there's any way to share the entities of the SUB ADMIN user to the user he creates?.

Using this modules right now:
ENTITIES REFERENCE
PROFILE 2
RELATION
SUB USER

Hope you guys could help me... Thanks in advance!.

Do you know about Node Access Relation, it sounds like maybe you want to use it.

  You use or plan on using the Relation module and want to grant users
  access to view/edit/delete content based on their relations.
  You find
  Drupal roles too broad but per-node access controls too much to manage


How to test a MySQL connection How can I test for active MySQL connections? I am trying to move one site to windows platform, and MySQL connections are failing; db_query() returns FALSE.
I am not sure how to use drupal_test_mysqli().

The function is invoked with code similar to:

$success = array();
$url = 'mysqli://username:password@localhost/databasename';

require_once './includes/install.mysqli.inc';
$err = drupal_test_mysqli($url, $success);

Replace username, password, localhost, and databasename with the values correct for your site.
The variable $success will contain an array with a value for each SQL instruction that has been executed with success.


Views programmatically limit results I'm trying to programmatically include a view in a module and need to limit the number of results displayed. I tried something like this, but it doesn't work:

$view->display[$display_id]->handler->options['items_per_page'] = 2;

I also tried, but neither this worked:

$view->display[$display_id]->display_options['items_per_page'] = 2;

Any ideas? Or at least some links to Views 2 programmatically implementation?

Thanks

You are looking for set_items_per_page()(6), set_items_per_page()(7). Essentially the function does what you are already trying to do, but probably you are calling it on the wrong object, so use the function instead, and Views will ensure it's the right object. :)


Declaring highwater property in Migrate I would like to know how to correctly define the highwater property when using Migrate for Drupal 8. I am doing an import from a legacy non drupal database and I should be able to update only the relevant nodes whenever a column highwater changed. According to the official documentation, the solution is to use a highwater property. How to declare it? Is it a property to be set in the Plugin mapping class or is it an entry in the migrate.migration.*.yml file?
Thanks!

highWaterProperty renamed to high_water_property, and moved from the top-level migration plugin configuration into the source plugin configuration.

id: my_migration
source:
  high_water_property:
    name: changed

For more information, see: https://www.drupal.org/node/2795403


How to add multiple taxonomy term to a single node in drupal 7? Using Taxonomy terms auto-complete wizard I can able to add one term to the a node. But I wanted to add multiple terms to a single node? Is it possible? If so, is there any modules or plugins or any configuration options in existing module?

In the above screen shot, I can able to add only one term. But I want to do in the way shown below.

Go to Term Reference Field settings of the content type and change 'Number of values' to  your required value.

For example if you want to allow 2 terms per node change the allowed number of values to '2' from select list. If you want to allow more than 10 or so change the option to 'Unlimited' so that you can insert multiple taxonomy terms to a node separated by 'comma' (,).

Here I've provided screenshot to allow unlimited values. Here 'SECONDTERM' is my    Term Reference of Autocomplete term widget field label name.


How can I downgrade a module with Composer? I updated the following module to its stable version :
https://www.drupal.org/project/commerce_pricelist/releases/8.x-2.0-rc2
This module completely broke my site. There has been no database update. How can I revert to the RC2 version ?

Open your composer.json and search for the line containing drupal/commerce_pricelist
Replace the line by this one : "drupal/commerce_pricelist": "2.0-rc2",
Execute composer update drupal/commerce_pricelist

Or simply run composer require 'drupal/commerce_pricelist:2.0-rc2' as suggested @4k4 in the comments


how to get view_mode from within hook_field_formatter_view I've created a custom field formatter which works correctly. My problem is that I want to differentiate its output depending on whether it's being used in a default or teaser view mode.

The hook_field_formatter_view doesn't seem to provide this.

One way I can solve this is by providing a setting on that formatter (hook_field_formatter_settings_form) with possible values default and teaser. I'd then have to go to the teaser view mode of all content types and configure this setting on all uses of that formatter. I'd then be able to get the setting using $display['settings']. This would work but it's a bad solution since it would be replicating data that is already there and it also requires administrative work.

Is there a cleaner solution to this?

Imho a formatter shouldn't be dependent on the view mode. It's the site builder's choice which formatter to use in which view mode, and through that decide how things look. It sounds to me like you'd be better off either having two formatters, or having one formatter which can be configured.

My understanding of the Drupal way here is that you provide the general purpose tools (just like a module typically provides permissions, but not a new role - leaving it to the site builder to aggregate perms into roles appropriate for their particular needs). Every time I create a new view mode I want to have complete power to make it do exactly what I want.


Querystring in Views ajax_view.js I'm using Views 7.x-3.11 with Better Exposed Filters and Ajax auto-submit in a panels page, and running into some issues that seem to be stemming from code in Views/js/ajax_view.js. I want to make the exposed filters bookmarkable, and I also need to deep link to certain result sets. Because of this, I added some custom js to add the selected form parameters to the URL as the user selects them.

I also have a section that lists all the currently active terms, where a user can click to remove them. In order to update the results from here, I'm calling $('.view-my-view').trigger('RefreshView');.

By default, from here I can see that the ajax_path for submitting the form has been set to the URL with the query string, which doesn't work. From what I can tell, the native ajax behavior is trying to submit the serialized form data to an already-parameterized URL. To change this behavior, at line 38 of ajax_view.js I've changed var queryString = window.location.search || ''; to var queryString = '';

It's pretty apparent that this is going to cause issues with some sort of intended functionality, but I can't determine what that is. I'm afraid I'm losing sight of something bigger-picture here, or not aware of something about how Views handles ajax submission typically.

Can anyone provide an example of a situation where you'd need the original code? Or what the intended purposed of it is?

Edit: Follow-up question that's a little more practical - is there a way I can make an equivalent change in my custom js that would override the default code in ajax_view.js, so that I don't need to alter the module?

I had a similar problem where I wanted to link to filtered versions of an ajaxified view, but the aforementioned line of code in ajax_views.js prevented the view from displaying all results when all filters where cleared. In my use case, I wanted all views filter identifiers removed, but in yours, as I understood it, you need the clicked filter value removed, so you could modify the code accordingly.

The first step is identifying all valid filter identifiers. We want to do that, so we don't parse out all of the query string's parameters, since some of them might serve another functionality. If you don't care about creating a dependency to the better_exposed_filters module you can find the views identifiers from Drupal.settings.better_exposed_filters.views.[view_name].[view_display].filters.
Otherwise, you could expose them in your own Drupal setting through a views hook:

function hook_views_pre_render(&$view) {
  if ($view->display_handler->has_exposed) {
    $valid_identifiers = array();

    foreach ($view->filter as $name => $filter) {
      if (!$filter->options['exposed']) {
        continue;
      }

      $valid_identifiers[] = $filter->options['expose']['identifier'];
    }

    drupal_add_js(array('validViewsIdentifiers' => $valid_identifiers), 'setting');
  }
}

So, now we have the identifiers and in our custom js file we can change the related properties of the views instance(s). The code for my use case is the following, but you can change accordingly:

Drupal.behaviors.fixAjaxQueryString = {
  attach: function(context, settings) {
    if (!Drupal.views || !Drupal.views.instances) {
      return;
    }

    for (var i in Drupal.views.instances) {
      var instance = Drupal.views.instances[i],
          url = instance.element_settings.url;

      // Check for any valid views filter identifiers and remove them
      var validViewsIdentifiers = Drupal.settings.validViewsIdentifiers || '';
      if (validViewsIdentifiers) {
        url = decodeURIComponent(url);

        for (var j = 0; j < validViewsIdentifiers.length; j++) {
          var regExpr = '\\&?' + validViewsIdentifiers[j] + '(\\[\\])?=[^&]*';
          var regExprObj = new RegExp(regExpr, 'g');

          url = url.replace(regExprObj, "");
        }
      }

      // Only the .options.url part is needed for the desired functionality
      // The rest is modified for consistency
      instance.element_settings.url = url;

      if (instance.exposedFormAjax) {
        instance.exposedFormAjax.options.url = url;
        instance.exposedFormAjax.element_settings = instance.element_settings;
        instance.exposedFormAjax.url = url;
      }

      if (instance.pagerAjax) {
        instance.pagerAjax.options.url = url;
        instance.pagerAjax.element_settings = instance.element_settings;
        instance.pagerAjax.url = url;
      }

      if (instance.refreshViewAjax) {
        instance.refreshViewAjax.options.url = url;
        instance.refreshViewAjax.element_settings = instance.element_settings;
        instance.refreshViewAjax.url = url;
      }
    }
  }
};


Add a 'Buy-it-Now' button to an ApacheSolr View So I have built a View that uses Apache Solr to display products on my Ubercart site from the Solr index.  Swell.  Now Ubercart typically lets me add a 'Buy-it-Now'/ Add to Cart button as a field in most views but for some reason in this view that is not possible.

How do I add a 'Buy-it-Now'/ Add to Cart field to this view?

You can use one of the hooks provided by apache solr to alter your search results : hook_apachesolr_process_results

and you could append 'Buy it Now' button as well by using hook_theme()

Apache solr hooks


how to debug a controller not being run my code below results in a page not found when I browse to the path.  How can I debug what is going wrong? I dont see any errors and I have cleared the cache.

mymodule.content:
  path: '/admin/viewfiles'
  defaults:
    _controller: '\Drupal\mymodule\Controller\FileView::content'
    _title: 'File Operations Module Description'
  requirements:
    _permission: 'access administration pages'

thanks i had a misspelling in the router name. thank you all


PHP code in menu links One of many things I want to do in Drupal is to have

Hi: "User name"

link for /users page. (In the future I also want to have a control over visibility of menu tabs and their links depending on the logged user.)

Currently I have a quick, easy and relaxing solution - hacked page.tpl.php which works perfectly. Unfortunately I it is not a perfect (nor profesional) solution because the website will brake down as soon as I update the drupal core.

Is there any way of injecting php code into menu link/title without messing up the core?

I've been thinking about using translation module, menu module, and others but so far I have not been successful. I know that menus in drupal are designed to be static, but there must be a walk-around.

I know that menu_token can solve some of my problems but it does not work for me (when installed I have memory allocation issues in php server or crashing MYSQL).

I finally figured this out.
YES it is possible to have dynamic menus in Drupal.

You start by enabling dynamic access to menu item with the ['alter'] flag and hook_menu_link_alter(&$item).

function mycode_menu_link_alter(&$item) {
    if($item['menu_name'] == 'user-menu'){
        $item['options']['alter'] = TRUE;
    }
}

Note that menu_link_alter works on a menu item (not the whole menu) and needs to be trigered by editing and saving that item (for example disable->save->enable->save->).

Once the menu item is activated, I can use
hook_translated_menu_link_alter(&$item, $map)

function mycode_translated_menu_link_alter(&$item, $map){
    //drupal_set_message("Menu: ".$item['menu_name']." Item: ".$item['title']
    if($item['menu_name'] == 'user-menu'){
        global $user;
        $item['title'] = "Hi: $user->name";
    }
}

Other very useful thing you can do is to disable the menu link

$item['hidden'] = TRUE;

or (my favorite) change the links

[...];
if($item['menu_name'] == 'main-menu'){
   switch ($item['title']){
       case "Home":
            $item['href'] = 'not/home/page';
[...]


Repeated elements in translations of a block view I have a small problem when translating taxonomy terms inside of a block view.

View configuration:

Output:

The translation is correct but the element quantity is incorrect. The idea is to have one of each term in each block regardless of translation.

You have to add a filter:

FILTER CRITERIA

Taxonomy Term: Translation language (= Content language selected for page)

or if the content language is not available when configuring the filter:

Taxonomy Term: Translation language (= Interface text language selected for page)

Otherwise you get a row for each translation, which are then all rendered in the same language, the one of the page, because you have configured this in the section Language in the middle column of the View.


How do I exclude a node from an entity reference field? I have a homepage content type which has a featured_article field, an entity reference field that allows the editor to choose a single node from the Article nodes. That node is displayed as Featured article on the homepage.

Together the featured article on the homepage, I'm rendering a view (block) that displays the latest articles. I would like to avoid the node selected as featured article doesn't appear in the view. How can I achieve this?

This is my first Drupal project (coming from Craft and ExpressionEngine), and I'm struggling to figure out how to properly configure the view. I expect that I need to use a contextual filter together with a relationship, but I haven't had any luck. I could probably work in a conditional in the Twig template, but I'd prefer to keep the logic in the view if at all possible.

Welcome to Drupal Answers :)

You are right, you can do that with the help of a Relationship and a Contextual filter, but details are important.

In your Latest articles Views add the Relationship named something like Content referenced from field_myERfield for your featured article field. Be careful about the wording there because there are two Relationships available for the same field, you want the "backwards" one. Don't require the Relationship, otherwise you'll get no results if your home page isn't an article type.

Add the Contextual ID filter and set it to use the Relationship you've just added. Provide default value and choose Content ID from URL. Under Validation choose Content and Article, and other options that make sense in your case.

Then under More choose Exclude. That is how you exclude the currently featured article(s) from the latest articles list.

If you don't choose Exclude you'll only see the featured article in the results.


Redirecting Drupal multisite non-www to www with varnish / nginx I'm building Drupal multisite with 35 sites (~60 different domains) and I'd like to redirect non-www urls to www regardless of domain.

Nginx is redirecting all domains to Drupal install folder.

I've tried to redirect domains with Nginx without success (is that even possible because of varnish?)

I was able to redirect single domain with Varnish (something like "if domain == xxx then redirect to www.domain.tld"), but I don't want to make own redirect rule for every domain.

I was able to do it with the following nginx config:

if ($host !~* ^www\.) {
   rewrite ^(.*)$ http://www.$host$1 permanent;
}


Show item as local task but hide if argument is not provided I have three tabs and third have wildcard in path. I added access callback for this menu item that checks if no argument then close access. The tab not shows afte that but ther is error "Notice: Undefined offset: 1 in _menu_translate()". So how correctly hhide this tab?

Access callback that I wrote:

/**
 * System log view access callback.
 */
function ebanq_custom_system_log_view_access($log_id) {
    return is_numeric($log_id) && user_access('access content');
}

I solve this by argument load function, but I don't think it is correct to do like this.

// Menu item change
//....
'system-log/%ebanq_custom_log_id/view' => array(
//....

/**
 * Implements hook_load().
 */
function ebanq_custom_log_id_load($arg) {
    if (!is_numeric($arg)) {
        return FALSE;
    }
    return $arg;
}


Get filename in webform with Rules I need to get just the file name from a file submitted in a Webform.

In actions, I try to execute the following code at a "Show a message on the site" action:

$path = "[data:component-value]";/*a REPLACEMENT PATTERN that return http://mysite.com/files/webform/submittedfile.pdf*/
$file = basename($path);/*$file is set to "submittedfile.pdf"*/
echo $file; /*this *should* return submittedfile.pdf*/

But ALWAYS return http://mysite.com/files/webform/submittedfile.pdf

I've tested ltrim, rtrim, god_trim_for_me and chop. And it always return the full URL.

What am I doing wrong?

I have managed to find an answer to my question

What I am doing wrong:

$path need set before.

In the value: [data:component-value]
Named the variable (ex: link_from_hell)

So, the next action you can manipulate the $patch.


Fixing D7 Bug: Block caching within views breaks JS I have a number of block on pages throughout my site which use views. Within these blocks I have slideshows(flexslider) or use masonry to produce a dynamic layout. If I enable block caching the JS within these blocks does not function correctly. Disabling caching on these blocks restores the functionality.

I am hoping to fix this problem and have a cached blocked with it's JS functioning normally.

I have found some information on this exact issue for the flexslider module (https://drupal.org/node/1873970) but it is not a complete fix. It states that the issue is within views and points to an issue there: https://drupal.org/node/1460766 . There is also the SE Q&A  at https://stackoverflow.com/questions/9788138/jquery-flexslider-not-loading-verytime which provides some insight to the issue when flexslide is used as stand alone rather than with views.

There are dozens of issue, especially within Views Slideshow (probably because it is one of the most popular Views Plugins) which make reference to this issue all the way back to 2009 but the are no actual fixes.

It is also worth noting that the page can be cached without JS breaking. It is only when the block is cached that things go wrong. In my current implementation cached page but not block adds ~1.5 seconds in load time.

With Views and JS being so widespread and caching being as important as it is I am surprised this issue has not been solved, or maybe I am misunderstanding the issue.

Has anyone encountered this issue and found a fix for it?

I welcome any comments or feedback that would improve this question or help move towards a solution for this widespread issue.

This is indeed an annoying bug.

I'm still looking for a permanent solution as well.  Meanwhile, I have been able to mitigate the effects of this bug by doing the following:

Install and enable Cache Expiration module
Setup the expiration setting of your content types or taxonomy terms so that cache for the problematic pages is expired on insert/edit/delete (adjust to your needs)
Implement hooks:
hook_entity_insert, hook_entity_update, hook_entity_delete and manually delete panels / views / block cache of the problematic blocks/content.
For example: cache_clear_all('my_view:my_display', 'cache_views_data', TRUE);

This is obviously far from perfect, since it forces regeneration of cache at every update but it does help in displaying content properly.


Re-using / Customizing content types I have constructed a content type, 3 fields are timestamps.

I wish to reuse this content type (form input etc) to a client facing application, with the caveat being the form is modified. For example my module should be able to tweak the form (ie: Hiding the timestamps fields and updating them accordingly).

I don't want to rebuild the whole form and muck with the CCK API to get data to persist, so I am wondering if it is possible to simply re-call that form and it's functionality and tweak it ever so slightly???

I found this googleing:

//Showing a node edit page with drupal_get_form() and hook_menu()

And implemented some of it:

function _tasks_create() {
  module_load_include('inc', 'node', 'node.task');

  $nid = '1';
  $node = node_load($nid);

  return drupal_get_form('task_node_form', $node);
}

function tasks_menu() {
  $items = array();

  $items['tasks/create'] = array (
    'type' => MENU_CALLBACK,
    'title' => t('Create New Task'),

    'page callback' => '_tasks_create',
    // Where is $node coming from???
    'page arguments' => array('task_node_form', $node),

    'access arguments' => array('create tasks')
  );

  return $items;
}

But I see two immediate issues:

$node in hook_menu is undefined -- where do I get it from??
I have no idea what the $nid (Node ID) will ever be for my content type

I need to essentially re-display the form that I use in the admin, hiding everything but maybe three fields (that means no URI, menu options, etc).

I will probably need to hook into the submission of the form in this context only and update the timestamps accordingly.

What am I missing or doing wrong? Any ideas?

Alex

Clive's answer is right.. You can not pass $node object before you created yet. If you want to show the same form which is shown in the /admin section you can do something like this:

function tasks_menu() {
  $items = array();

  $items['tasks/create'] = array (
    'type' => MENU_CALLBACK,
    'title' => t('Create New Task'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('task_node_form'),
    'access arguments' => array('create tasks')
  );

  return $items;
}

and:

function task_node_form($form, &$form_state) {
  $form = array();
  $node = new stdClass();
  $node->type = 'YOUR TYPE';

  field_attach_form('node', $node, &$form, &$form_state, $langcode = NULL, $options = array())

  // Other code
}


Profile as in a Social Network Site i am creating a social network site. I want when the users clicks join after entering his initial details such as name, email and password (the user does not need admin approval for account to be created) he or she is taken to a user registration page which looks like:
http://imgur.com/fa31Xt1

i know how to add fields from admin/settings/people but should i use profile 2 module? if so how exactly...also once the user clicks save profile (as in link above) then he or she is taken to his profile page where he can view his profile

You can control how the user is redirected after login using the Rules module.  Create a rule using the event User logs in and action Redirect to page.  You can create as many redirect rules as you need to get the user to go to the appropriate destination.

For example, for my social networking site, I do the following:

redirect users who haven't completed their profiles to a page telling them they need to do that (condition: user doesn't have profile_completed role)
redirect users who have completed their profiles and have new messages (from private message module) to the message inbox (condition: custom PHP condition)
redirect all other users to the search screen

In my implementation, I actually implemented this as a rule set (component) instead of a bunch of individual rules so that I could easily achieve the third option ("redirect all other users").


How to make my mobile app to work more faster when web services made from drupal7 REST services We did an app based on drupal web services(REST server). The thing is the app is very slow on the device. The reason for this may be, the app requires 3 webservices to load initially. lile

http://myapps/api/node?parameters[type]=Company

From the above web service i will get all node under CCk company. then to get the details of the node i need to pass another url as http://myapps/api/node/5 and then to get the taxonomy term to which ths company belongs to i need to pass another url. there by it is taking much time to load. Is there any solution to make my app faster?

I'm used to create my own resources / module then i can send all the information i need with custom query / joins, following the next tutorial:

http://drupal.org/node/1246470

Also on my module i could enable cache etag and then programming on mobile device the http client with etag support.


Replace node add/edit form with a custom form I have this custom form I made in my module which is responsible for adding/editing a specific node type. I was not able to alter the built-in add/edit form to meet my requirements so I decided to make my own forms using the form API.

The forms are doing good but I need drupal to use my custom forms whenever a user tries to add/edit a node from that specific node type instead of the original drupal's standard forms.

It should be a matter of routing/path. I already tried menu hook but it did not work. So how can I make drupal to replace the content add/edit form for that specific node type with the one I want?

Try the pathauto module. You can use the Url Aliases page to add an alias for all of your custom node edit links.


When I am logged-in the page doesn't look the same as when I am logged-off Do I need to include something in the code or in settings.

I have a problem which is that pages don't look the same when I am login or not. Like on photo down. Some help or suggestion?

This is my code. Does I need to add Edit and view bartik?

Whan I change base theme: stable with base theme: bartik bug is fixed.

        {# link is in html.html.twig #}

            {{ page.content }}

{# /.layout-content #}

            {% if page.sidebar_first %}
                    {{ page.sidebar_first }}
            {% endif %}
            {% if page.sidebar_second %}
                    {{ page.sidebar_second }}
            {% endif %}

What you see / notice is pretty standard Drupal ... The link like "Add content" is something you typically only want to be shown for logged in user (and maybe even limited to users with roles such as "content editor" (or whatever you'd call it). Also, the small icons in the upper left (above "logo" and "home") are typically also things you only should be able to use if you are logged in.

Should you want to change any of such things (eg: anonymous users should also be able to "add content"), then it's just a matter of finding out which permission it is that actually governs the specific function (such as "add content"), and then indicate in your "permissions" page within admin that is related to it that you want "role" anonymous to have the very same permission.


Should I always save ContentEntityType after updating a value? I have bunch of ContentEntityTypes made programatically.
What weirds me out is ::save() method of ContentEntityType.

In the documentation about ::save() method is information that reads:

  When saving existing entities, the entity is assumed to be complete, partial updates of entities are not supported

For example, if I update some value with

<?php $contentEntityType->set('field', $value); ?>

Is it partial update? Do I need to do <?php $contentEntityType->save(); ?>?

I think what it means is, that you shouldn't save changes that you don't want to keep.

Since you want to keep the change you are making, you have to save the entity.

The changes to make on they entity are only saved to the database when you call $entity->save().


When should I use the private file system instead of public file system? I try to build a social network on Drupal 8 currently.

And now I have to decide, which files (e.g. user pictures, uploaded user files) should be handled as private files and which as public files.

As far as I know, the public file dir listing is deactivated by Drupal generated .htaccess and it returns a 403 server error. The file is only accessible if you know the exact URL.

The private file system sometimes is buggy (e.g. default user pictures) and doesn't it bloat the database with aliases?
If I want to grab e.g. a picture from the site which is saved in private file system, but shown as content of a view or a node field, I can simply right click on it, and despite private file structure I can save it locally.
So, back to question, when does it make sense to use private file system?

You should use private file system for files to take under control of your drupal installation.

If you have some content with files and pictures you want to be visible only for certain users or groups, then you should save it in private file system. Perhaps paid content or sensitive content.

Content and images which is public to all do not need to be in private file system. For that it is better to use public file system to save server resources.

All files in public space are usable for everyone who knows the url.
Files in private space are not. You can get them only if drupal serves it to you.


How to use condition with multiple term I try to get all the node that belong to 2 taxonomies terms (term 1 AND term 2).

I try with this :

    $select = db_select('node', 'n')
      ->fields('n', array('nid','title'))
      ->condition('n.status', 1);
    $select->fields('n', array('nid'));
    $select->fields('n', array('title'));
    $select->orderBy('n.title', 'ASC');
    $select->join('field_data_field_sous_theme', 'ss', 'ss.entity_id = n.nid');
    $select->condition(db_and()->condition('ss.field_sous_theme_tid', 517)->condition('ss.field_sous_theme_tid', 514));
    $results = $select->execute()->fetchCol();

or this :

$select = db_select('node', 'n')
  ->fields('n', array('nid','title'))
  ->condition('n.status', 1);
$select->fields('n', array('nid'));
$select->fields('n', array('title'));
$select->orderBy('n.title', 'ASC');
$select->join('field_data_field_sous_theme', 'ss', 'ss.entity_id = n.nid');
$select->condition(db_and()->condition('ss.field_sous_theme_tid', 517)->condition('ss.field_sous_theme_tid', 514));
$results = $select->execute()->fetchCol();

But there is no result.

And when i try this :

$select = db_select('node', 'n')
  ->fields('n', array('nid','title'))
  ->condition('n.status', 1);
$select->fields('n', array('nid'));
$select->fields('n', array('title'));
$select->orderBy('n.title', 'ASC');
$select->join('field_data_field_sous_theme', 'ss', 'ss.entity_id = n.nid');
$select->condition('ss.field_sous_theme_tid', array(517,514), 'IN');
$results = $select->execute()->fetchCol();

I've all the nodes that belong to the term 1 OR the term 2.

I've you got an idea to solve my problem ?

Ps: sorry for my bad english, i'm french :-)

What about getting the arrays of nids for each of the tids you want to search with taxonomy_select_nodes($tid) and then intersect the lists with array_intersect. There should be a more Drupalistic way however...


How to get an image URL from a field in a twig template I have a node that contains various fields. I am able to get the values of text fields but not an image field. Below is the relevant output of the node variable being dumped in the twig template:

 'field_main_image' =>
    object(Drupal\field\Entity\FieldConfig)[1312]
      protected 'deleted' => boolean false
      protected 'fieldStorage' => null
      protected 'id' => string 'node.homepage.field_main_image' (length=30)
      protected 'field_name' => string 'field_main_image' (length=16)
      protected 'field_type' => string 'image' (length=5)
      protected 'entity_type' => string 'node' (length=4)
      protected 'bundle' => string 'homepage' (length=8)
      protected 'label' => string 'Main image' (length=10)
      protected 'description' => string '' (length=0)
      protected 'settings' =>
        array (size=12)
          ...
      protected 'required' => boolean false
      protected 'translatable' => boolean false
      protected 'default_value' =>
        array (size=0)
          ...
      protected 'default_value_callback' => string '' (length=0)
      protected 'itemDefinition' => null
      protected 'constraints' =>
        array (size=0)
          ...
      protected 'originalId' => string 'node.homepage.field_main_image'     (length=30)
      protected 'status' => boolean true
      protected 'uuid' => string 'f40a7a65-18a5-4ced-85b0-ab1cdc41b2f5' (length=36)
      private 'isSyncing' (Drupal\Core\Config\Entity\ConfigEntityBase) => boolean false
      private 'isUninstalling' (Drupal\Core\Config\Entity\ConfigEntityBase) => boolean false
      protected 'langcode' => string 'en' (length=2)
      protected 'third_party_settings' =>
        array (size=0)
          ...
      protected '_core' =>
        array (size=0)
          ...
      protected 'trustedData' => boolean false
      protected 'entityTypeId' => string 'field_config' (length=12)
      protected 'enforceIsNew' => null
      protected 'typedData' => null
      protected 'cacheContexts' =>
        array (size=0)
          ...
      protected 'cacheTags' =>
        array (size=0)
          ...
      protected 'cacheMaxAge' => int -1
      protected '_serviceIds' =>
        array (size=0)
          ...
      protected 'dependencies' =>
        array (size=2)
          ...

I have seen similar questions on SE, like this one Getting the image URL from a field_image on a node, but none of the answers have worked for me.

Thanks in advance for any responses.

An image field stores the file id in target_id. You can access the file id with:

{{ node.field_main_image.target_id }}

There is a second property in the image field. It is for the referenced entity, in this case the file object. This is not visible in the debug output, because it is computed:

{{ node.field_main_image.entity }}

In the file object you find the field uri

{{ node.field_main_image.entity.uri.value }}

which you can use the get the url of the original image

{{ file_url(node.field_main_image.entity.uri.value) }}

or the url of an image style

{{ node.field_main_image.entity.uri.value | image_style('thumbnail') }}

The filter for the image style is part of this module which you have to install:

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


Cache API troubleshooting I'm trying to cache an object returned after a 3rd party API call via HTTP. The API charges based on calls, so I'm trying to cache the information returned for some period of time.

However I don't seem to be able to get cache_set() to ever store anything. I've enabled "Cache pages for anonymous users" and "Cache blocks" in the performance configuration, as I read somewhere that the cache API may depend on those being set.

I'm using code inside a function called in hook_block_view():

  $cache_key = 'custom_module'.$index;

  $conditions = cache_get($cache_key);

  if (!$conditions) {
     $conditions = API_CALL($index);
     cache_set($cache_key, $conditions, 'cache',  REQUEST_TIME  + (60 * 10)); //stores in cache table and expires after 10 minutes
  }

However this still results in an API call per page load with testing from a logged out browser.
I added some minimal test code:

  cache_set('testing','foo','cache',CACHE_PERMANENT);
  var_dump(cache_get('testing'));

And the output is "bool(false)".

Looking in the database shows the 'cache' table is empty.

I'm about to start digging through the function calls being cache_set() to see what is happening, and intend to report back what I find. However if this is a common problem perhaps someone already has an answer?

I'm an idiot, and I had configured up the DrupalFakeCache earlier in development to prevent caching. Clearly this results in no caching.


How to link to a users profile in a view I created a view which displays users on my site. Using "Rewrite results" I displayed the first name and Surname in one column. I then checked "Output this field as a link".

My challenge is what path will I enter into the "Link Path" field to ensure that the names in the column link to the user profiles.

By default, user profiles are at user/UID, where UID is the numeric user ID.  (This is true unless you are using a module like Pathauto to customize the profile URLs.)

So, one way to do this is to:

Add the numeric user ID field to your view.  Make sure to check exclude from display so it won't actually be shown in the view.
Reorder the fields in the view so that the user ID field comes before the field for which you want to rewrite results.
The value of the user ID field will now be available as a token in "Rewrite results."  So, you can use the token to create a link to the user profile like this: user/[uid] (the actual token may be slightly different).


How to create a scheduled mailing list using Rules? I am looking for a way to send out an email to a list of users once a week in Drupal. My obvious choice was Rules Scheduler, but that has not been ported.

Is there a preferred way to do this in Drupal 8?

This can be accomplished by using Views, Ultimate Cron, and a custom module:

1) Create a view with the list of emails that you want to send.

2) Create a custom module to loop through the view results and send the emails.

3) Use Ultimate Cron to schedule it to run once a week.


CSS styles not working while included in .info.yml file For some reason my theme can't find css/style.css in Drupal 8.

This is the .info.yml:

name: Adminimal
type: theme
description: Drupal Administration Simplified.
# version: VERSION
# core: 8.x
base theme: seven

# Include CSS.
 stylesheets:
  all:
   - css/style.css

# Information added by Drupal.org packaging script on 2014-10-23
version: '8.x-1.x-dev'
core: '8.x'
project: 'adminimal_theme'
datestamp: 1414059738

This is how the folders look like:

Theme/adminimal.info.yml
Theme/css/style.css

The css in the style.css file:

html{
    background-color: blue !important;
}

It doesn't even show up in the styles section in my Google Chrome console so I think it doesn't find the file but why?

And about jQuery in Drupal, I can't manage to get this working: https://www.drupal.org/node/1541860 To work with: //ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js How should I do this?

Working for me creating drupal8 theme using bartik theme as base theme. Successfully call the css file present in my custom theme. Hopes this will helps you.

name: Smart
type: theme
description: 'Smart business templates'
core: '8.x'
package: Custom
base theme: bartik
project: 'drupal'
stylesheets-remove:
 - colors.css
stylesheets-override:
 - css/colors.css
regions:
 header: Header
 primary_menu: 'Primary menu'
 help: Help
 featured: Featured
 content: Content
 sidebar_first: 'First sidebar'
 sidebar_second: 'Second sidebar'
 triptych_first: 'Triptych first'
 triptych_middle: 'Triptych middle'
 triptych_last: 'Triptych last'
 footer_firstcolumn: 'Footer first column'
 footer_secondcolumn: 'Footer second column'
 footer_thirdcolumn: 'Footer third column'
 footer_fourthcolumn: 'Footer fourth column'
 footer: Footer

settings:
 shortcut_module_link: false

Also take reference from https://www.drupal.org/node/1876600


Save as unpulished role I want to give a role the possibility to create new articles and save them as unpublished. Only the administrators can save articles as unpublished, and I want to give this possibility to another role. How can I do that?

I only have Save and publish for the other roles.

Looking around, it would appear that users with the Administer Content permissions can do what you want to accomplish. However, this permission has the following warning: Give to trusted roles only; this permission has security implications. Promote, change ownership, edit revisions, and perform other tasks across all content types. If this is a limited permission that you want to give and to trusted users only (as suggested by the warning provided by Drupal), you should be fine.

However, if you want many (possibly untrusted) users to be able to do this, the best suggestion I have at the moment is to add a field to the node itself asking the user if they want it to be published or not and to write a hook  that checks the value of that field and publishes it based on that information. There are many variations of this - you can make the field appear only for certain roles, etc.

Edit: Another option you have, instead of writing a hook, is to use the Workflow module. You can set various access permissions from within the module itself to replicate published/unpublished behavior (i.e. make it so that only the author can see nodes published under a certain workflow state). This is probably a better option in the long run since these can be saved in configuration. I'm sure there are other benefits as well.


$form_state=>setErrorByName/setError on fieldset/container/etc I have written a custom validation handler for webform that compares two fields.  If the fields are in a container/fieldset/etc., I would like to set the error on the container instead of on the fields (since either of the two fields could be the erroneous field).  For example, the fieldset is trip-dates, the fields are start-date and end-date and I want an error if start-date is after end-date.

I can use setErrorByName/setError to set errors on individual fields, but it doesn't work if I try to set an error on the fieldset.  When called against a fieldset, setErrorByName/setError call sets the error message at the top of the form, but does nothing to highlight/set an error class on the fieldset.

Webform Source:

event_details:
  '#type': fieldset
  '#title': 'Event Details'
  '#attributes':
     name: event-details
  date_container:
    '#type': fieldset
    '#title': 'Travel Dates'
    '#required': true
    '#attributes':
       name: date-container
     departure_date:
       '#type': date
       '#title': 'Departure Date'
       '#required': true
       '#default_value': '+1 day'
       '#format': short
       '#date_date_min': today
       '#datepicker': true
       '#datepicker_button': true
       '#date_date_format': m/d/Y
     return_date:
       '#type': date
       '#title': 'Return Date'
       '#required': true
       '#default_value': '+1 day'
       '#format': short
       '#date_date_min': today
       '#datepicker': true
       '#datepicker_button': true
       '#date_date_format': m/d/Y

Class Code:

  $errorFields=[
     'date_container',  //sets message, fails to highlight
     'date-container',  //sets message, fails to highlight
     'event_details][date_container',   //sets message, fails to highlight
     'event-details][date-container',   //sets message, fails to highlight
     'return-date',     //sets message, fails to highlight, as expected
     'departure-date',  //sets message, fails to highlight, as expected
     'return_date',     //sets message, highlights single field as expected
     'departure_date',  //sets message, highlights single field as expected
  ];
  foreach($errorsField as $errorField){
    if (!($left_val <= $right_val)) {
      $formState->setErrorByName(
       $errorField,
      $this->t('some weird message'));
    }
  }

I have also tried changing the names of the containers to underscores instead of dashes...no luck.  If it would just add an error class to the fieldset, I could style it easily enough, but it doesn't seem to change anything about the fieldset.

I have also tried container, details and section instead of fieldset.

A workaround may be to add a class to the form which you could then use to style the fieldset:

$form['#attributes']['class'][] = 'my-fieldset-error';


Submit is not working for contact form which was embedded by AJAX I'm trying to add contact form with AJAX callback, called from another form. Form is embedding as well, but when I submit it only page is reloading and form doesn't send any data (in my case it's a contact form, and I can't see any created contact message in backoffice after submitting).

function somemodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['somefield']['widget']['#ajax'] = [
    'callback' => 'somemodule_form_conditional_ajax',
    'method' => 'html',
    'wrapper' => 'form-conditional-ajax-wrapper',
    'event' => 'change',
  ];
  $form['#suffix'] = '

'

}

function somemodule_form_conditional_ajax($form, FormStateInterface $form_state) {
  $output = [];
  $values = $form_state->getValues();
  $conditional_form_id = $values['somefield'][0]['value'];

  $contact_message = \Drupal::entityTypeManager()
    ->getStorage('contact_message')
    ->create([
      'contact_form' => $conditional_form_id,
  ]);

  if (!is_null($contact_message) && $contact_message instanceof Drupal\Core\Entity\EntityInterface) {
    $output = \Drupal::service('entity.form_builder')->getForm($contact_message);
  }

  return $output;
}

I just had this issue myself. Try this:

use Drupal\Component\Serialization\Json;
use Drupal\Core\Render\BubbleableMetadata;

function somemodule_form_conditional_ajax($form, FormStateInterface $form_state) {
  $output = [];
  $values = $form_state->getValues();
  $conditional_form_id = $values['somefield'][0]['value'];

  $contact_message = \Drupal::entityTypeManager()
    ->getStorage('contact_message')
    ->create([
      'contact_form' => $conditional_form_id,
  ]);

  if (!is_null($contact_message) && $contact_message instanceof Drupal\Core\Entity\EntityInterface) {
    $form = \Drupal::service('entity.form_builder')->getForm($contact_message);
    $output = render($form);

    $data = BubbleableMetadata::createFromRenderArray($form);
    $attachments = $data->getAttachments();
    $settings = '';
    if(!empty($attachments['drupalSettings'])) {
      $settings .= '<script type="text/javascript">jQuery.extend(drupalSettings, ';
      $settings .= Json::encode($attachments['drupalSettings']);
      $settings .= ');</script>';
    }

    $output .= $settings;
  }

  return $output;
}

The only thing I'm unsure about is if the $output requires an array - what I've given you is a string. So it may not work.


A views & CSS only solution for a previous post & next post buttons in a blog-node? I found the Previous/Next API module that lets you create previous-post & next-post buttons, that you could put on any node.

For example, if you have nodes of the content type "Blog" you could put such two buttons under them in one div.

A core-only way would most likely include 2 view-blocks styled with some css (most probably display: flex; flex-wrap: wrap; etc).

This you can do easily with the Core Book module. As you can see on the any Drupal.org page for example, Drupal.org page.

Using Book module

You can create a Book which is like index and add the nodes in-order you want, and it will show Next and Prev as shown in above page as title of that node.

D8 site scree shot:

Configuration page

Example Page:


Get() on array in settings from custom Form controller I'm making a custom module with a form controller, that has a text_format field.
I'm storing the text_format value in my submitForm function like so.

public function submitForm(array&$form, FormStateInterface $form_state) {
    $this->config('foundation.settings')
         ->set('infoblock_text', $form_state->getValue('infoblock_text'))
        ->save();
}

I'm attempting to retrieve that for the default value of the field like so

    $form['infoblock_text'] = [
        '#type'          => 'text_format',
        '#title'         => t('Infoblock text'),
        '#description'   => t('The body text for the infoblock on the front page'),
        '#format'        => 'full_html',
        '#default_value' => $config->get('infoblock_text'),
    ];

However it's empty. After performing a die(print_r($config->get('infoblock_text'))) I found that infoblock_text is actually an array and 'value' is the key that contains the text I need. This is what the die() statement returns

Array ( [value] =>
Text of infoblock
[format] => full_html ) 1

After seeing that I actually needed to retrieve the value element rather the entire array I attempted the following with no luck.

$config->get('infoblock_text', 'value');
$config->get(['infoblock_text', 'value']);
$config->get('infoblock_text')->value;
$config->get('infoblock_text')->value();
$config->get('infoblock_text')->getValue();
$config->getValue('infoblock_text');
$config->getValue('infoblock_text');
$config->getValue('infoblock_text');

So how would I actually retrieve the value of 'infoblock_text', when $config->get('infoblock_text') returns the entire array?

You can handle the config like an array:

$form['infoblock_text'] = [
    '#type'          => 'text_format',
    '#title'         => t('Infoblock text'),
    '#description'   => t('The body text for the infoblock on the front page'),
    '#format'        => isset($config->get('infoblock_text')['format']) ? $config->get('infoblock_text')['format'] : 'full_html',
    '#default_value' => isset($config->get('infoblock_text')['value']) ? $config->get('infoblock_text')['value'] : '',
];

When accessing the array like this, it's always a good idea to check if the key is set. This avoids warnings in your log.


get timestamp of most recent comment of an article I need the date of the last created/updated comment of an article. Are there any API functions in drupal 8 like node->most_recent_comment ? Or do I have to check every comments date of a node in a loop?

EDIT - Solution:

$node->comment->last_comment_timestamp;

Note that you'll have to change ->comment to the actual field name of the comments on your node.

As @IvanJaros pointed out the comments statistics are stored in a database table. You don't need an API function to get them. The comment module does this for you and places them in the field while loading the node from storage:

function comment_entity_storage_load($entities, $entity_type) {
  ...
  // Load comment information from the database and update the entity's
  // comment statistics properties, which are defined on each CommentItem field.
  $result = \Drupal::service('comment.statistics')->read($entities, $entity_type);
  foreach ($result as $record) {
    // Skip fields that entity does not have.
    if (!$entities[$record->entity_id]->hasField($record->field_name)) {
      continue;
    }
    $comment_statistics = $entities[$record->entity_id]->get($record->field_name);
    $comment_statistics->cid = $record->cid;
    $comment_statistics->last_comment_timestamp = $record->last_comment_timestamp;
    $comment_statistics->last_comment_name = $record->last_comment_name;
    $comment_statistics->last_comment_uid = $record->last_comment_uid;
    $comment_statistics->comment_count = $record->comment_count;
  }
}

So you can access the statistics directly from the node field:

$node->comment->last_comment_timestamp;
$node->comment->last_comment_name;
$node->comment->last_comment_uid;
$node->comment->comment_count;


Get Facebook content from node_load() I want a content type having a field "FB URL" that get the URL of a Facebook Event and that when people load a node of this type, the content of the facebook event is retrieved through FB API. It cannot be retrieved from the database because the content must be up to date with the one on facebook.

So far, I created a module with node_load() to add content while the node is loaded but I don't know what function to call from FBOauth module to do so... Before that, I tried with a simple file_get_contents(); that worked well until the access token from the FB App expired and didn't know how to get a new one dynamically.

I think I'm getting lost so could anyone guide me on how to do that?

Thanks a lot!

Ok, I found!

function fb_event_crawler_node_load($nodes, $types) {
    foreach ($nodes as $node) {
        if ($node->type=="event"){
            $fb_url = $node->field_event_url['und'][0]['value'];
            $url = parse_url($fb_url);
            if (!$url['host'] == 'www.facebook.com'){
                echo t('This is not a Facebook URL');
            }

            $path_exploded = explode("/", $url['path']);
            if (!$path_exploded[1] == 'events'){
                echo t("This is not a Facebook event page!");
            }

            $fb_event_id=$path_exploded[2];

                // dpm($path_exploded);

            $app_id = isset($app_id) ? $app_id : variable_get('fboauth_id', '');
            $app_secret = isset($app_secret) ? $app_secret : variable_get('fboauth_secret', '');
            $app_token_url = "https://graph.facebook.com/oauth/access_token?"
            . "client_id=" . $app_id
            . "&client_secret=" . $app_secret
            . "&grant_type=client_credentials";

            $response = file_get_contents($app_token_url);
            $params = null;
            parse_str($response, $params);
            $access_token=$params['access_token'];

                //echo($params['access_token']);

            $fbquery = fboauth_graph_query($fb_event_id."/", $access_token);

            dpm($fbquery);
        }
    }
}


Access Denied when I try to flush cache or change theme This is a very odd issue. Logged in as admin. All permissions given to admin. But Access Denied page when I try to flush cache or change theme. I can flush the cache with drush. I tried switching theme to garland and back again. I tried creating a new admin user, didn't work. I tried disabling recently enabled boost module, to no avail.

I have no idea why, but I disabled clean-urls and reenabled it and now I can flush cache and switch themes without access denied.

I had installed the Boost module which also involved putting some stuff in the .htaccess and turning on clean urls (although I was using it anyway).

This problem took me about 4 hours to solve and was completely unintuitive.


Serve Anonymous Pages when users are logged in for some pages so essentially I have a Drupal website with great performance for anonymous users and terrible performance for logged in users.

What I am looking for is a way to serve some pages that logged in users access as if they were an anonymous user.

In custom development this would be done using a:

cache-control:public

header for varnish, but obviously when viewing that page anything such as the users profile information and the login status must not be shown so its not cached in varnish.

I was hoping there would be a config change or module that could perform this without having to write a custom module,

any ideas would be greatly appreciated

You may implement ESI block caching.

Have a look at ESI module  and varnish basic tutorial. You would be able then to cache whole pages except the blocks with session data.

Additionally, @Kevin comment points a complementary way: using Redis or Memcache will substantially speed the pages when logged, by caching data and objects in server memory to reduce the number of times the data source must be read.


Fetch column sum from database and print the output using static/dynamic queries in drupal 7, i want to get the sum of a column in the database and display it using a static query and show the display in a block. I am executing the php code at site.com/devel/php from the devel module.

Plese do note that I am not proficient in coding, and i am a script kiddie. I am not a developer, and i have only used the drupal platform as a designer, and have only dealy with the configurations and menus.

the query i want to exectue is very very simple. it is

SELECT SUM(column_name) FROM table_name

i have tried using static query as follows:

$val=db_result(db_query('SELECT SUM(column_name) FROM {table_name}'));
print $val;
then i get --- *"Fatal error: Call to undefined function db_result() "*

i also tried

$query = db_select('table_name');
$query->addExpression('sum(column_name)', 'total');
$result = $query->execute();
print $result;

then i get --- "Recoverable fatal error: Object of class DatabaseStatementBase could not be converted to string in eval()"

I want to print the value of the total sum.
If i remove the print statement, then it works and executes. but i want the value printed.
as in, if i only execute the first three lines

$query = db_select('table_name');
$query->addExpression('sum(column_name)', 'total');
$result = $query->execute();

it runs successfully, but with the print statement it does not.

I am executing the php code at site.com/devel/php. I intend to use this result that gets printed either in a page or in a block.

Is there any noob mistake that i have made, and can you guys guide me to the right resource to get thhis to work.

I have looked at issues that other prople have had and have been copying thaat and modifying it so it used the table i want to use and the column names within it.

Truth be told, I dont know if we cam print variables when we are executing php code in drupal. if i run the query with a print 'Hello', then it prints. So i know that the print statement works, but i am not sure if it prints variable.
If it is not possible to use the SUM in the query, will i have to fetch rows individually using for each, and within the loop add the values to a sum variable to get the total?
Also, in a few of the posts i read that db_quey()/some other function is not there in d7 and was a part of d6. So i am unsure if i am even going in the right direction.

Any help here would mean the world to me.

Regards and Peace from the UAE,

Aamir

The first error is caused from the fact that Drupal 7 doesn't define db_result() anymore; it was used from Drupal 6.

The second error is caused from $query->execute() returning an object of that class, which you cannot convert into a string (which is what you do when you try to print it). You should use code similar to the following code.

$query = db_select('table_name');
$query->addExpression('SUM(column_name)', 'total');
$result = $query->execute()->fetchField();


How is this realised? When we implement, for example, theme_preprocess_page(&$vars) function, we can alter variable that are visible as not array items.

What I mean: $vars['somevalue'] from theme_preprocess_page(&$vars) function is further  available in page.tpl.php as $somevalue. How is it possible? Definitely there is some kind of automatic generation of variables but the implementation is unclear.

Clive's answer is correct. I am just pointing out where exactly that happens.

theme_render_template() is the function called by theme(), and it contains the following code.

  extract($variables, EXTR_SKIP); // Extract the variables to a local namespace
  ob_start(); // Start output buffering
  include DRUPAL_ROOT . '/' . $template_file; // Include the template file
  return ob_get_clean(); // End buffering and return its contents

The code that calls theme_render_template() is the following one.

    // Default render function and extension.
    $render_function = 'theme_render_template';
    $extension = '.tpl.php';

    // The theme engine may use a different extension and a different renderer.
    global $theme_engine;
    if (isset($theme_engine)) {
      if ($info['type'] != 'module') {
        if (function_exists($theme_engine . '_render_template')) {
          $render_function = $theme_engine . '_render_template';
        }
        $extension_function = $theme_engine . '_extension';
        if (function_exists($extension_function)) {
          $extension = $extension_function();
        }
      }
    }

    // In some cases, a template implementation may not have had
    // template_preprocess() run (for example, if the default implementation is
    // a function, but a template overrides that default implementation). In
    // these cases, a template should still be able to expect to have access to
    // the variables provided by template_preprocess(), so we add them here if
    // they don't already exist. We don't want to run template_preprocess()
    // twice (it would be inefficient and mess up zebra striping), so we use the
    // 'directory' variable to determine if it has already run, which while not
    // completely intuitive, is reasonably safe, and allows us to save on the
    // overhead of adding some new variable to track that.
    if (!isset($variables['directory'])) {
      $default_template_variables = array();
      template_preprocess($default_template_variables, $hook);
      $variables += $default_template_variables;
    }

    // Render the output using the template file.
    $template_file = $info['template'] . $extension;
    if (isset($info['path'])) {
      $template_file = $info['path'] . '/' . $template_file;
    }
    $output = $render_function($template_file, $variables);
  }


Get parameter from current url How can I get parameter i.e node id from URL in views link path . Eg. - suppose in taxonomy term's view I am giving field name's custom link path is "document/getParameterFromCurrentURL/{{tid}}". where suppose getParameterFromCurrentURL  is variable or etc so how can i get id from current url in getParameterFromCurrentURL.

You could try adding a "Global: Null" contextual filter to your Views display, configured to "Provide default value" with type "Content ID from URL".

The Null filter type doesn't change the output of your view. But it would make the Node ID available as a replacement pattern.


indexing first letter of items to make an A-Z type glossary, using solr backed and search api I am using the search_api and the solr backend. It is possible to index first letter of content so I can use solr to create an A-Z style filter?

OK, it's a little late. But yes, you can index a glossary. I've build an A-Z-Filter in SOLR based on custom entity-fields like surname here http://www.autorenwelt.de/verzeichnis/menschen My filter based on the following description: https://drupal.org/node/2069005

I need only this functions to build a field in the SOLR index:

/**
 * Apachesolr index name for this module.
 *
 * Dynamically creates name as expected by Solr.
 */
function _MODULENAME_search_index_key($key) {
  $index = array(
    'name' => $key,
    'multiple' => FALSE,
    'index_type' => 'string',
  );
  return apachesolr_index_key($index);
}

/**
 * Implementation of hook_apachesolr_index_document_build()
 *
 * Alters what is sent to Solr in $document.
 */
function MODULENAME_apachesolr_index_document_build($document, $entity, $entity_type, $env_id) {
    $glossary_key = _MODULENAME_search_index_key('custom_glossary');
    // We want to index the first letter of the title for use in our glossary
    $key = strtoupper($entity->title[0]);
    // Build a custom glossary of profile2 entities
    if ('profile_main' == $entity->type) {
        $key = strtoupper($entity->field_profile_surname['und'][0]['safe_value'][0]);
    }

    $indexed = '0 - 9';
    switch ($key) {
        case 'A':
        case 'B':
        case 'C':
        case 'D':
        case 'E':
            $indexed = 'A - E';
            break;
        case 'F':
        case 'G':
        case 'H':
        case 'I':
        case 'J':
            $indexed = 'F - J';
            break;
        case 'K':
        case 'L':
        case 'M':
        case 'N':
        case 'O':
            $indexed = 'K - O';
            break;
        case 'P':
        case 'Q':
        case 'R':
        case 'S':
        case 'T':
            $indexed = 'P - T';
            break;
        case 'U':
        case 'V':
        case 'W':
        case 'X':
        case 'Y':
        case 'Z':
            $indexed = 'U - Z';
            break;
    }
    $document->{$glossary_key} = $indexed;
}

And I use hook_facetapi_facet_info_alter to register this facet:

/**
 * Implementation of hook_facetapi_facet_info_alter().
 **/
function MODULENAME_facetapi_facet_info(array $searcher_info) {
    $facets = array();
    // Facets are usually associated with the type of content stored in the index.
    if (isset($searcher_info['types']['node'])) {
        $facets['ss_custom_glossary'] = array(
            'default widget' => 'links',
            'name' => 'ss_custom_glossary',
            'label' => t('A - Z Glossar'),
            'dependency plugins' => array('role'),
            'description' => t('Glossar basierend auf dem ersten Buchstaben des Node-Titles.'),
            'field' => 'ss_custom_glossary',
            'field_alias' => 'ss_custom_glossary',
            'weight' => -50
        );
    }

    return $facets;
}

Ciao
Ralf


Contact form in content type I've made a content type User. Each user has a field email. I will not display the email but I would like a way for visitors to contact each user. So I am looking for a way to have a simple contact form inside a content type.

Any ideas?

If you use the module Email Field to create your email field you can set the field to be displayed as a contact form. You will find the setting to turn the field into a contact form under Display settings for the field.


EntityFieldQuery get total of paged results I have added a pager to my query with $query->pager(6); but I also want to display a total number of results. For example, if there are 8 results I want to display Search results (8) with 6 per page but I don't know how to get the total number of results, the query only ever returns an array of up to 6 elements so I can't add them all up.

As usual, I find an answer soon after asking :P

If anyone's wondering, there is a global $pager_total_items https://api.drupal.org/api/drupal/developer!globals.php/global/pager_total_items/7