Exposed view filter is not rendered properly I have a view with a filter "Has taxonomy term", this filter is an exposed filter and is set to be a "Dropdown" and "Show Hierarchy"

The vocabulary has parents and children term (hierarchical).

The filter works fine but the html tags of the select dropdown are incorrect. The parent terms should be wrapped in  instead of  (see image 2)

Can I override this?

I trying to do it with hook_form_alter() but I see that the construction of the select itself is done by drupal_map_assoc() function. Then I see no way to do it? Can I put the value for '#options' in other way?

<?php
  $form['undergraduate']['school_country'] = array(
    '#type' => 'select',
    '#options' => drupal_map_assoc(array(t('UK'), t('Other'))),
    '#title' => t('In what country is your college or university located?'),
  );
?>

You could check if it is the top level (maybe by checking if it doesn't have a - at the start), and then add the attribute disabled (disabled="disabled")

You could also use this module: drupal.org/project/term_reference_tree. It has on option to only allow selection of the lowest term in the hierarchy. I used it on a site recently and it worked well.


Using Event Subscriber change the product custom field value after first checkout of that product Using 'Event Subscriber', I'm able to get $order and $items from the order after completing the checkout.

How can I get the product id from the $itemsand modify the product custom field value?

Scenario: I want to change the status of the product after completing the first checkout of that product.

Do you really want to change the status of the product or the product variation?

$items is an array of OrderItems. If you loop over the items, you can get the referenced purchased entity of the single item with $purchasedEntity = $item->getPurchasedEntity();. If you only want the first item you can access it like so $purchasedEntity = $items[0]->getPurchasedEntity();.
In case the PurchasedEntity is a ProductVariation you can get the product with $product = $purchasedEntity->getProduct();

In case you want to change the status of the product:

$product->setUnpublished();

Or for the variation:

$variation->setActive(false);

If you want to set any custom field on the product variation:

$variation->set('your_custom_field_name', $value);

docs
This assumes you use the default commerce2 product architecture. It is absolutly possible that you get other purchasable entities than ProductVariations back from the OrderItem.


View to show node titles only when a new comment has been posted? I am trying to create a view that will show the titles of all nodes only when these nodes have new comments. I need a filter like "Content has new comments" but there isn't any.
Can somebody help?

You can add a relation in views "comments of the node" and add filter criteria by comment post date. As I know there is no status "new" in comments that's why you can limit them by date.

Or you can add custom field with status but you will need a logic how to add and remove that status.


How To Create Combined Search Filters In Views? I am currently working on a view that allows me to search "title" of a content type along with 3 other exposed filters. But now I want users to not only be able to search "title" but also "category" field of the same content type, except "title" and "Category" fields need to be one filter.

I tried using contextual filters but I'm afraid I don't quite understand the best method. I'm currently using global:combine fields filter but instead my views results (which worked fine previously) no longer works. I'm trying to avoid complicated coding. Any suggestion?

The newest version of Views integrates this feature without the need for Views filter populate.  It's a filter called Combine fields filter.

To make use of it you first need to add all of the fields you want to filter on.  You may check Exclude from display if you want to search for it, but don't want to display it.

Once all of the fields are there, add a Combine fields filter, and choose to Expose it.  Choose Single field for the Filter type to Expose

This is a different approach than Views populate filter, but as this is integrated into Views I find it much more intuitive.


Turning View into flashcard I am working on a requirement to display a 2 column (question and answer ) view into flashcard .  question should appear on front and on flipping the answer should appear . I am not sure whether such kind of thing can be done with view , If there is any custom module that needs to be written , what should be the approach taken for such requirement.

Thanks for any pointer on this

Pks

Views can render both question and answer. Beyond that you need jQuery and CSS for the hide/show/flip effects.


User registration form throws validation errors on already unset profiles´ fields Using Drupal 7 with Profile2: I have a number of profile types, with different fields, some of which I want a registrant to already fill up during the registration process. I´ve checked "Show during user account registration" for all. In my custom module, I´m first taking the registrant´s choice of profile, then unsetting (unset(); also tried hide() and ...[#access]=FALSE) all the other profiles and then rendering the registration form. This 'shows up' correctly because I only get to see the chosen profile fieldset. However, when I submit the form I get validation errors (required fields) on the unset profiles´ fields. So apparently only unsetting/hiding/etc. won´t do the trick. What am I missing?

Appreciate any help!

Best,
Mir

The Profile2 Registration Path module  solves the issue!

  This module enables administrators to set unique registration paths per Profile2 profile type.


Access database tables with Views I want to show some fields of a database table with Views. There is no node type, fields, or something like that for this database table. How can I do that?

If you are using Drupal 6 and Views 2, the easiest way to accomplish this is by utilizing the Data module.

If you can't use the Data module and have to do this programmatically for one reason or another, the following steps will get you on your way to achieving your goal of being able to manage your custom tables through the Views GUI.  The first step is implementing hook_views_api() in a custom module.  hook_views_api() tells which version of Views you are working with and will be similar to the code below:

function mymodule_views_api() {
  return array('api' => 2.0);
}

Change the version number depending on which version of Views you are using.  Then you will define your table structures in hook_views_data().  It is a fairly lengthy discussion, so I will point you to the resource at http://views-help.doc.logrus.com/help/views/api-tables on how to do this.

In order to add fields, sorts, etc. using your table's fields, you will have to add "handlers" to the various field definitions in hook_views_data().  The documentation at http://views-help.doc.logrus.com/help/views/api-handlers is a great overview of how handlers work, and the article by Treehouse Agency is a good working example of creating handlers and adding them to your fields.

Views programming is very tough at first, and it is always helpful to look at the built in examples that come with Views.  For example, the modules/node.views.inc file will have the hook_views_data() implementation for the core Node module, and the module/node directory will contain all of the handlers it utilizes.


Change the name of a tab I have a group made from Organic groups, and it has these two tabs.

I want to change the name of "View", but can't figure out where to do that.

Even better would be if I could delete that little menu. Ideas?

The Tab Tamer module should do everything you need.

  Tab Tamer is an administration utility that provides easy re-ordering,
  hiding, and deactivation of tabs and subtabs. You can also rename tab
  labels.


Menu drop down in Drupal 7 I just started to learn and to develop a Drupal 7 site; therefore, I don't know Drupal very well.
How can I create the menu used in these two sites, http://www.honda.com.my/ and
http://www.toyota.com.my/index.html?

There is three sides to the question.

One is to make dropdown multi-columns menu, also called mega menu. The Superfish module should provides that. But I'm sure there are others.

The second is to have pictures associated with the menu entries. One solution is to use pictures associated to the pages linked from the menu. If all the pages are nodes, this can be done by using a file (or media) field. Another solution is to use picture associated to taxonomy terms. And to use these terms as categories for the pages (through classic term-node association or any other solution). To get the picture for a menu entry, simply get the image for the term associated with its page.

Instead of looking for the pictures of menu entries when building the menu, which could be query intensive, I would rather use a custom menu callback to deliver the picture of a menu entry. The menu callback takes a single argument, the menu path, and ends by issuing a redirect (ie. drupal_goto()) to the picture to use. Off course, use an image style to resize the pictures to fit in the menu.

The third question is to automatically generate a menu from the products list (nodes). I'm not sure this is actually wanted. The menu in Drupal are dynamic and can be edited at any time by users with the right permissions. On creation a node can be placed in a menu. If automatic menu are needed, custom code may be needed. The Auto Menu provides this feature even if it has not been ported to Drupal 7. The Taxonomy Menu produces menu from taxonomy hierarchies, so if product are terms this can work too. If coding is an issue, the Rules menu can provide the necessary tools to implement any custom menu entry creation logic. The solution really depends on the actual site structure.

Off course, you can also bypass the menu system and produces your menu using Views or custom code, but it means you will end up with a full-custom solution which won't be able to re-use any existing module, or even code snippets, targeted at normal Drupal menu.


Disable default view when offering module is disabled I have the User IP Log that displays the logged data using a default view defined in the module; when the module is disabled, the view page becomes broken, throwing PHP warnings and notices.

I would like to disable the default view when the module defining it is disabled, to fix the PHP warnings I get. Is it the right way of handling this? If it is so, what API could be used for disabling the default view defined by a module?

hook_disable() is what you are looking for:

  Perform necessary actions before module is disabled.

  The hook is called every time the module is disabled

Remember to do inverse actions with hook_enable(), which is used when a modules is enabled, install hooks don't fire when a module is re enabled.

Also if you need to track enable/disabling of another module you can use hook_modules_disabled() and hook_modules_enabled()

(it looks like you found it, but adding an answer for others is always good).


how to send a exposed filter when use Service views I create a exposed filter of field field_nick_name.

and I visit this link

http://drupal/daxuebao/api/views/user_search_by_nick?filters[field_nick_name]=a

and this link

http://drupal/daxuebao/api/views/user_search_by_nick?field_nick_name=a

this above 2 can not work, is there someone can tell me how to use Service View with exposed filter?

I try to find out the views setting that store in database with following code:

$db = db_select('views_display', 'v')
    ->condition('v.vid', '30')
    ->fields('v', array('display_options'));

  $res = $db->execute()->fetchAssoc();
  $a = unserialize($res['display_options']);

the $a contain a filter array. The field_nick_name actually is field_nick_name_value, and uid is uid_raw


Shorten feed_item links on the fly I am using feeds module. The site structure creates a new feed_item for each item in the parsed rss

I want that upon the arrival of each feed_item, the link be shortened. I read about few related modules, but all require manual intervention.

I am ready to insert some api function into the feeds module, but where to insert it exactly, that is out of my knowledge. Please help.

Currently using Shurly

Done using 'Shurly' and 'feeds_tamper_php' module.

After enabling both the modules, add

  Execute PHP Code

plugin to

  Feed Importer's field_url

.

Execute the following code:

$shortUrl = shurly_shorten($field);
return $shortUrl['shortUrl'];


Embed a view into a Webform for submission I have the following set up on a D8 install using the Flag, Views and Webform modules:

A content type named Product with a Flag field that can be set to "Add product to quote" or "Remove product from quote".
A view named "My Quote" that displays all products Flagged with "Add product to quote".
A Webform named "Get Quote" set up to capture the client's name, email, address, etc.
I now need to add the the view for "My Quote" to the Webform in some way.

I see in D7 there was a module called Webform View that provided similar functionality to what I'm looking for. If I understand the Webform Computed Elements correctly there should be a way to do this using Twig or Tokens, but I have no idea how to get the View data using either method.

I would be very grateful if someone could point me in the right direction, or help me understand the Twig syntax for referencing a View so I can use it in my Weform.

To embed a View in a Webform, you can use the View element.

Below is the YAML for how you would embed the Frontpage view into a Webform.

frontpage:
  '#type': view
  '#name': frontpage

@see \Drupal\views\Element\View


How do i fix Invalid arguments passed in DefaultMailSystem->format() (line 23 system.mail.inc I'm getting this error while developing a module:

  Warning: Invalid arguments passed in DefaultMailSystem->format() (line 23 /modules/system/system.mail.inc)

here's my code:

function mymod_mail($key, &$message, $params) {
    switch ($key) {
        case 'job_mail':
            $message['subject'] = 'mysubject';
            $message['body'][] = 'test';
            break;
    }
}

I googled it normaly this happens when $message['body'] is defined like this:
$message['body'] = 'test'; instead of $message['body'][] = 'test';

And then I've got the following code to call the above hook_mail()

function mymod_send_mail($vacancies, $user) {
    // specify module name and template key for hook_mail
    $module = 'mymod';
    $key = 'job_mail';

    // Specify to and from addressses.
    $to = 'my@email.com'; // user email TODO get user email based on $uid
    $language = language_default();
    $params = array(
        'username' => $user->name,
        'sitename' => variable_get('site_name', 'Drupal'),
    $from = variable_get('site_mail', 'default@email.com');
    $send = TRUE; // defaul = TRUE can be set to FALSE to not actually send the mail and only generate it.
    drupal_mail($module, $key, $to, $language, $params, $from, $send );
}

I've put a debug() in system.mail.inc above the implode function but that showed my message  $message['body'] was not an array ( $message['body'][] ) anymore.

Also when I put a debug on the result of the drupal_mail function I see that my subject is set but the body is empty.

I fixed it by using:

$language = user_preferred_language($user);


Integrate SQL Query into views I manage a Wordpress site for a football team, and I created therefore a SQL Query to calculate the standings.
Now I want to switch over to Drupal and for the calculation of the standings I thought to use the views module. Is it possible to integrate my SQL Query into Views?

Query :

$sql="SELECT
  teamname AS Team, Sum(Played) AS Played, Sum(Won) AS Won, Sum(Draw) AS Draw, Sum(Lost) AS Lost,
  SUM(Gfor) as Gfor, SUM(Gagainst) AS Gagainst, SUM(Gdiff) AS Gdiff, SUM(Pts) AS Pts

FROM(
  SELECT
    teamhome Team,
    1 Played,
    IF(homescore > awayscore,1,0) Won,
    IF(homescore = awayscore,1,0) Draw,
    IF(homescore < awayscore,1,0) Lost,
    homescore Gfor,
    awayscore Gagainst,
    homescore-awayscore Gdiff,
    CASE WHEN homescore > awayscore THEN 3 WHEN homescore = awayscore THEN 1 ELSE 0 END Pts
  FROM matches
WHERE homescore IS NOT NULL AND awayscore IS NOT NULL
AND division='1' and season = '2015-2016' AND matchtype='C'
  UNION ALL
  SELECT
    teamaway,
    1,
    IF(homescore < awayscore,1,0),
    IF(homescore = awayscore,1,0),
    IF(homescore > awayscore,1,0),
    awayscore,
    homescore,
    awayscore-homescore Gdiff,
    CASE WHEN homescore < awayscore THEN 3 WHEN homescore = awayscore THEN 1 ELSE 0 END
  FROM matches
  WHERE homescore IS NOT NULL AND awayscore IS NOT NULL
  AND division='1' and season = '2015-2016' AND matchtype='C'
) as tot

JOIN teams t ON tot.Team=t.teamid
GROUP BY Team

ORDER BY SUM(Pts) DESC, Sum(Won) DESC, SUM(Gdiff) DESC";

You will need to create a (1) custom table in the drupal database, (2) to adopt that table using the data module and (3) to create a view with that table as base the table of your view.

1) Create your custom table by using pure SQL (the fields order matters)

DROP TABLE IF EXISTS my_custom_table;
CREATE TABLE `my_custom_table` (
`node_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'The primary identifier for a node.',
`int_field` int(10) unsigned DEFAULT NULL,
`text_field_1` varchar(255) NOT NULL DEFAULT,
`text_field_2` varchar(255) DEFAULT NULL,
`long_text_field` longtext,
`term_tid_field` int(10) unsigned NOT NULL DEFAULT '0',
`term_field` varchar(255) NOT NULL DEFAULT,
 PRIMARY KEY (`node_id`),
 KEY `text_field_1` (`text_field_1`),
 KEY `text_field_2` (`text_field_2`),
 KEY `long_text_field` (`long_text_field`),
 KEY `term_tid_field` (`term_tid_field`),
 KEY `term_field` (`term_field`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

You can peek at the drupal database for more field types

1.1) Continue by adding your data into that table by using SQL again:

INSERT IGNORE INTO my_custom_table(
SELECT
 int_field,
 text_field_1,
 text_field_2,
 long_text_field,
 term_tid_field,
 term_field
FROM
// Your query
);

2) Go to the data module's admin page admin/structure/data and adopt your custom table. The module is smart enough and your table will be displayed in the list, simple adopt it.

3) Create a new view admin/structure/views/add and if everything went well your table will be in the Show list with all other available tables. You should be able to see all the fields (1:1) from your table as fields in the view.

A drawback (if it really is) by following that method is that no other fields are available, like node fields, taxonomy, users etc, just yours. The same goes for contextual filters handlers, filters criteria handlers and relationships. That's all.


Drupal is slow only in IE We have had a lot of feedback about our Drupal site running very slow on a different network. Most of the users on this network use IE (IE6 and IE8), which is causing a huge slowdown compared with Firefox.

However, even in Firefox it is still slower than what we would expect. We have put this down to a local DNS issue (the DNS request is timing out after 2 seconds, then works off another DNS sever. I am assuming this is adding a 2 second latency to all page loads?)

What other problem could be causing a dramatic slow down for Drupal, only in IE?

Site in FF from YSlow:

Empty Cache = Total Weight - 586.2K
Primed Cache = Total Weight - 267.3K

Javascript is probably your villain.

Especially on IE6 and IE7 and still in IE8, Javascript is MUCH slower than the rest of the world.

Despite not being the most brilliant piece of js ever, drupal.js is harmless.  The real harm probably lies a lot of plugins or maybe one or two poorly-coded scripts that perform some kind of expensive DOM lookup or other task that is negligeable in Firefox et al but really slows down IE.


Message "No pending update" after update.php (update module) Today I updated the security update for the "views".

I always follow the steps for updating a module or core:

1) put site in maintenance mode
2) FTP the files
3) go to link site/update.php

But sometimes i get the message "no pending updates"... after step 3...

When I googled this I read something about some updates don't require a update of the Database.

So, ... If I see this message can i leave step 3 when i update my next site?
I think so, but i prefer a conformation of a Drupal expert ;-)

Thanks for reading and all the info you will leave behind here :-)
Kristof

The "no pending updates" message means that there are no DB updates to be run. At that point, you are safe to go on with your normal process, which may include a few more steps:

If you use features, check to see if they have been overridden.
Clear caches.
Take your site out of maintenance mode.


Adding fields to user registration form I want to collect user personal information like first name, last name, and home address in in user registration, and I also want user to make the profile pubic or private.

I am using Drupal 7.

Go to Config > People > Account Settings > Manage Fields

Then, you can add fields to user profiles just as you would add fields to any content type. When you add fields here, there is a checkbox to "Display on user registration form" if you want the field to be part of the user's registration process.

Hope this helps someone.


Site aliases: Use a different PHP path on remote The Problem:

For reasons I'm not gonna get into, the path to my php executable is NOT /usr/bin/php but is instead something else (let's say it's /local/path/to/php).

My staging and production servers do use /usr/bin/php, however; Moreover, the non-standard php path doesn't exist on those servers.

The problem is that whenever I run a Drush command for a remote site, I get an error:

$ drush @mysite.remote status
bash: /local/path/to/php: No such file or directory

Since /local/path/to/php definitely exists on my local machine (or else my local sites wouldn't work and drush would fail) I can only assume that error is coming from the remote server.

I know I can pass --php=/usr/bin/php to Drush, but there are some less Drupal-savvy devs on my team, so I want to get it configured for them so they don't have to think about it.

I also know about the $DRUSH_PHP environment variable, but setting that to /usr/bin/php breaks drush on my dev machine entirely, so that's not an option either.  It just straight-up breaks Drush.

The Question:

Is there a way to configure my remote aliases to use a specific path to PHP that is different to my local machine's PHP path?  (And why is a remote server trying to use a local path to PHP in the first place?)

If not, what workarounds are there? (I'm hoping I won't have to create a symlink at /non/standard/php to /usr/bin/php on my servers, because that feels fragile and hack-ish, but if there are no alternatives, it'll have to do.)

Drush 7.4.0

From example.aliases.drushrc.php:

  Although most aliases will contain only a few options, a number
  of settings that are commonly used appear below:

...

  'php': path to custom php interpreter. Windows support limited to Cygwin.

So try somtehing like:

$aliases['example'] = array(
  'uri' => 'example.com',
  'root' => '/var/www/example.com',
  'remote-host' => 'www.example.com',
  'remote-user' => 'user',
  'php' => '/path/to/php/on/the/server'
);

You could try that. If this doesn't work I would suggest to update your drush version (locally and on the server) and try again, before doing any strange symlinking on the server.


how to give path to custom page tpl for content type I want to give the path for custom page tpl which I have created for specific content type. 'test_insights' is my content type name.I have created custom page tpl in the folder

project_name/themes/themename/templates/page--test_insights.tpl.php

I want to know how to give the path for created tpl now I tried http://localhost/project_name/test_insights

I caught the error as

  The requested page "/project_name/test_insights" could not be found

.

If I understood your question correctly, you are looking for hook_menu. You can find the API here.

An Example:

function mymodule_menu() {
    $items['test_insights'] = array(
      'page callback' => 'mymodule_test_insights',
      'page arguments' => array(),
    );
    return $items;
  }

//The callback function
function mymodule_test_insights(){
    //Do the necessary actions
    return $something;
}

Note: After implementing the hook_menu you have to clear the drupal cache to access the URL.

To add content type specific page tpl you have to use theme_hook_suggestions by implementing template_preprocess_page. You can add the below code in the template.php file of your theme

Example:

function themeName_preprocess_page(&$vars, $hook) { //themeName change to your theme name
  if (isset($vars['node'])) {
  // If the node type is "test_insights" the template suggestion will be "page--test--insights.tpl.php".
   $vars['theme_hook_suggestions'][] = 'page__'. str_replace('_', '--', $vars['node']->type);
  }
}


How to delete true orphaned taxonomy terms I have a taxonomy vocabulary that contains a large number (5000+) of orphaned taxonomy terms. By orphaned I mean that they refer to parent terms that no longer exist, or refer to parents who are themselves orphans (grand-orphans ?). I am not talking about unused terms.

I do not see these terms in the Drupal interface as they are no longer connected to the main hierarchy. I can however still see them in the database, and I can open them directly using the tid in the Drupal interface.

I can't bulk delete them using any module because modules get the entire tree of the vocab to delete - and they are no longer part of the tree. I think I will have to delete them manually in the database.
I can delete the terms from the taxonomy_term_data and taxonomy_term_hierarchy tables:

DELETE FROM taxonomy_term_hierarchy WHERE parent NOT IN (SELECT tid FROM taxonomy_term_hierarchy) // or something like it

Are there any other tables I need to think of though, in order to not end up with a database that's messed up worse than it already is?

I wouldn't advise doing that - taxonomy terms are entities and need to be cleaned up with taxonomy_term_delete(). Otherwise you'll potentially leave a lot of orphaned data in field tables/contrib module tables/etc.

However, if you know your DELETE query will get you the correct terms, just convert it to a SELECT and you can do things the proper way:

$tids = db_query('SELECT tid FROM taxonomy_term_hierarchy WHERE parent NOT IN (SELECT tid FROM taxonomy_term_hierarchy)')->fetchCol();

foreach ($tids as $tid) {
  taxonomy_term_delete($tid);
}

Be wary that you don't delete top-level terms that have a parent of 0, since that record will not appear in your sub-query. It'll probably need a bit more thought, but the above code won't be too far off what you end up using.


Prevent Drupal from timing out during a large node export? Is there a setting to prevent drupal from timing out during long operations?

There is (obviously ;)) no setting to make Drupal faster, so you're only chance is to allow it to run longer.

You will only be able to change these settings if you are running your own server. If so, then see http://drupal.org/node/207036 and http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time.

You could also ask your hoster nicely to increase these settings for you, but that might not happen as these settings are usually setfor good reasons (On shared hosting servers are usually tons of users, so hosters want to prevent that one of those users is taking up too many ressources from others..)


Add Attachment to Rules Email - Drupal 8 I am trying to set up a simple rule in D8 that when a new node is created, an email is sent out that includes an attachment from the file system.

How can I accomplish this?

Drupal core does not provide a way to send HTML e-mail or to send e-mail with attachments. Thus, you will have to use a separate module which has this functionality AND which integrates with Rules. One such module is Mime Mail. Mime Mail does have a D8 port, but it's not complete. When it is complete, Rules in D8 is ready and able to use that functionality.


Arranging related nodes in doubly linked list I've an article and related stories. So I want users to navigate between the stories left or right or back to parent(the article).

Book module does it but when having 100's of books(articles) it could be cumbersome.

Is there any module in which I can create queues/groups which can be browsed much like book module based node pages? Nodequeue does not generate prev/next links and I don't think it provides what I want.

Any suggestions?

I've used the PrevNext module to accomplish a similar requirement.

Out-of-the-box functionality of this module would normally cover basic requirements in choosing the Previous and Next nodes such as:

Selection based on node created or changed date.
Selection based on node's nid field and title.
Additionally one has the ability to limit the previous and next to nodes of the same content type.

The nice part is that for any given node the previous and next nodes will be determined earlier and saved in the module's table by its own cron task (hook_cron implementation). Hence instead of determining the previous and next nodes (which could be costly in terms of time and space) while viewing a node and adding those to the page load a simple select query gets the predefined value.

Making call to prev_next_nid with your node id and operation as 'prev' or 'next' would provide one with the previous and next nodes' values which can themed to be displayed.

Additionally a hook hook_prev_next_nid is provided for developers to customize the function.

The caveats are that

if your logic for prev/next are not covered within the default functionality you might have to consider alternate means as there's not much option to cover such features as stated in the module's home page and
that the module showing up as dev version if you feel insecure by that status. However  it seemed to work pretty well for me and appeared to be stable.

Note that the prev/next index will be cleared and rebuilt from scratch when user changes settings per a node type in the admin interface.


Pre-populate Commerce Shipping Cart using a link I need capability to pre-populate commerce cart using a link (preferably add to the cart if one already exists).

For example a link like http://aziteez.com/cart?add_product=prod1+prod2 should add prod1 and prod2 to the existing cart of the user on my website.

Thanks in advance.

You could use Rules for triggering an event on your link with Rules link event and maybe combine it with Rules Link to attach the link to your commerce order entities.

If you prefer to code, you'd need either to create a new menu using hook_menu or alter an existing one with hook_menu_alter and then use commerce_cart_product_add or commerce_cart_product_add_by_id to add the product to the cart user, you can retrieve the current cart from the user with commerce_cart_order_load


drupal_render does not render concatenated elements I am new to Drupal and wonder if users who have experience in this kind of questions can help me with my issue.

The problem is that the output of $complete0 through drupal_render() results in an empty space. Replacing $complete0 with either $title0 or $name0 works just fine, however trying to render a concatenated field does not get the job done. Please see the piece of code below:

    try{
        $title0 = field_view_field('profile2', $user['recommendation'], 'field_rec0_title');
        $name0 = field_view_field('profile2', $user['recommendation'], 'field_rec0_title');
        $complete0 = "{$title0} {$name0}";
    }
    catch (EntityMalformedException $e) {}
    if(empty($complete0)){
        $form['profile_evaluation']['field_field_eval_rec0']['und']['#title'] = 'Information missing';
    }
    else{
        $complete0['#title'] = 'Recommender 1';
        $form['profile_evaluation']['field_field_eval_rec0']['und']['#title'] = drupal_render($complete0);
    }

drupal_render() renders an array.

The var $complete0 in your code is a string, so you shouldn't be passing it to drupal_render().

Either use render(), which works for strings too, or convert $complete0 to a render array.


During insertion of the field in the drupal view, there is image contained text but text is displaying not in image During insertion of the New field in the Drupal view, there is content type field containing text and image but text is displaying not in image what to do ?

for example

Filed Name : text_field

During insertion of the that text_field in the Drupal view the new image not visible what to do? i wanted to display that new image also.

It might be field settings issue.. Make sure your field has "full_html" format also,

Make sure formatter is default in view field settings..

Make sure Rewriting results has not been enabled..


Adding classes to menu items to signify what level they are How can I add classes to the  or
 tags of the main menu to signify which level they are in the menu hierarchy (e.g. "level-1", "level-2", etc.)? The code below shows the first link has 3 sublinks (dropdown):

    Top link

Dropdown 1

Dropdown 2

Dropdown 3

    Another top link

You can use theme_menu_link() in Drupal 7.

function MYTHEME_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  $element['#attributes']['class'][] = 'depth-' . $element['#original_link']['depth'];

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

Here I added:

$element['#attributes']['class'][] = 'depth-' . $element['#original_link']['depth'];

Which will provide a class on the list item with the menu depth.


Restricting block changes How can you let an editor edit the text in a block, but not make other configuration changes, as moving the block from one region to another?

In Drupal, only the users with the permission to administer blocks can change the block settings, including which region the block is assigned.

As far as I know, there aren't modules that allow to assign to users a more granular permission. You should write your own custom module that shows only the fields that a user is allowed to edit.

For example, the following code would alter the form build from block_admin_configure(), the function that build the configuration form for any block, to permit to users with the "edit block titles" permission to edit the block title.

function mymodule_form_block_admin_configure_alter(&$form, &$form_state, $form_id) {
  if (isset($form['settings']['title'])) {
    $form['settings']['title']['#access'] = user_access('edit block titles');
  }
}

The function is the implementation of hook_form_FORM_ID_alter() made for a module named mymodule.module.

The fields for the region settings (the theme regions a block is output) are contained in $form['regions']; The field set contains a select field for each enabled them.
To show the field set only to users with the "edit block regions" permission, you can use the following code, for example.

function mymodule_form_block_admin_configure_alter(&$form, &$form_state, $form_id) {
  if (isset($form['regions'])) {
    $form['regions']['#access'] = user_access('edit block regions');
  }
}

Users with the permission to administer blocks could alter the region assigned to blocks from http://example.com/admin/structure/block. To not allow the user without the "edit block regions" permission to access that page, you should alter the access handler of that menu, and replace the default access handler with a custom one that would return FALSE when users don't have that permission.
For more information, see hook_menu and hook_menu_alter().


Why do site visitors end up with two sessions after logging in? I have an up and running Drupal 6.30 (latest) site, but some users are having problems logging in.
This is due to the user having two rows in the sessions table, one for uid 0 and one for their uid (this one appears after logging in).
The session for uid 0  should be removed from the database after authentication, but it is not.

Question: How could a user end up with two sessions or why is the uid 0 not removed?

Steps to repeat and further background:

Truncate sessions table
Delete all cookies in browser
Visit site homepage.
This gets a new session for uid 0.
Login
Successful login is seen in the watchdog table.
uid x appears in the session table.
The uid 0 session is not deleted, but I think it should be.

I believe that this causes the browser to send both sessions and Drupal only expects one, so if the uid 0 session is seen by Drupal then the request is seen to be from an anonymous user.

The user is redirected back to the homepage and is presented the login form again and is not logged in. Ironically, the user's name appears in the footer of the homepage as a logged in user.

Additional info: I managed to get some debug info from a user. After logging in the browser also has two sessions. Both have the same SESSxxxxxx name but different values. So it seems the old session is not being destroyed properly.

Full disclosure: I've posted this question on the Drupal Community Forum but haven't had any response after 48h, I hope it's ok to cross post it here.

User always have one session at a time. Every time he logs in or out, new session is created.

Drupal 6 does not clean session table. I don't know if it is supposed to or not, but both my experience and simple Google search reveals it fails to do it.

So you have current session of an logged-in user, and outdated session data he left behind when he stopped to be anonymous.

If this really bothers you, consider moving sessions to APC or Memcached, it's much faster than database way, and unused data will be purged by the storage system even if Drupal will not trigger cleanup.

  The user is redirected back to the homepage and is presented the login form again and is not logged in. Ironically, the user's name appears in the footer of the homepage as a logged in user.

This behaviour I experienced only once - when database was misconfigured, and it reported inserts to session table as successful, but next request failed to read freshly inserted data. Apparently it was database caching, but unable to fix it, we ended up with sessions in RAM, as noted above.


How to add custom sort order to a taxonomy field list? I am trying to sort the list of content according to the weight order given to taxonomy term.

Terminology used:

content type    : contact-person-details

taxonomy        : company vocabulary which has list of company names like company A, company B, ...

session company : every user has a company which is stored in session, users have similar company names too.

how it works now: Imagine I am from "company A" stored in my session. Based on my company, content in a view is getting shown (company A is the taxonomy term used for filtering).
Views are used to filter the content type contact-person-details. Varies from company to company which was tagged to content, based on user session company.

What I am trying to achieve? Image below helps in understanding the visual concept. Imagine list (Test one, Test sort, ...) shown are the company vocabulary lists, just like (company A, company B, ...) I want an additional field or textbox just to the side of each term showing to add weight. This weight should be available in the view so that I'm able to making sorting based on the weight allocated for each content.

I would like to know is there a existing possibility to weight the taxonomy list in field.

If it is still complex to understand I will try to edit my explanation.

The Taxonomy Term Reference Sortable Widget module appears to meet your requirement. Once installed, the module will provide a widget that can be selected for a taxonomy term field via its widget type panel. (Admin -> Structure -> Content Types -> My Content Type -> Manage Fields -> My Field -> Widget Type).

If you have a lot of different terms available this may not be a good choice because it displays a full master list of terms from which you select and order those you need. It does not have an option for using autocomplete to build the set.


How to insert social share buttons in drupal 7 using Bootstrap Social Sharing Buttons? I am using module Bootstrap Social Sharing Buttons in my D7 site.

I can show e-mail, twitter, facebook and google+ but I don´t know how to insert others social buttons like linkedIn.

This module implements networks by harcoding in the module's code. Because it is not much clean way how to implement modules for this use-case and this module is not widely used, I recommend you to use somethink different.

If you dont't want to include third party scripts to your site (they can spy your users and slows down page) you can use this module: https://www.drupal.org/project/service_links It is also widely used, so should be better developed and maintained in the future.


Enable Twig debug doesn't work? Why isn't the Twig debug working on my Drupal 8.2.6 site?

This is the folder structure.

These are the folder permissions.

This is the content of the settings.php file.

$settings['hash_salt'] = 'DEVELOPMENT_SALT';
$settings['update_free_access'] = FALSE;
$settings['file_public_base_url'] = 'http://localhost/files';
$settings['file_public_path'] = 'sites/default/files';
$settings['file_private_path'] = 'sites/default/private';
$settings['file_scan_ignore_directories'] = [
  'node_modules',
  'bower_components',
];
if (file_exists(__DIR__ . '/../development/settings.development.php'))     {
  include __DIR__ . '/../development/settings.development.php';
}

Here I include /../development/settings.development.php.

assert_options(ASSERT_ACTIVE, TRUE);
\Drupal\Component\Assertion\Handle::register();

/**
 * Enable local development services.
 */
$settings['container_yamls'][] = __DIR__ . '/development.services.yml';

$databases['default']['default'] = array(
  'database' => 'dbname',
  'username' => 'dbusername',
  'password' => 'pw',
  'prefix' => '',
  'host' => '127.0.0.1',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

$settings['hash_salt'] = 'DEVELOPMENT';

$config['system.logging']['error_level'] = 'verbose';
$config['system.performance']['css']['preprocess'] = FALSE;
$config['system.performance']['js']['preprocess'] = FALSE;
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] =     'cache.backend.null';
$settings['extension_discovery_scan_tests'] = TRUE;
$settings['rebuild_access'] = TRUE;
$settings['skip_permissions_hardening'] = TRUE;

Here I also add development.services.yml.

parameters:
  http.response.debug_cacheability_headers: true
  twig.config:
    debug: true
    auto_reload: true
    cache: false
services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory

Things I have checked/done:

Checked if all these files are loaded -> They are
Checked the indentation of the development.services.yml -> Checks out
Cleared all the different caches, rebuild them, etc -> If I change a template, it changes, but no Twig debugging

sites/default/files AND sites/default/private are not used by Drupal.

Try to change your development.services.yml to following. this  works for me correctly(I hope works for you too) .

services:
  cache.backend.null:
    class: Drupal\Core\Cache\NullBackendFactory

# Enable Twig debugging.
parameters:
 twig.config:
   debug: true
   auto_reload: true
   cache: false

also  this article about setting up debugging on Drupal 8 is very good for future visitors of this question.


Print the main menu in overridden node page In development site. I am using sitemap page so i need to print the all main menu and submenu in that page. I am using this code, but it is not working.

$main_menu = menu_navigation_links('menu-main-page');
echo '<pre>main menu';print_r($main_menu);

How can I achieve it?

If you want to render the menu for sitemap purpose, better to use the "Sitemap" module

Configuration page from this link

admin/config/search/sitemap

You can see the below screen on configuration page,

Just check the menu, which you want to display in sitemap.

After this you can access your page with /sitemap url and you can see your menu there on that page.


Format date field in twig Date field having multiple values. Need to format the output.

{% for item in items %}
<div{{ attributes }}>{{ item.content|date(format="F j, Y") }}</div>
{% endfor %}

item.content showing the date as updated. But not able to format the result. Got the below error,

  TypeError: DateTime::__construct() expects parameter 1 to be string,
  array given in...

Please suggest on this issue.

In Twig, drill down to the timestamp value:

node.html.twig:

{{ content.field_name['#items'].value | date('F d, Y') }}

For a loop, do:

{% for items in content.field_name['#items'] %}
  {{ items.value | date('F d, Y') }}
{% endfor %}

field.html.twig:

{% for item in items %}
  {{ item.content["#markup"] | date('F d, Y') }}
{% endfor %}

Note: Set field format display option to plain or custom if using the field template. This field option can break your site just by someone changing the format option for the field, so use caution.


Combine Webforms to export multiple form results in a single CSV I need to be able to select multiple webforms and then be able to export all of their results in a single CSV download.

I am considering using this module (Views data export) but I'm not yet sure it will fit the task.

Any suggestions on the approach you would take would be appreciated.

UPDATE:
I approached this using the 'Webform Mysql Views' module but the process is incredibly time consuming as each Webform needs to have a view created for its submissions. These fields then need to be associated in the Webform Submissions view and duplicate fields need to be merged.

Webform 4.x is integrated out of the box with views on drupal 7.

Upgrade to last webform 7.x-4.x release.
Create a view: webform submissions
Select each field: webform submission data:Value and your webform node to extract the fields

To download all results the best option is Views data export, you should configure it to use batch for better performance.


Exposed date select list in descending order Using Drupal 7 Views with exposed filter on date, the select list is working fine. Problem is that the list is always in ascending order, for example 2000:2014, but we want it the other way round, like 2014:2000 so that the recent years are closer at hand.

I don't mind if the solution (changing date list to descending order) is affecting every select list of the whole site. Preferably if don't need to change code.

You can do this via hook_form_alter().

function myModule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form['#id'] == 'FORM-UNIQUE-ID') {
    $form['field_MY_FIELD_value']['value']['#process'][] = date_select_desc_element_process;
  }
}


Converting static site to Drupal 7 - How to set-up department sites? I am new to Drupal.  We have a corporate site that is static html, has 13 departments.  The template for the department sites are very similar to the main corporate site.  The departments will not have a different DNS assigned to it, that is, the structure will be as so:

main site URL:  www.mycorp.com
department Site:  www.mycorp.com/hr

We would want the departments to update their own content. Each department has about 10 pages to maintain, but can grow. It is also important that all of the departments' content is  shared/accessed/searched by the main corporate site. Would Drupal 7 multisite set-up be recommended for this?

I think multisite is not the optimal solution for you. With a multisite installation, you will end up with completely separate sites that have their own content, categories, users, settings, user files etc. etc. In my experience, that is often too much separation for a site like yours.

For instance: With multisite, if one person needs to get access to two or more departments, you need to create a user account for him in each site. He will also need to login in every site. Another example: With multisite, it's not easy to take content from a department site and promote it to the main home page.

In your case, I would look into a solution built with Workbench and Workbench Access, or perhaps Domain Access. With those modules, you will end up with a system that is technically a single site, but where Drupal is configured to split the site into sections and control user permissions on a per-section basis.


How to programmatically send an email? I'd like to use Drupal's email system to programmatically send an email from my custom module. Is that possible?

Using hook_mail and drupal_mail you can create and send an e-mail.

Implement an e-mail use hook_mail:

function MODULENAME_mail ($key, &$message, $params) {
  switch ($key) {
    case 'mymail':
      // Set headers etc
      $message['to'] = 'foo@bar.com';
      $message['subject'] = t('Hello');
      $message['body'][] = t('Hello @username,', array('@username' => $params['username']));
      $message['body'][] = t('The main part of the message.');
      break;
  }
}

To send a mail use drupal_mail:

drupal_mail($module, $key, $to, $language, $params = array('username' => 'John Potato'), $from = NULL, $send = TRUE)

Obviously replace the parameters: $key should equal 'mymail'

An e-mail is sent in a few steps:

drupal_mail is called
Drupal builds the e-mail
hook_mail is called for the specifics (implementation)
hook_mail_alter is called so other modules can modify it
drupal_send_mail is called


How to reset the display of nodes? For some reason I can no longer manage the display of a node in the backend. Managing the form display works but not the frontend display managing. I get the following error message:

  Fatal error: Maximum execution time of 50 seconds exceeded in
  /customers/2/f/2/igghq.com/httpd.www/core/modules/field_ui/src/Element/FieldUiTable.php
  on line 100

I can still manage the display of other content types. Just not that specific one. Is there a way to reset the manage display backend form, maybee through the database?

running display suite
Drupal 8

More info: it only locks-up when loading the default display mode. Teaser still works

Wanted to post my solution(i encounter it too) if anyone stumble upon.

You don't have to uninstall and reinstall fieldgroup if you know which content type is causing this issue.

Go to Configuration Export ( [your URL]/admin/config/development/configuration/single/export)
Choose Entity View Display in  Configuration type
Look for your content type in Configuration Name
Copy the configuration that appeared in Here is your configuration:
Open a text file and paste your config.
Look for field_group: , delete it together with it's child or until id
Then re-import your config.

That works for me without resetting other content type field groups.


Form preview before submission I have written a form using the form API, and I want the user to preview the form before submission. How can this be accomplished?

Effectively this is a multistep form. Display the form showing a "Preview" button. On submit save something to the session or $form_state and redisplay the form. If the value has been set in the session show a "Submit" button. On this submit you can save the form values to the database and clear whatever flag value you had in the database.


Services 3 Session authentication CSRF Validation with Persistent Log in I am trying to use Services 7.x-3.11, the latest stable available to authenticate and access Drupal 7.34. Accessing from mobile devices with Native coding. I want to keep the user authenticated forever. Is it possible?

Here is the workflow i am following.

First launch of app

POST /services/session/token to retrieve CSRF Token
POST myendpoint/system/connect with X-CSRF-Token header
IF not Logged In Try Log in /myendpoint/user/login
Log in Success and keep session_name=sessionid in Cookie Varible

Future Launches

POST /services/session/token to retrieve CSRF Token
POST myendpoint/system/connect with X-CSRF-Token header along with previousely saved session_name=sessionid as Cookie Header

From this point I am getting ["CSRF validation failed"] message. Am I missing something? Is the workflow correct?

Evidently the workflow has been simplified.  I make a single call to /user/login.  Here is an example:

{
  "method": "POST",
  "url": "http://HOSTNAME/SERVICE_PATH/user/login",
  "headers": {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "Connection": "keep-alive"
  },
  "json": {
    "username": "USERNAME",
    "password": "PASSWORD"
  }
}

which returns:

Response: {
  "sessid": "waroHcB4h8rbU0yhZjh-zGLAquZYlpayC_kB38gx--I",
  "session_name": "SESSb4d5ba755bb4eb727d982993490e6681",
  "token": "MHT4hmagxHgf0lOYlkENGlTZGk2AZ96G3p3ZCCc2kvo",
...
}

Now the cookie is created by concating the session_name and sessid with the equal sign separating them.  The X-CSRF-Token header is simply the token in the response.  All future requests will reuse the X-CSRF-Token: and Cookie: headers:

Here is an example of a user profile request:

{
  "method": "POST",
  "url": "http://http://HOSTNAME/SERVICE_PATH/user/profile",
  "headers": {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "Connection": "keep-alive",
    "X-CSRF-Token": "MHT4hmagxHgf0lOYlkENGlTZGk2AZ96G3p3ZCCc2kvo",
    "Cookie": "SESSb4d5ba755bb4eb727d982993490e6681=waroHcB4h8rbU0yhZjh-zGLAquZYlpayC_kB38gx--I"
  }
}

Short answer: call /user/login once, set and reuse the X-CSRF-Token: and Cookie: headers for all future REST calls.


Where can I find the form API reference? Form API Reference gives information about which properties to use for a form array, for Drupal 7.

Where can I see what properties I can use in buildForm(array $form, FormStateInterface $form_state), such as #type, #title, #required? How can I know the other possible properties?

Actually I'm using the Drupal 7 information in Drupal 8, and it works, but there should/must be an updated page, I guess.

Many of the form element properties are listed in the documentation for the FormElement class. The properties described there are:

#after_build
#ajax
#array_parents
#default_value
#description
#disabled
#element_validate
#field_prefix
#field_suffix
#input
#parents
#process
#processed
#required
#states
#title
#title_display
#tree
#value_callback

Then, as Form and render elements says:

  Each form and render element type corresponds to an element plugin class; each of them either extends \Drupal\Core\Render\Element\RenderElement (render elements) or \Drupal\Core\Render\Element\FormElement (form elements). Usage and properties are documented on the individual classes, and the two base classes list common properties shared by all render elements and the form element subset, respectively.

(Emphasis is mine.)

There isn't a single page describing all the form element properties, but there is a page for each plugin class that implements a form element.


Is it redundant to use the "boost" module if varnish is used? We run our Drupal instances behind a Varnish server, but we're looking at alternative/additional ways to speed up the site. Boost is a module that is frequently named for this purpose; it appears to generate static versions of pages and serve those to avoid regeneration time, but—if we're already caching with varnish—does this give us any benefit?

No, with the correct configuration, Boost and Varnish can work together. The combination is said to speed up your site even more than just Boost or Varnish (I haven't tried it myself yet).

See Will Boost conflict with Varnish and Use Varnish for cache storage instead of file system. If you're visiting DrupalCon London, check out the Boosted Varnish talk.


How can I create a breadcrumb? I have to create a breadcrumb so that, if a page has a menu, the breadcrumb should be the menu with its hierarchy. If the node page doesn't have a menu, the page title should be in the breadcrumb.

I tries the Menu breadcrumb module. Menu pages are coming correctly, but other pages are showing the page title in the breadcrumb.

How can I achieve this?

You can do this by creating custom module and creating yourmodule.services.yml

services:
  yourmodule.breadcrumb:
    class: Drupal\yourmodule\FwsBreadcrumbBuilder
    tags:
      - { name: breadcrumb_builder, priority: 100 }

and creating custom class which should extend BreadcrumbBuilderInterface like this

class FwsBreadcrumbBuilder implements BreadcrumbBuilderInterface {
  public function applies(RouteMatchInterface $route_match) {
    $route = $route_match->getCurrentRouteMatch();
    // Add conditionals that return TRUE when the current route should have it's
    // breadcrumb handled here.
    return FALSE;
  }

  public function build(RouteMatchInterface $route_match) {
    $breadcrumb = new Breadcrumb();
    $breadcrumb->addCacheContexts(['route']);

    // Add logic here that builds up the breadcrumbs based on desired behaviour.
    $links[] = Link::createFromRoute(t('Home One'), '<front>');

    $breadcrumb->setLinks($links);

    return $breadcrumb;
  }
}

I have also got the above code from http://drupal.stackexchange.com

You can also add new and alter previous breadcrumbs in hook_preprocess_HOOK function like this

function yourmodule_or_yourtheme_preprocess_breadcrumb(&$variables) {
    // Your Logic Here
}


I get a "URL not found" error, but the image is on the server I have a Drupal site which I have just migrated to a different Linux server for development. The site seems to be working more or less.

However, one problem persists: None of the images is shown. Instead, if I click on an image, it says: "Requested URL not found."

What is more, all of these images exist in the proper directories. I checked .htaccess for RewriteRules but did not find anything relevant. I have also played with permissions. Currently the entire root of the site is set to 755.

What can I do to make the images work?

If you have some sort of caching service like "Varnish" active you may want to try clearing it's cache.

This sometimes happens to me and I just need to clear my browser's cache.


Most simple way to integrate a html/jquery block into the system? i want to build a form with jquery and html without using drupal forms api (looks too complicated for me to put effort on that). How can i do this?
How do i have to use a node and how would that be visible?
Does anyone know a tutorial for this?

I would appreciate any kinds of hints...

Surely you could just build the HTML form as you normally would, and set the Filter Format to Full HTML (if you're using the WYSIWYG).  Seems an odd way of doing things though to be honest!

You could also take a look at the Webform module.  That'll allow you to store form submissions easily as well!  Or Form Builder, but I've never used it before and it doesn't appear to have a 1.0 release.

On another note, the form API in Drupal is not only REALLY powerful, but actually easier than it looks!  It's definitely worth taking time to learn, as you'll find yourself coming back to it again and again!


Dynamic allowed values list How  to display dynamic allowed values list in drupal 8?

In drupal 6 while creating cck select list, I written php code instead of entering allowed values. The sample code of drupal 6 is as follows :

$query = db_query("SELECT distinct field_x_value as x FROM {node} n, {content_type_y} ctdr , {content_field_x} cfer WHERE n.nid = ctdr.nid and cfer.nid = ctdr.nid and field_x_value is not null and field_user_state_value = %d and n.status = %d and field_environment_value = %d", $user->user_state, 1, $environment);

How to do the same functionality in drupal 8?

It's not possible to set it in the UI, but it's still possible through code.

If you check the exported configuration for your field, you can see that it has an allowed_values_callback property. Create a custom module, create a function that returns the allowed values, set that property in config and then import the configuration again. Or use drush cedit or a similar tool.


Exporting and Importing configuration setting only I have a development and a production site. Both are working in an offline environment, Drush and Composer are not installed.

The plan is to make all changes always on the development and during each "release" to simply synchronize the changes on the production site.

Currently this is working fine via UI  "Configuration Synchronization -> Import/Export " feature.

But I would like to execute this on the command level ( Linux ) and as it was mentioned, no drush is installed.

Question:
Is it possible to export just the CONFIG Table from MySQL database and import this on the production site? Would this be similar to the Import/Export mentioned above?

Importing configuration in SQL alone is not possible, you need to run PHP code.

From the command line, if you don't have Drush installed, you can download Drush on the fly and execute the import command:

wget https://github.com/drush-ops/drush/releases/download/8.1.17/drush.phar
php drush.phar config-import


change Your search yielded no results I would like to set a custom message for my search using the core Drupal search module. Right now it says:

  Your search yielded no results Check if your spelling is
  correct. Remove quotes around phrases to search for each word
  individually. bike shed will often show more results than "bike
  shed". Consider loosening your query with OR. bike OR shed will
  often show more results than bike shed.

The core Drupal search module uses several template files that dictate both how search results are displayed, and what's displayed when there are no search results.

If you're already using a custom theme on your Drupal site, the best way to customize those would be to copy and paste the entire 'search-results.tpl.php' file from the search/ module folder into your own custom theme subfolder.

Open that file up for editing and you'll see the following at the bottom:

<?php else : ?>

<?php print t('Your search yielded no results');?>

  <?php print search_help('search#noresults', drupal_help_arg()); ?>
<?php endif; ?>

This is what's displayed if search results are not found (thus the 'else')...  Modify the text to be anything you want here.  The second line, which calls the search_help() function is the one that displays the search suggestions.  Feel free to replace that too....

And as always, before you can see your changes, you'll probably need to clear cache!

Let us know if this works for you!


Module not found during installation I am creating an install profile that requires, among other things, a slew of Features. Because of the intricacies of the project, which is a multi-site, I have in sites/mysite.com/modules/custom_features 3 different categories of features, each in its own folder: my_install_profile/, my_other_install_profile/, and common/.

Drupal seems to be finding all of the modules that my install profile requires just fine, except one. It's expecting to find it in sites/mysite.com/modules/custom_features/my_install_profile/ but the module actually lives in sites/mysite.com/modules/custom_features/common/.

I've triple-checked the install profile, and any dependent modules. I can't find anything path-specific, or specific to this module, that might be causing the confusion.

It doesn't report that the module is missing at the beginning of installation, but partway through I get this:

Warning: include_once(umn_import_content_type.features.inc) [function.include-once]:
      failed to open stream: No such file or directory in include_once()
      (line 7 of /www/sites/mysite.com/modules/custom_features/my_install_profile/my_feature/my_feature.module).

Warning: include_once() [function.include]:
      Failed opening 'my_feature.features.inc' for inclusion
      (include_path='.:/Applications/MAMP/bin/php/php5.3.14/lib/php') in include_once()
      (line 7 of /www/sites/mysite.com/modules/custom_features/my_install_profile/my_feature/my_feature.module).

Why is Drupal looking for this in the wrong folder?

It appears that the issue was at the infrastructure level. The error resolved when I restarted Apache.


print field in views row template I try to make a custom view using templates. I need to print one certain field at the last row, after all other fields have been printed like so:

--1st row
field1
field2
--2nd row
field1a
field2a
--last row
myfield

I can manage to display a custom field inside field template like so:

<?php print $fields['title_1']->content; ?>

However there are few problems:
1/to display the field as needed, I should print the field inside row template - but above code doe's not work inside row template, only inside field template.
2/the field get's printed twice - as normal field and as a field called directly from template as well.

The questios are
1/how can I print a field called from other than field template?
2/To prevent printing the field twice, I assume I need to exclude it from display, but after that it is not available inside template.
I found this article https://drupal.org/node/687046 where people say it is possible. I used following code but it is not working

print_r($view->result[$id]node_data_field_title_1_field_title_1_value)

can anyone point me to right direction?

Thank you

ANSWER: the correct code to put inside row template is

print $view->result[$id]->node_title

this displays excluded field

I can't comment yet, or I would to inquire further about your use case.

Instead, I'll just provide an answer in hopes it helps.

Do you absolutely need to use a template file? In Drupal 7 Views 3, there are options for each field to customize the html for the field label and value if desired. See attached view field style settings to see how this is configurable.

Optionally, you can set the html to none and rewrite the output to include your specific markup. See second attachment.

Hope that helps, Jason.


Is backlinking possible in drupal 7? Is there a way to tell what pages within the site link back to a particular page within the site?

Create a view of the pages with, for example, a list of tiles linked to the content. Then create a contextual filter using the entity reference field. In the Contextual Filter configuration for the entity reference, select 'Provide default value > Content ID from URL' under 'When the filter value is NOT available'.

Set the view to display as a block on the page, and it will display a list of the titles referencing that page.


Using `hook_field_attach_presave` for replacing characters In Drupal 7, I used hook_field_attach_presave() to replace characters of a body field in the moment when the node is saved. Now i want to use the code for Drupal 8, but could not get it to work:

function my_module_field_attach_presave($entity_type, $entity){
  dpm($entity);
  $replacement_pattern = '/(?<=\d\ )x(?= \d)/'; // replace a "x" surrounded by numbers with symbol "×"
  if(!empty($entity->body->value)){
    $entity->body->value = preg_replace($replacement_pattern, ' &times; ', $entity->body->value);

}
The above code does not work, not even the dpm($entity) is printed. What is the problem here, is the hook not available in D8? I just found it here, not on official drupal sites. So if it does not exist, what's the alternative?

EDIT: Thanks to @Clive I got it working. Here's the code:

function my_module_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $entity->setTitle('dd The new Title');
  $replacement_pattern = '/(?<=\d\ )x(?= \d)/';
  if(!empty($entity->body->value)){
    $entity->body->value = preg_replace($replacement_pattern, ' &times; ', $entity->body->value);
  }
}

hook_field_attach_presave() was removed some time ago, there's no such operation in Drupal 8.

You can, however, use hook_entity_presave() or  hook_ENTITY_TYPE_presave() instead.


How to to check if user has changed the password? I wanted to send basic notification email to the user, after it has changed the password, to inform him of password change.

I am using Rules modules for that. But I am not finding any option there, to add condition if user has changed the password.

Is there any way I can check if user has changed his password using rules or pragmatically.

-- Many thanks for your time.

The easiest would be to do this using Rules. Following the next steps, should do the job.

Ensure you have enabled the "PHP filter" on the modules page. This is needed to be able to use PHP code inside Rules.
Create a rule that reacts on the user event "After saving a new user account".
Add a condition of type "Execute custom PHP code" and use the following snippet: return $account_unchanged->pass != $account->pass;
Add your action(s) to send an email notification to the user or anything else that fits your purpose.


How can I add a search feature to my Drupal 7 Zen child theme frontpage? I would like to add a search form to the front page. I've added this to my template.php:

function my_theme_preprocess_page(&$variables){
   $search_box = drupal_render(drupal_get_form('search_form'));
   $variables['search_box'] = $search_box;
}

I've added this to my page.tpl.php:

<?php print $search_box; ?>

After viewing my site I do see the search form but get this error:

  Strict warning: Only variables should be passed by reference in
  denta_quest_preprocess_page() (line 142 of
  C:\xampp\htdocs\drupal\themes\my_theme\template.php).

Your probably getting the warning because the function takes its argument by reference and to pass a variable by reference it needs to be defined. You're passing a function call which isn't a variable.

Try the following...

$search_form = drupal_get_form('search_form');
$search_box = drupal_render($search_form);
$variables['search_box'] = $search_box;


Multigroup field in view only showing single delta How are CCK multi groups handled in a view? Because when I select the fields for the views, they come with a "delta" field:

The delta fields are always empty, so it doesn't work out of the box. The delta fields are always empty in the table view.

Is there any way I can have support for multigroup fields, or even a way to concatenate the delta's of the three fields ('Naam', 'Bedrijfsnaam', 'E-mailadres') for each delta?

OK, to get this to work on Drupal 6, CCK 3 and Views 2, I spun up a testbed on the ever trusty Pantheon and created a content type:

and then created three nodes, the first one had two sets of name/biz/email, the second had one and the third had three.

I then created a View:

with these results which I hope is what you were after.

Things that needed to be done differently:

One.  Add in that Content multigroup filter.  I just chose 'Name' as the field to join on.

Two.  Turn off all grouping of the Fields, eg uncheck this in their setup:

Three.  Put all the values in the Global Custom Text field:


Translated content not accessible / wrong links At the moment I am working on a multilingual page (German/English). I finished adding my German content, and want to add my English version, so I can access it like examplesite.com/examplepage (German) --> examplesite.com/en/examplepage (English).

The steps I did so far:

I enabled the right custom language settings for translation
I added the needed pathauto-patterns
added a path-prefix-configuration for English "en"

My problem now is the fact, that I can't access these pages after adding the translations.

This means when I access a German site in the front end, and click the language switch to the English version, it won't link me to the translated content but only refreshes the page.

The same weird behaviour is shown in the backend on the content-overview page. The translated pages all exist in the list and if I hover over the title it will show me the right URL like e.g. examplesite.com/en/examplepage but when I open the url it will just show me a 404. It seems that the content is not connected to the right, translated urls.

Am I missing something?

In addition to enabling "URL" Detection method (path prefix or domain) and positioning it to be used first, you also have to Configure it.

Set German as your Default language under  Administration > Configuration > Regional and language
Go to the Language Detection and Selection page and enable the "URL" Detection method
On the Language Detection and Selection page click through the Configure button for the URL (/admin/config/regional/language/detection/url)
Select "Path prefix" as the " Part of the URL that determines language" option
Delete the de from the "German (de) path prefix (Default language)" option
Clear cache! This can be tricky through the interface if you're using the admin module because the /de/ might linger on the menus but will lead to a Page not found. Delete the /de/ in your browser Location bar from the flush cache link to make it work.

After this you should have the correct Home in German, without the /de, German content and links without the prefix and English content and links with /en/.


Output all possible items in a list field as a View? Is it possible to output all of the possible options in a list field type (of a content type) as a view?

My own answer (but still feel free to chip in):

Create a View of the Content Type containing the list.
In the FIELDS section only have your Content Type Field that contains the list Content: (whatever the name of your list field is called)
Click on your Content Type Field under FIELDS for the 'Configure field: Content: Your field' Under Multiple Field Settings, make sure display multiple fields on one row is unchecked
add your Content Type Field to the FILTER CRITERIA. Filter should be set to 'is not empty' / not null
over to the right hand side of the Views settings, enabled Aggregation
back to FILTER CRITERIA and click Aggregation Settings for your content type field and select COUNT DISTINCT.

What this does is produce a unique list of items from all of the content that has this field with those items checked.

What it won't do is show items in from the list field if they have not yet been selected in any content.

It may also have a performance overhead to generate the list like this as it is based on the data from the entire set of content. The positive benefits flipside of this is that perhaps you only want to see items where there is content that has it checked and you may want to extend the list to include number of content using a list item.

Final thought - why did I not just use a taxonomy? this would have been far easier and Views supports this better. Reason: currently (at the time of writing), Views does not support context filtering on taxonomy where multiple arguments are provided in the URL. I want to use this list from this View as a menu block to filter data in a View in another block in Panels from multiple fields.

References / Credits:

How do I remove duplicates when using the random sort?


How to add custom css class to block wrapper I need to add custom css classes to several blocks (can be blocks from view, or facet api, etc).
Is there a way to do it without creating a template for every block?
It could be useful a theme function, or a hook, that should do something like:

 if ($var == 'block_name') {
   $class_custom = 'my-custom-class';
 }

Is it possible?

You can also use the Block class project for the matter.

  Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent  element of a block. Hooray for more powerful block theming!


node_delete_confirm_submit() and hook_node_delete() Still getting my head around Drupal 8 after using Drupal 7 for so long. I want to override (alter) the node delete action. Now in Drupal 7 I would have used  node_delete_confirm_submit() and hook_node_delete() or similar such as using hook_form_alter and changing the submit function.

In Drupal 8 this has partly changed. I can still use hook_node_delete(), but there is no node_delete_confirm_submit() which was deprecated in favor of \Drupal\Core\Form\ConfirmFormBase. Rather than try and create a hack I would like to learn the proper way I should be doing this.

I have tried to use ConfirmFormBase. I have a src/Form/DeleteXXXConfirm.php file.

namespace Drupal\XXX\Form;

use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

class DeleteXXXConfirm extends ConfirmFormBase {

   ... code here for confirm and delete ...

}

Since I want to override node/nid/delete, I assumed the routing file would look something like this.

XXX.delete:
  path: '/node/{id}/delete'
  defaults:
    _form: '\Drupal\XXX\Form\DeleteXXXConfirm'
    _title: 'Confirm Deletion'
  requirements:
    _permission: 'administer site configuration'
    id: ^\d+$

This doesn't appear to work, do I need a Controller? Or am I totally barking up the wrong tree? I am obviously misunderstanding something. Can anyone point me in the right direction?

I've found inspecting the routes availble and then working back to the controller to be a super helpful way to understand how to override things.

You will need Drupal console installed.

For example run

drupal router:debug | grep node | grep delete

This will list all routes, and then filter only ones with node in and then filter only ones with delete in.

You should then see the route you are interested in (/node/{node}/delete) is called entity.node.delete_form

Now you can debug just that specific route:

drupal router:debug entity.node.delete_form

This will show you that the form for this route is called node.delete. If however there was a method and a controller for the route is would show you exactly what the callback is.

To change the entity.node.delete_form route to use your own callback you can use the new method of doing menu_alter.

However if you want to keep the same node delete form and just change the submit handler then you can still use hook_form_alter to change this.


How do you define an arbitrary sort sequence for views? Take a look at the Drupal issues queue and the Priority column.  If sorted in descending order you get critical, major, normal, and minor issues, in that order.  Since "normal" would not go between "major" and "minor" in alphabetical order, they've obviously defined a custom sequence to use for sorting.  How is this done in Drupal?

Is it merely sorting based on a numeric value that is not displayed?  Or is it more clever than that?

Views has hook_views_query_alter, which lets you mess with the query object that it maintains.  It gets called before the query object gets converted to SQL.  You can change the sorting that is set in the UI with something like:

function mymodule_views_query_alter (&$view, &$query)
{
  $query->orderby = array('node.nid ASC');
}

Basically, the value you use is what would be after the ORDER BY in a normal query.  You should be able to use an ORDER BY CASE,

function mymodule_views_query_alter (&$view, &$query)
{
  $orderby = "
    CASE
      WHEN node.type = 'page' THEN 1
      WHEN node.type = 'article' THEN 2
    END ASC
  ";
  $query->orderby = array($orderby);
}

You will need to enable previewing the SQL in Views (it's in the main views settings, not with the settings for a particular view) to see the names to use.


How to add metatag module data to the Search API indexes I am in the process of building a new site that will have some content in the form of videos and PDFs. To make those more searchable I added the metatag module. We are also using the Search API to hook into Solr and do our search operations.

I have found the hooks I need to insert, update, and delete metatag info from the metatag fields. That part is fairly straight forward.

However, I am stuck on the part where I tell the Search API about the fields so that they can be indexed. I think I will be able to figure out how to push the data to the index with the hooks. I just don't know how to tell the Search API that the fields are there and that they contain strings.

I was looking, originally, at the hook_search_api_item_type_info(). However, after reading the description in the API documentation (in the code) I realize that it is only for new entity types. These metatag fields are mainly attached to nodes. And the documentation specifically says that it should not be used for existing entity types (i.e. nodes) because this hook simply tells about the data controller classes.

Should I use hook_search_api_alter_callback_info() to do this? That seems like a good candidate, but I am just not quite following how this works in the SearchAPI.

How do I tell the Search API that the metatag fields exist and I want to be able to index them?

This is in Drupal 7.

I do it like this:
First

  function HOOK_search_api_alter_callback_info() {
  $callbacks['search_api_alter_add_keywords_field'] = array(
    'name' => t('Keywords field from metatag module'),
    'description' => t("Adds Keyword field from metatag module to indexed data."),
    'class' => 'SearchApiAddKeywordField',
  );
  return $callbacks;
}

Second

class SearchApiAddKeywordField extends SearchApiAbstractAlterCallback {
  public function alterItems(array &$items) {
  foreach ($items as $id => &$item) {
      if (!isset($item->metatags[$item->language]['keywords']['value'])) {

        $item->search_api_keyword = NULL;
        continue;
      }
      $item->search_api_keyword = strtolower ($item->metatags[$item->language]['keywords']['value']);
    }
  }

  public function propertyInfo() {
    return array(
      'search_api_keyword' => array(
        'label' => t('Keyword field'),
        'description' => t('Add keyword field to index.'),
        'type' => 'text',
      ),
    );
  }

}

After Clear cache go to you index filters and check: Keywords field from metatag module
If Boost settings need to be changed (to give more importance to the field) do it now.
Index Again
Go to the search results view - the view you created to list indexed content.
Assuming that you have fulltext search filter in "Searched fields" select the new "field" Keyword field
Test the things out.


Notice: Undefined variable: node in eval() and Notice: Trying to get property of non-object in eval() After upgrading to Drupal 7, I get the following error on my recent log messages:

  Notice: Undefined variable: node in eval() (line 24 of /home/scode/public_html/modules/php/php.module(74) : eval()'d code).
  Notice: Trying to get property of non-object in eval() (line 24 of /home/scode/public_html/modules/php/php.module(74) : eval()'d code).

The user accessing the page is "Anonymous (not verified)."

Do you have any idea?

Something is trying to run the php_eval() function in php.module. Most likely you have something configured in your site (such as a block) to use the PHP input filter, which evaluates PHP code and prints the output as text. I would check all the blocks you have defined first.

You can also temporarily put a call to debug_print_backtrace() at the top of the php_eval() function and print it's results while browsing your site as an anonymous user to see what exactly is calling that function.


"Enterprise" authentication, single sign-on and user provisioning for multiple sites I'm looking for a solution for user provisioning, authentication and single sign-on which will make it easy for me to manage accounts for all the staff at my company across all of the sites we work on.

My main goal is to have a single point at which I can add/remove users to grant/revoke access to all the sites our staff will need to work on. This is obviously a pretty useful thing on it's own, but it'll also mean that I can ask staff to change passwords regularly without it taking a day to go through every site, etc. All this is in addition to "normal" users which vary from site to site.

The shared tables approach won't work (and wouldn't use anyway), I don't fancy setting up an LDAP server just for this, none of the sites share a domain so Bakery won't work, the OpenID module allows any provider so I can't trust the profile details to automatically set roles, etc.

Is there an existing (production ready) solution that uses, e.g., OpenID but lets me restrict the provider/s to those I can trust? Should I just bite the bullet and start trying to hack at the OpenID module? Am I barking up the wrong tree?

You would have to use a few modules working together to make this happen.

Development Seed had an interesting demo using OpenID, PubSubHub and Feeds.
They detail it at http://developmentseed.org/blog/2010/mar/02/simple-sign-openid

lordg's comment re: hubs is exactly what they did.


Select a taxonomy parent ID based on the current node type for shared field declarations in cck I have a taxonomy vocabulary with the below heirarchy:

*Property Type

 -Commercial
    -Office
    -Building
    -Warehouse
 -Residential
    -Villa
    -Apartment
    -Penthouse

I have two content types for the property information that has a common field called: 'Property Type' relating to that vocab above, again, for the two content types: "Commercial Property" & "Residential Property" they are using the same field declaration that relates to the same vocab group.

I want to use the php advance code to filter 'commercial' and 'residential' whichever content type is concerned. E.g. Villa, Apartment and Penthouse should only show under the "Residential Property" content type.

My Current code is this but it does not work:

if (arg(0) == 'node' && is_numeric(arg(1))) $nodeid = arg(1);
if($nodeid) $type = noad_load($nodeid);
if($type->type=='commercial_for_rent' || $type->type=='commercial_for_sale') return 798;
else if($type->type=='residential_for_rent' || $type->type=='residential_for_sale') return 799;

In other words: Show only the sub category items of 'Property Type' vocab (e.g. "Residential terms") if content type being edited is this (e.g. "Residential Property" content type)...

Can someone help me point to the right direction please.

Thank you!

Apparently, I am answering my own question. This may not be the best solution (the drupal way) but it works and at least for the meantime I can continue the project. Here is how I solved it:

arg(0), arg(1).. will always refer to the current url arguments. so arg(0) will be the first arg after the siteroot, arg(1) is next.. etc..

With my problem, when you are editing a content type here is my current url path for example: http://localhost/mysite/node/add/commercial-for-rent, where arg(0) = node, arg(1)=add etc..

simply posting this to php snippet worked:

if(arg(2)=='commercial-for-rent' || arg(2)=='commercial-for-sale') return 798;
else return 799;

That's at least as far as the url pattern goes. ../node/98/edit is when editing the content which is again this solution will no longer work...

As I said this is not the best solution if there is anyone out there who has better ideas please do tell me so I can edit the snippet and solve this the drupal way.


Restricting access to nodes I am new to Drupal and for some time now I am trying to figure out how to control access to nodes.
After figuring out that no module will give me what I want and deciding that I will have to get my hands dirty and write my own.

The problem is that nothing works and in no way I can restrict access to nodes.

To make things simple I tried blocking everything to anything in any way I found, but it makes absolutely no difference.

function mymodule_node_access_records_alter(&$grants, $node) {
  $grants=array();
}

function mymodule_node_access_records($node) {
  return array();
}

function mymodule_node_access($node, $op, $account) {
  return NODE_ACCESS_DENY;
}

The module is loaded by drupal, it is parsed (I get error messages when something is wrong), I tried clearing the cache, tried loading the module on and off, I disabled OG Access Control (I still have OG field access running).

The OG access modules are working more or less correctly (sometimes they block what you want them to block).

I am probably forgetting about something obvious but I feel like I tried everything.

In the code you are showing there are some mistakes.

If you implement hook_node_access_records_alter(), you don't implement hook_node_access_records() (and viceversa)
If you implement hook_access_records(), then you don't implement hook_node_access() (and vice versa).
If you implement hook_node_access_records(), the other hook that need to implement is hook_node_grants().
Returning an empty array in hook_node_access_records() or setting $grants to an empty array in hook_node_access_records_alter() doesn't mean blocking every users from accessing any node. In fact, the function that invokes hook_node_access_records() and hook_node_access_records_alter() (node_access_acquire_grants()) contains the following code.

$grants = module_invoke_all('node_access_records', $node);

// Let modules alter the grants.
drupal_alter('node_access_records', $grants, $node);

// If no grants are set and the node is published, then use the default grant.
if (empty($grants) && !empty($node->status)) {
  $grants[] = array(
    'realm' => 'all',
    'gid' => 0,
    'grant_view' => 1,
    'grant_update' => 0,
    'grant_delete' => 0,
  );
}

When $grants is empty, it adds the default grant that allows users to see the nodes (if other conditions are met).

Even implementing the right hooks, a module is not able to stop every single user from accessing all the nodes, since:

Users with the bypass node access permission can still access any node; this includes the first user created on a Drupal site
When viewing a node that is unpublished, the user who created it can still see it, if that user has the view own unpublished content permission

See the code in node_access(), in particular the following lines.

  if (user_access('bypass node access', $account)) {
    $rights[$account->uid][$cid][$op] = TRUE;
    return TRUE;
  }
  if (!user_access('access content', $account)) {
    $rights[$account->uid][$cid][$op] = FALSE;
    return FALSE;
  }

  // We grant access to the node if both of the following conditions are met:
  // - No modules say to deny access.
  // - At least one module says to grant access.
  // If no module specified either allow or deny, we fall back to the
  // node_access table.
  $access = module_invoke_all('node_access', $node, $op, $account);
  if (in_array(NODE_ACCESS_DENY, $access, TRUE)) {
    $rights[$account->uid][$cid][$op] = FALSE;
    return FALSE;
  }
  elseif (in_array(NODE_ACCESS_ALLOW, $access, TRUE)) {
    $rights[$account->uid][$cid][$op] = TRUE;
    return TRUE;
  }

Assuming you aren't interested in blocking the access to users with the bypass node access permission, or avoiding that users with the view own unpublished content permission can see their own unpublished nodes, then implementing hook_node_access() is the quicker way to avoid some users can see all the nodes, as long as the nodes aren't shown in a list of nodes, for example a view, or the front page, because in that case hook_node_access() is not even invoked.
Differently, the following code surely works and avoid some users can see every node.

function mymodule_node_access($node, $op, $account) {
  return NODE_ACCESS_DENY;
}

If that code doesn't work, then there is an error in the code of the module your wrote, since:

A single module returning NODE_ACCESS_DENY in hook_node_access() stops users from seeing a node (but remember the permissions part)
Drupal core doesn't use hook_node_access_alter(), so a module cannot alter the value returned from your module, and change that value from NODE_ACCESS_DENY to NODE_ACCESS_ALLOW or NODE_ACCESS_NEUTRAL


Add rel = "dofollow" to internal links I wanted to add rel = "dofollow" to all internal links only like menu links, title links, user links etc. I managed to add rel = "nofollow" to comments and user posted contents. But I am not able to add rel = "dofollow" attribute to internal links.

Any suggestions how can I do this?

-- Thanks

What some people call a "dofollow" link is just a normal link - i.e. a link that is not tagget with the rel="nofollow" attribute.

In other words, this what a dofollow internal link looks like:

target

There is no dofollow (or similar) attribute you can add to the link.  The absence of nofollow is what you're looking for.


How to theme only top level menu? I have the following menus

about us
    company
    menu 2
our work
    menu 1
    menu 2
news
contact
jobs

I like to insert an extra li between each top level menus (about us, our work, news, contact, jobs) to make them look like "about us   |   our work   |   news   | contact   |   jobs "

I looked at template.php and I have themename_menu_link, but I don't know how to compare the variable to check if it is a top level menu or not.

The only way I can think of is as follows:

template.php

<?php

function YOURTHEME_menu_tree__YOURMENUNAME(&$variables) {
    global $cur_level;
    $cur_level++;
    return '
' . $variables['tree'] . '
';
}

?>

page.tpl.php

<?php print render(menu_tree('YOURMENUNAME')) ?>

This will give each level an unique class for it's level. Though, there is one big problem with this approach, and that is that menu_tree is working from the bottom up. So you will end up in the following level classes:

ul .level-3
li
li
    ul .level-2
    li
    li
        ul .level-1
        li
    li
li

So, you can never actually be sure about which classname the top level will have, only if you know for sure that there will always be an X count of levels.

Edit
So, just to be clear about my solution here above, this is the only way I can think of doing this programatically at theme level. If you could use a module like Nice Menu's (like suggested above) you should really be using that, since this is more a kind of workaround than a real solution to Drupal's sturdy menu system...


Can I use hooks in a template for views? I'm still not sure how hooks work.

I want to join a table to one of my views, but I have no idea where I'm supposed to put the hook for that. Do I just stick it in the template for the view? Or where does it go?

The API reference at http://drupalcontrib.org/api/drupal has all of the Views hook in it: http://drupalcontrib.org/api/drupal/contributions--views--docs--docs.php/group/views_hooks/6

That said, the views documentation is a little sparse.  The best thing to do is look through the list of hooks, then search on the various hook names for examples.

I suspect you need to use hook_views_query_alter but I don't think I have ever had to add a JOIN to a view before.

EDIT:

Notice another of your questions: Join a custom table on a View.

In your case, if you want to properly make a custom table Views aware, implementing hook_views_data is the correct solution.  But you still need to do this in a custom module, and not in your theme files.


How can I configure the search engine to search by dates? Drupal 7 I am new using drupal and I am creating a website for renting various items. I need the searcher to give me as a result the available articles between 2 dates, that is, the user searches for items that are available between 2 dates, for example, I am looking for an amplifier that is available between September 11th and Augus 2th.

Please help me. Thanks.

You have not mentioned is it drupal 7 or 8
If it is drupal 7 i think it will help you.
First you install  date module. You can add a date field with a start and an end date. Other than that the rest is simple. Go to your view and add two filters.

First filter will be your start date where the field is "less than or equal to" -> "now" you can write that only if you select "enter a relative date"

Second filter as you may have guessed will be your expire date field where the field is "is greater than or equal to" -> "now"

If "less than or equal to" and "greater than or equal to" don't appear as options, make sure you've enabled the Date Views module. (It is installed as part of the Date project.)


How do I use drupal_mail() without the $to value? I'm trying to send same email to several users at once. They should not see each other's email addresses, so I add them as Bcc in the header.

However, the problem is that Drupal seems to require the $to parameter passed to drupal_mail() function. I tried passing both NULL and an empty string but without success. System would return the Unable to send e-mail. message.

I don't want to use some random email address instead and I want to avoid new modules.

How can I send an email just with BCC recipients?

You do this by putting the string 'undisclosed-recipients:;' (notice the colon and semicolon at the end) is the $to parameter you pass to the drupal_mail function. E.g.:

drupal_mail('mymodule', 'send', 'undisclosed-recipients:;', $language, $params);

You can now add the list of bcc-recipients to the header.


What's the usual practice for providing several CMS-editable content in pages, particularly the home page? I need to create a home page with several content areas containing text and images (e.g. welcome text, welcome image on a different section of the same page, a second welcome text on a different section of the same page, a third text content area, etc). All of these, of course, is in the same page as some other regions and blocks.

My googling led me to these options:

Create a content type for each of those content. I think this option is a bit overkill since the content type will only be used for one instance of the content type. Doing this will also require creating a block specifying the particular instance of the content type.
Create a system settings page using hook_admin a make each of the content sections a system variable. This also sounds incorrect since those content aren't really system variables. This method also isn't applicable since there is no sense of authorship and doesn't work with the workflow modules.

So what's the usual practice for doing this?

You can try to use Views and make little blocks of content type flagged to the front page if you want.

Another options is Panels or Panelizer and using custom content in Panelizer to layout your frontpage however you want.

Or if you're really brave hook_page_build.

I've used your 2nd option on sites; if Workflows is an issue for you, you will want to try either Views or Panelizer as those tools play more friendly with workflows (it's all about the UX and how much you want to empower your site maintainers).