Node translation vs. Entity (field) translation I would like to know what you guys recommend for a multilanguage site. For example, consider the following case: A page and its content should be available in 3 languages (e.g. German, English, and Spanish); the site uses one profile type, several content types and views, taxonomy, taxonomy-references, node references, user and field references, field collections, menues and so on. All of this informations should be translatable.

As far as I know, there are two ways to obtain this: with Entity Translation and the "node-based" method, or the usual one with the Internationalization modules and l10n.

What way should I choose? In which case and why should I consider a method instead of the other?

Randy Fay recently created a post discussing the possibilities achieved with of Entity Translations, where Gabor Hojtsy commented on some of the considerations to weigh:

  Some good things offered by [good old] node translation include support for separate node commenting (eg. your German and English comments will not be intermixed); support for per language revisions; publication workflows (eg. the German node can be in a pre-publication revision workflow while the English is already published, coordinated actions can publish multiple language versions when all reach a certain step in the workflow, etc); different permission handling (eg. certain people can only edit German translations not English originals), thanks to Drupal's excessive node access system, etc. Think about menus. Most sites do not plan to have 1-1 menu structures for all translated versions.

The major caveat as I see it for Content/Entity/field-level Translation right now boils down to that age old Drupalism special case: the node title... Its not really a field, so its not translatable without another module, and potentially some patch work.  As of right now, I think field translation is still very much "experimental" ground, but more power to you for pushing forward into new territory.


Use Views for Search You can use Views for search results by using "Search Keywords" as a Contextual Filter.

This works fine when you search using a single word. But when entering multiple words with spaces, you don't get the correct results (usually no results).

Any idea how to solve this huge problem?

I was looking for an answer for hours... I thought I made a mistake, but it seems there is a bug in the Views module! I guess I'm not the only one with this problem, so I'd like to share the sollution I finally found.

Make a custom module and add these lines of code:

function mymodulename_views_query_alter(&$view, &$query) {
  // Fix bug where multiple terms in search index filter returns no results
  if (isset($query->relationships['search_total'])
      && !empty($query->fields['score'])
      && empty($query->fields['score']['table'])) {
    $query->fields['score']['table'] = 'search_total';
  }
}

The sollution was found here: https://drupal.org/node/1948510


How to group multiple blocks into one big block I have a website with Drupal 7 and the customer just asked to make it "responsive design".

I need, for the design to respond correctly, to group some blocks I already have into some bigger blocks, on which i can apply the specific classes I need.

Region aren't valid for me because the website is already built and it would be really messy to change it just to add regions.

Any ideas?

Thanks

Block Group module may help you

  This module extends the standard drupal block system with block
  groups. Each block group provides a new block as well as a
  corresponding region. Child blocks can be moved into any group region.
  The position and the settings of the parent block are propagated to
  its children. Also block groups are nestable.

Take a look. I am not sure how it will integrate with responsive style.


'Userpoints Transactions: Description' doesn't appear in Views I am building a site using Drupal 7 and the User Points module.

I have an original user points page. There I have table with the column "reason".

The HTML code for the "Reason" field (same as description?):

Commented on New Question f...

But, I tried to create a new table for transactions in Views.
For some reason, the "Userpoints Transactions: Description" is not showing in views.

Below you can see that the "description" column is empty:

This is the HTML code I see in the view:

Description:

why the "Userpoints Transactions: Description" does not shows up
through views?

There is no 'Reason' field: it is named 'Description'. When you're creating a new 'Userpoints Transaction' view, you can simply add a 'Userpoints Transactions: Description' field and everything should work out fine.

Edit: I've imported your view and everything works fine on my website. Try reinstalling the User Points and the Views modules and clear caches. Hopefully that solves your problem.


Node creation button/ link I'm new to Drupal 8.

I need to let users to create new node of some content type by pressing a button or custom link. In Drupal 7 I could achieve this by Rules and Rules link modules but I can't figure out how to do it in D8.

Let's assume I have a content type where all fields have default values and I want to create new node of this content type just by pressing a custom button.

How can I get this working in D8? Any tips?

Add a link for the route node.add in Twig:

{{ 'Add content of type "Basic Page"'|t }}


Get the current range values from a QueryAlterableInterface As far as I can see this isn't possible outside of QueryAlterableInterface, because the $this->$range variable is protected, and the range() method can only be used as a setter.

I suppose I could implement my own class that extends QueryAlterableInterface and adds in a method to expose the protected field... but I would have no idea how to get Drupal 7 to use the new class instead of its core one. Not to mention this would be quite over-kill.

Any better ideas?

Context

I am attempting an external (i.e. outside of hacking the Reference module) general code fix for something similar to the following issue:

References module doesn't specify/read a pager limit when field is using a view to generate potential references

I have come across another instance where this is causing my site a problem, but I can't apply the specific fix found in the Q/A above. Mainly because the code takes a different route through the References module. Rather than my field using a view to generate its "potential" reference values — as in the previous Q/A, which makes it quite identifiable — it is instead just a field that relies on a direct query to source its values. This direct query still has the same problem of attempting to list far too many values, to the point of timing out.

My plan is to detect the particular query involved, and see if it has no limit applied, and then set a safe limit — so that the views UI doesn't attempt (and fail) to generate thousands and thousands of checkboxes. I can probably find a way to detect the specific query, but I don't think I can tell if a limit is set or not.

function hook_query_alter(QueryAlterableInterface $query) {
  if ( $query->getMetaData(...) == ...) {
    $query->limit(); /// this does not return the limit value.
    $query->limit; /// triggers an protected access error.
  }
}

A different way to find this question

I realised that with the way I've posed this question, only those who know the underlying cause will be able to find a possible solution. So just as an aid to those who might searching for this specific problem — as it is easy to reproduce if you have a good sized database — here are some key search terms.

Unable to add a filter to a View for a Reference field

When attempting to add a Reference field as a filter for a View, using the Views UI, the Ajax request seems to hang. After max execution time triggers the following error:

An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /admin/structure/views/ajax/config-item/related_nodes/default/filter/field_node_related_nid
StatusText: parsererror
ResponseText: Fatal error: Maximum execution time of 60 seconds exceeded in /var/www/drupal/includes/common.inc on line 6642

Luckily (or thankfully) the Reference module adds some rather useful information as meta data to the query in question. Making it easy to spot in terms of its id (although you have to watch out that the id is prefixed with a whitespace character). This is the same id for all similarly made queries. It also records the $options array, which means we have a reference to the ['limit'] value without going through the $query object.

I've set the following to work for any field, but have left reference to the $field in use just in case it is useful for others. For my purposes 300 rows is a suitable default to have, rather than just accepting an infinite number or records.

Whilst this doesn't access the limit/range value from the query itself, it does solve the problem in quite a general way.

/**
 * Implements hook_query_alter().
 */
function HOOK_query_alter(QueryAlterableInterface $query) {
  /// trim due to typo in references module (took me a while to spot this)
  $id = trim((string) $query->getMetaData('id'));
  if ( $id === '_node_reference_potential_references_standard' ) {
    $field = $query->getMetaData('field');
    $options = $query->getMetaData('options');
    if ( !empty($options) && (empty($options['limit']) || !$options['limit']) ) {
      drupal_set_message('Modifying Node References query to ' .
        'protect against too many values (limited to 300 values)');
      $query->range(0, 300);
    }
  }
}


Display distance Coordinate vs Zip Code? I am trying display Coordinate vs Zip distance. User inputs zip they get a list of things close. Trying to work with Openlayers and expand on this post.
Need a simple Google Maps solution; lost in the labyrinth of modules

This tutorial helped me when i set my first proximity search.

It goes through eveything you need, and once done, is easily configurable.


Filtering a View that is output as a Block I have a view which has a page display and a block display. The block display has Use Ajax enabled so the filters show up. When I output the block display to my template using:

<?php print views_embed_view('list_disciplines', 'block_1'); ?>

It outputs correctly, and shows the filters. The problem is when I submit the filters form it redirects me to the path I have set up for the page display, and doesn't use ajax at all.

Any ideas?

Ok finally dug up my answer.

http://drupal.org/node/386388

In summary, the scripts for ajax views cannot be added if you embed your view in a page template. You either have to create the view in preprocess_page or in a node template file.


Drupal Commerce Payment Module I am creating a Drupal commerce Payment module and planning to sell it through codecanyon. Is there any licencing issues if I proceed with this?

Any module you distribute must be licensed under the GPL 2.0 or later. You are free to put it up for sale so long as anyone who buys it enjoys the same rights of redistribution - that's just the nature of Drupal's license overall. Anyone who buys your module will be free to put it up on drupal.org and redistribute it at will.


Different price for role My question is similar to others, but not exactly the same. All the other answers have a specific discount (%) amount for Members, but my client needs to be able to set a totally different, specific price for each of their art classes for members, that is, there is no specific rule that applies to all classes equally. So, I created a Member Price field to hold each unique reduced price, but I'm not sure which action in the dropdown would switch out the base price for the price in that field.

It was a strange flow of events, but the question was relevant to Ubercart, which I was wrong not to mention in the original post. It took doing research for a Drupal Commerce install to find the path to the answer for Ubercart!

The answer was the Price per Role module. Part of the project requirements were that the "member" viewer should be able to see the original price. As a workaround, we actually had to set up a special fields so that both prices could show! Yes, this could have been done with coding, but the client doesn't have a budget for coding.


How do I programmatically populate longitude and latitude fields when Geolocation used in content type I am using the Geolocation module and I have created a custom content type (we'll call it Bookshop), which contains a field called location and is of type Geolocation.

I can already programmatically create the custom content type instance and programmatically populate the title field.

    $node=Node::create(
      'title'=>'Shop 1'
    );

    $node->save();

How would I go about populating the the Geolocation field content (e.g. the longitude and latitude fields in the Geolocation field)?  e.g.

    $node=Node::create(
      'title'=>'Shop 1'
      'Geolocation field'=>array ('latitude'=>'1', 'longitude'=>'2.33'),
    );

An approach such as the one above does not appear to work?

Pretty straight forward just had to change the field names to correspond with the field names used by Geolocation:

$node=Node::create(
  'type' => 'content type - machine name',
  'title' => 'Shop 1',
  'geolocation_field' => ['lat'=> 1, 'lng' => 2.33]
);
$node->save();


add new menu items after existing items When I create a page and add a menu link, it appears above the existing menu items (in the menu tree). Can this be changed so that new items flow under existing items?

Yes, it's possible. You have to change the "Weight". If you put a weight greater than the other menu links, the last will appear below.


How do I add the "onload" attribute to a script tag? I need to add the onload event in jquery script tag as advagg does. I have done a bit of research, and I found that they are actually invoking hook_element_info_alter() and thereby add their hook_advagg_modify_js_pre_render() implementation into it. Then, they alter the child elements.

When I do the same in a hook_element_info_alter() implementation, type['script'] is not there.

Am I missing something?

If you want to make sure you're javascript is loaded in the header:

For drupal 7

/sites/default/themes/yourtheme/template.php

function theme_preprocess_html(&$var) {
      $path = $GLOBALS['base_url'] . '/' . path_to_theme() . '/js/yourscript-min.js';
      $script = array(
        '#tag' => 'script',
        '#attributes' => array(
            'type' => 'text/javascript',
            'src' => $path
        ),
        '#value' => '',
       );
       drupal_add_html_head($script, 'script');
    }

or if you want it loaded in the page:

function theme_preprocess_html(&$var) {
      $script = array(
        '#tag' => 'script',
        '#attributes' => array('type' => 'text/javascript'),
        '#value' => 'Add your javascript here',
       );
       drupal_add_html_head($script, 'script');
    }

For drupal 8

In the yourtheme.libraries.yml you need to create a library like so:

yourtheme.libraries.yml

library-name:
  header: true
  js:
    js/yourSrctipForTheHeader.js: {}

Also in the theme.info.yml you need to add this library, then it will automatically comes in head tag and will be available before the page load, if you remove header:true the script will be loaded after the page load.

theme.info.yml

libraries:
  - yourtheme/library-name

Alternativly, you can make use of this module:
https://www.drupal.org/project/header_and_footer_scripts and put the scipts in manually in the position that you want. But to be honest, i think the first solution is the more elegant way.


Commerce Product Display or just Views Display of line items? I will be presenting the products in one view and don't need the display nodes as they wont be seen.

Do I have to create display nodes for each product or can I just use views to display the line items in a table for example?

Is there any catch with doing this?

You can't see products because the permission to see products is disabled by default.
Just enable it at /admin/people/permissions. E.g. enable View any product of any type if you want to permit users to see directly entities.

But also have a look at the module Inline entity form. you can edit both node display and attached product entities in one form.


Where to place drush in MAMP I placed drush in MAMP folder outside of htdocs folder and downloaded drupal successfully but obviously to wrong folder. Where should drush be placed to have it work with drupal folder in htdocs folder?

I use the drush qd command and add the --root parameter. You can use it to download the Drupal installation into /Applications/MAMP/htdocs


Executing a Python script from Drupal I'm trying to execute a python script from Drupal using this:

exec('/usr/bin/python name_of_the_script.py')

But it does not work. Although, if I'm on the php console (php -a), then it works fine.

The name_of_the_script.py file has all the permissions.

I thought maybe it was the python command that didn't have all the permissions.

So I checked it with this command:

which python
ls -lisa /usr/bin/python

  694 0 lrwxrwxrwx 1 root root 9 2011-03-09 18:41 /usr/bin/python -> python2.6

Similarly I also used this command:

ls -lisa /usr/bin/python2.6

  369 2240 -rwxr-xr-x 1 root root 2288240 2010-04-16 10:06 /usr/bin/python2.6

It seems everything is OK.

Do you have any suggestions?

Adding 2>&1

exec('/usr/bin/python script.py 2>&1');

Pointed me to the right direction.

I was writting in a file ( inside the script that hadn't enough permissions )

chmod 666 name_of_the_file.txt totally solved the issue!

Thanks!


icon_map in PHP annotation instead of layouts.yml I need to add an Icon to a layout added by a contrib module. But I see it is adding the layout via plugin PHP file instead of layouts.yml.
The annotation looks like following
/**
 * A very advanced custom layout.
 *
 * @Layout(
 *   id = "lb_tabs_tabs",
 *   label = @Translation("Tabs"),
 *   category = @Translation("Effects"),
 *   path = "layouts/tabs",
 *   template = "lb-tabs-tabs",
 *   icon_map = ""
 * )
 */

I don't know how to represent the multidimensional array into this annotation form. When I tried simple [['region', 'region']] form it errored [Syntax Error] Expected PlainValue, got  '[' .
tried @Array(@Array('region', 'region')) as well but got
Syntax Error] Expected Doctrine\Common\Annotations\DocLexer::T_CLOSE_PARENTHESIS, got '(' .
What is the correct way to add an icon_map there?
Also tried adding layouts.yml and moving these values to yml and the layout option just disappeared as a whole`.

You can do this via the layout alter hook ( hook_layout_alter(&$definitions) ).  The definitions variable is an array of all the defined layouts keyed by the layout machine name.
The value here is a Drupal\Core\Layout\LayoutDefinition object.  This has a setIconMap method.  You can pass this an array of arrays that define the icon.
E.g. if the yml format is:
- [top]
- [first, second]
- [bottom]

the value is something like:
$map = [
  ['top'],
  ['first', 'second'],
  ['bottom']
]


How to mark calendar days between two dates? I added two cck for start date and end date. I want to mark the dates on calendar.

If I select the start date and end date in single field by enabling requires to date option it works fine.

But I have a different date field for end date.How to do it?

I did this with the same date field and enabled the to date option.


Determining content access by role for viewing content? Here is the scenario:

I have 10 roles (plus the 3 core roles, anon, auth, administrator).
I have 7 roles imported from an outside system.
Users can belong to multiple roles.
Editors need to be able to check off in a list of these roles when editing content, as to whom can view the content.
If none are selected, anyone can view.
A user only needs to possess one of the roles checked off in order to have access.

There does not seem to be a solid solution for Drupal 8 out there. Content Access is unfinished, Permissions by Term is too restrictive, and Access by Entity currently does not work.

What is the path of least resistance to enabling view based access if the options are enabled? Where can I start?

To further complete the list of content access modules you mentioned, i.e.:

  There does not seem to be a solid solution for Drupal 8 out there. Content Access is unfinished, Permissions by Term is too restrictive, and Access by Entity currently does not work.

I recommend you have a look at the Group module, which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections.

Group creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it. Groups can also act as a parent of any type of entity. Group provides an extensive API to attach entities to groups.

Sample configuration

Below is an example of a possible configuration, which may help to get you started with possible configurations (using the Group module):

Group type ID ! Group type ! Group role ID ! Role
--------------+------------+---------------+------------
 1            ! Class      ! 3             ! Instructor
 1            ! Class      ! 4             ! Student
 2            ! Customers  ! 5             ! Lead
 2            ! Customers  ! 6             ! Prospect
 2            ! Customers  ! 7             ! Licensed Customer
 2            ! Customers  ! 8             ! Sales
 2            ! Customers  ! 9             ! Support
 2            ! Customers  ! 10            ! Accounting
 2            ! Customers  ! 11            ! R&D
 3            ! Project    ! 12            ! Project Manager
 3            ! Project    ! 13            ! Developer
 3            ! Project    ! 14            ! Customer

Group Types

The above example consists of 3 group types:

Class.
Customers.
Project.

Group Roles

For each of the 3 group types, there are specific Roles defined, some more details about some of them:

for the Class group, these are the 2 roles that are configured:

Instructor.
Student.

for the Project group, these are the 3 roles that are configured:

Project Manager.
Developer.
Customer.

These are the Group Specific Roles: these roles can be configured per group type and will only be available on groups of that group type. As an example, for group type "Class", the defined roles are Instructor and Student (which are not available for the other group types).

On top of the group specific roles, there are also Special Global Roles: These are the special (hardcoded) roles named Outsider (= a signed in user that did not join a group) and Member  (= a signed in user that did join a group). These cannot be defined by the Drupal administrator, and they are always available for any group. These roles can have different permissions sets for each group type. Special case: the role Anonymous is related to a user that is not signed.

Groups

Each of the configured group types can have any number of Groups.

Examples of groups:

for the Class group type, there could be these Groups:

Getting started with Drupal.
Drupal for site builders.
Become an expert in using the Rules module.

for the Customers group type, there could be these Groups:

Service Requests.
Order Processing.
Sales Orders.
Relationship Management.

Permissions

For each of the configured group types, you can then also configure for each Content Type which Role has what kind of access (= none, view, create, edit, delete). Be aware: even though this looks similar to Drupal's permission configuration, these permissions are not the same permissions (they are specific to the Group module).

Module integrations

The Group module integrates with various other (popular) modules, such as Views, Rules, etc. These integrations are more or less out-of-the box (not dozens of extra modules needed to make those integrations work). Simply because everything is entity based.

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".
Podcast "Using the Group module as an Alternative to Organic Groups in Drupal 7 and 8".

PS: this answer applies to either D7 or D8.


How can I create a simple non-CRUD resource action with Drupal 7 / Services 3? The resource "username" appears but my action does not appear in the list in services admin. Response to a POST is HTTP/1.1 404 Not found: Could not find resource username.

I replaced my module name with "module" here:

function module_services_resources() {
  return array(
    'username' => array(
      'check' => array(
        'help' => 'Checks username for uniqueness',
//       'file' => array('file' => 'inc', 'module' => 'noteresource'),
       'callback' => '_module_username_check',
       'access callback' => '_module_resource_access',
        'access arguments' => array('view'),
        'access arguments append' => TRUE,
        'args' => array(
          array(
            'name' => 'username',
            'type' => 'string',
            'description' => 'The username to check',
            'source' => 'data',
            'optional' => FALSE,
          ),
        ),
      )
    )
  );
}

function _module_resource_access($op, $args) {
  return TRUE;
}

function _module_username_check($data) {

  $username = $data->username;

  $user = db_fetch_object(db_query("SELECT uid FROM users WHERE name=':username'", array(":username" => $username)));

  return $user;
}

Actions outside the normal CRUD roster must be wrapped in an array under the key 'actions'

function module_services_resources() {
  return array(
    'actions' => array(
      'username' => array(
...


EntityReferenceSelection plugin ignored I am trying to create a simple time tracking app and for this purpose, I need an entity reference field with some additional filtering of referenced entities (only active projects can be selected).

I read some guides and it seems that what I need is to

1. create entity reference field

This is done in the buildForm() function of the src/Form/TimesheetForm.php class like this:

    $form['project'] = [
  '#type' => 'entity_autocomplete',
  '#title' => $this->t('Project'),
  '#weight' => '0',
  '#target_type' => 'project_entity',
  '#selection_handler' => 'default:active_projects',
  '#selection_settings' => [

  ],
  '#tags' => FALSE,
];

2. create custom plugin

This is done in src/Plugin/ActiveProjectsSelection.php like this:

    <?php

    namespace Drupal\timesheet\Plugin\EntityReferenceSelection;

use Drupal\node\Plugin\EntityReferenceSelection\NodeSelection;

/**
 * Provides specific access control for the node entity type.
 *
 * @EntityReferenceSelection(
 *   id = "active_projects",
 *   label = @Translation("Active projects selection"),
 *   entity_types = {"project_entity"},
 *   group = "default",
 *   weight = 3
 * )
 */

class ActiveProjectsSelection extends NodeSelection {

  /**
   * @param null $match
   * @param string $match_operator
   *
   * @return \Drupal\Core\Entity\Query\QueryInterface
   */
  protected function buildEntityQuery($match = NULL, $match_operator = 'CONTAINS') {
    \Drupal::logger('timesheet')->debug('buildEntityQuery');
    $query = parent::buildEntityQuery($match, $match_operator);
    //$query->condition('project_start_date', time(), '<');
    //$query->condition('project_end_date', time(), '>');
    return $query;
  }

}

However, even when I commented out all the logic, the autocomplete does not work. When I type in the field, no autocomplete popup appears. Not even the debug message is logged when I try to trigger the autocomplete.

I have also tried to extend DefaultSelection instead of the NodeSelection as I am using a custom entity which is not a node, but the result was the same.

It looks like my plugin is not even reached, but I do not know why.

I cleared the cache, my local site is in dev mode.

So, with help from Clive (see his comment below the original question) I have identified two issues:

The correct path for the ActiveProjectsSelection.php file should be src/Plugin/EntityReferenceSelection/ActiveProjectsSelection.php.
The id of the plugin in the annotation should be default:active_projects.
(not related to the original problem) The correct timestamp for the date comparison is DrupalDateTime::createFromTimestamp(time()).

With these changes, my code works perfectly. Also, it does not matter whether I extend NodeSelection or DefaultSelection, it works with either of them.


Existing site drops me back into the install routine Existing site drops me back into the install routine and when I succumb and try to go through the install, it tells me:

I need to create a sites/default/settings file when it already exists; even when I delete that and create a new one, I get the same error message
Similarly, it says I need to create a sites/default/files directory, even when it already exists; when I try to delete the old one and start over I get a bunch of denials and when I try to change the properties, I get a bunch of messages telling me I can't do that.

Do I have to scrap the whole site and start over? Hopefully I can keep the Drupal DB which has some newly-created content pages.

And while we are at it, when I set the properties for a file or folder, is Drupal considered the Owner, Group, or Other?

This seems like a permissions problem. If you are in Linux, use the "chmod" command to set the correct permissions for settings.phpYou may need to have superuser privileges to do this so see your site admin.

Often, the web-server runs as user "www-data" with group "www-data" so you may need to use the "chown" command (once again with superuser privileges) to change its ownership first.

Example:

# sudo chown www-data:www-data settings.php

# sudo chmod 444 settings.php

You will have to adjust the permissions again before editing this file in the future.


How to create a views filter for users who have never accessed a site? I have a view where I am trying to show all users who have a last access value of never, meaning they have never logged in.

The filter however expects a Date value which is no help to me because I just need to filter by users who have never accessed.

Does anyone know a way around this?

You can achieve this using following simple steps:

Add filter criteria User: Last access or User: Last login is equal to 1970-01-01

You could see the users.access = 0 in query

  Note: Drupal uses Unix time. The unix time stamp is a way to track
  time as a running total of seconds. This count starts at the Unix
  Epoch on January 1st, 1970 at UTC. Therefore, the unix time stamp is
  merely the number of seconds between a particular date and the Unix
  Epoch.


One time Editing Of Profile page I am using drupal 7 with profile2 module, Created a profile type which is not filled up by user at registration time. after a user register they have a option to fill up the page . I need a way to restrict user from editing that custom profile page only if they have already submitted the information. Does anyone know how to accomplish this ?

thanks

You can use Field Permissions for this.

  The Field Permissions module allows site administrators to set
  field-level permissions to edit, view and create fields on any entity.

Just set up the fields on the Profile page so that only authenticated users can fill them in.  This will mean that when the anonymous user is registering they won't see the fields, however when they are registered (and therefore authenticated) they can edit them.


How do I change submit URL for exposed search filter? I've created view using Search API Views with two different displays.
First Page display (by_terms) and with the following options:

Page settings: Path:/taxonomy/term/%
Contextual filters: Category: Term ID (indexed)
Filter criteria: Search: Fulltext search (exposed)

And second Content pane display (panel_pane):

Use Panel path: Yes
Filter criteria: Search: Fulltext search (exposed)
Link display: Custom URL set to search/results

When I open page with 1st display /category/list/name (which is alias to /taxonomy/term/123) and submit Search input, it goes to /category/list/name?keywords=test.
When I open page with 2nd display (/search/results) and submit Search input, it goes to /taxonomy/term/%2A?keywords=test which is weird.
Ideally I would like the submit to end up in both cases at /search/results?keywords=test.

Is there any way of controlling the submit URL of the landing page for exposed filter? How?

Seems that specific problem is with Panels.

The exposed form is basically a block which have no sense of context, therefore setting the URL from the view pane doesn't affect exposed filters in a block.

Therefore one way to go is to use hook_form_alter:

/**
 * Implements hook_form_alter().
 */
function foo_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $form['#action'] = current_path();
  }
}

Or:

/**
 * Implements hook_form_views_exposed_form_alter().
 */
function foo_form_views_exposed_form_alter(&$form, &$form_state) {
  if ($form['#id'] == 'views-exposed-form-foo-default') { // Or: if ($form['#action'] === '/foo')
    $form['#action'] = '/bar';
  }
}

Or by extending Views handler, for example:

class foo_handler extends views_handler_field {

  /**
   * Add to and alter the form.
   */
  function views_form(&$form, &$form_state) {

    // Submit to the current page if not a page display.
    if ($this->view->display_handler->plugin_name != 'page') {
      $form['#action'] = current_path();
    }
  }

}

Alternatively content pane can be used which can override the path, instead of using exposed form. See this issue for more details.


Display child terms of taxonomy term When displaying a taxonomy term, how can I also display the teasers of all the child terms of the current term?  I still want to display all the content and fields of the current node, but also display the child teasers.

The taxonomy display won't do this on its own. You could create a view to do this, then display the view below the term page.

If you call the view from a taxonomy term template you could use a "Contextual filter" to pass the term id (tid).


Get order of a content type's fields When I manage fields in content type edition I can put them in order. How could I retrieve this information to use it in a custom module. In Database there is no any column which saves weight order information of fields as they appears in "Manage fields" tab in content type edition.

Use field_info_instance()
  $entity_type = 'node';
  $field_name = 'body';
  $bundle_name = 'article';
  $body = field_info_instance($entity_type, $field_name, $bundle_name);

Which gives you access to numerous config/settings

  $body_weight = $body['display']['default']['weight'];


Custom page with user selected nodes I want to allow my users to print a pdf with the nodes they want.
I thought to create a view and use the Print module to generate the pdf, but I don't know how to let them choose the nodes.
I tried with Panels, but it's a bit complicated for standard user.
I thought to use some cck field to manage this, but since the custom page is per user, this is not possible.
Did anybody face the same problem?

You can use the Flag module to allow users to select nodes. Flag integrates nicely with Views, so you can create a view of nodes flagged by the current user.


When is it appropriate to create an entity instead of a new content type? What is the benefit to creating new entity types over just building a new content type?

It seems a bit overkill to do all of the custom coding that is required to create a new entity when you have all of the CRUD and Views functionality already built into content types.

It's not so much about what the benefits are but more about what's appropriate for a particular situation like you've said. You can represent pretty much anything with a node and for 99% of situations (as I've found at least) you won't need to implement custom entity types.

I always think of the taxonomy_term entity type as a good example of why not everything should be a node/content type:

A taxonomy term is essentially for grouping together different entities and as such doesn't require the same functionality as a node. While you could theoretically use a content type to perform this functionality (with perhaps a node reference field), a taxonomy term doesn't need to do the same thing as a node so it doesn't really make sense to do so. The same can be said for the user and taxonomy_vocabulary entity types.

So a taxonomy term is created as a separate entity and is programmed to do only what it needs to, while still getting the benefits of being able to have fields attached, etc.

I think the simple answer is that when a node/content type doesn't do what you need it to, or it's just a massive amount of overkill/overhead for very little benefit, then you should choose to write a custom entity.

This is only based on my personal experience; I'd be interested to hear what someone directly involved with Drupal core development had to say about this.


Setting a standard value to a field I've created a field with drupal console. That made the following standard folder structure.

FieldFormatter
FieldType
Fieldwidget

These all have their respected php classes.

Now this field is in a content type that always is used in a Book.
I want to this Books name into that field.
I know how to retrieve this name trough code but i don't know how to get this value into this field in all new instances of this content type.

I thought i just needed to use a default value but that doesn't seem to work because even though i added 'default' to the schema with that value it doesn't show up?

Normally a default value is configured in the field configuration. Either static in default_value or dynamic in default_value_callback pointing to a callback function which returns the default value.

For your original question, how to do this in one of the field plugins, see No way for a field to dynamically set default value and especially #6:

  I resorted to creating widgets (extending the base widgets), whose
  only concern is to set the default value dynamically according to
  contextual values, e.g. I have a widget that presets a default value
  to an entity name referenced by the logged in user, something like
  this:

/**
 * Define the {@link AcmeWidget} class.
 *
 * @FieldWidget(
 *   id = "acme_widget",
 *   label = @Translation("Acme Textfield"),
 *   field_types = {
 *     "string"
 *   }
 * )
 *
 * @package Drupal\acme\Plugin\Field\FieldWidget
 */
class AcmeWidget extends StringTextfieldWidget {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    // Call our parent but set the value using our default value function.
    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    // Get the current user organization's name.
    $user = User::load(\Drupal::currentUser()->id());
    $organization = $user->get('field_organization')->entity->title->value;

    // Set the default value if a value hasn't been set.
    $element['value']['#default_value'] = $organization;

    return $element;
  }

}


Content type menu links? I'm making a site that has three different content types.  I would like a Main-Menu link to each content type.  Additionally, I would like each of these three pages to list recent nodes for that content type, with a link to to that node.  I would think this is pretty standard.

So I've created the content types, and I can click directly to each content type, but I do not know what the "best practice" would be to create these pages.  I could create an override of node--mycontenttype.tpl.php but is this the right way to go?  How would I link to the general page (instead of the specific node)?

There are many ways to do this. A simple way would be to create a view for each content type and then create menu items for each of them.


Custom module block holding DB calls I am working on a project where I first was only designing the theme. However, I now need to create 5 already made custom pages or blocks in a page, which will be available as soon as theme is enabled.

Each page should hold its own code for grabbing information from external database. Now I am having a huge dilemma on deciding how to create those pages. Since there are DB calls made on each of them, I was suggested to create a custom module, which would display a block with the printed content from database. I tried creating "pvpstats.module" and "pvpstats.info" as normal for custom modules, and displaying it in sidebar_first. After I enable the module, nothing happens. The block is just not visible. I used the code below.

function pvpstats_block_info() {
  $blocks['pvpblock'] = array(
    'info' => t('Example Block'),
    'status' => TRUE,
    'region' => 'sidebar_first',
    'weight' => 0,
    'visibility' => 0,
    'pages' => 'admin*
coder*
node/add*
node/*/edit
node/*/devel
',
  );

  return $blocks;
}

/**
  * Implements hook_block_view().
  */
function pvpstats_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'pvpblock':
      $block['subject'] = t('Block Name');
      $block['content'] = theblock_contents();
      break;
  }

  return $block;
}

function theblock_contents() {
  return '
    $dbserver="serveradress";
    $dblogin="username";
    $dbpass="dbpassword";
    $dbname="databaseserver";

                mysql_connect($dbserver, $dblogin, $dbpass);
                mysql_select_db($dbname);
                mysql_query("SET NAMES 'utf8'");

                $vypis =  mysql_query("SELECT * FROM characters WHERE (accesslevel < '1') AND (pvpkills > '0') order by pvpkills desc LIMIT 20");
                echo '

Nick		Kills
';
         while($row = mysql_fetch_array($vypis))
                    {
                echo '
';
                echo $row["char_name"];
                echo '	&nbsp;&nbsp;	';
                echo $row["pvpkills"];
                echo '
';

                    }
    echo '
';
    ?>

The main point is that I need those blocks later included in my theme so that they are visible immediately after enabling the theme, if that is somehow possible.

In theblock_contents you are trying to return php code. Don't. Do not echo or print in it. If anything, build a string. It should look about like that:

/**
* custom html block
* @return string
*/
function theblock_contents() {
  $dbserver="serveradress";
  $dblogin="username";
  $dbpass="dbpassword";
  $dbname="databaseserver";

  $result = '';

  mysql_connect($dbserver, $dblogin, $dbpass);
                mysql_select_db($dbname);
                mysql_query("SET NAMES 'utf8'");

  $vypis =  mysql_query("SELECT * FROM characters WHERE (accesslevel < '1') AND (pvpkills > '0') order by pvpkills desc LIMIT 20");
  $result .= '

Nick		Kills
';
  while($row = mysql_fetch_array($vypis))
  {
    $result .= '
';
    $result .= $row["char_name"];
    $result .= '	&nbsp;&nbsp;	';
    $result .= $row["pvpkills"];
    $result .= '
';
  }
  $result .= '
';
  return $result;
}

It's worth to mention that your code was plainly invalid PHP, no matter if it was supposed to run in Drupal or not. You can't simply return PHP code as string and hope it'll be executed. Only the part about not using echo in hooks is really Drupal dependent.

Important note: if you want your modules to work stable, please don't use PHP SQL functions directly. Use db_select to obtain data. Connecting to multiple databases is pretty well documented too.


Add css-class based on productpages' top level taxonomy term So I have a website (created with drupal 7) where each product is linked to a taxonomyterms. This was done so that all products can easily be divided into several different categories.

So I have a taxonomy that looks somewhat like this:

Top level item 01

Level 2 item 01
Level 2 item 02
Level 2 item 03

Top level item 02

Level 2 item 04
Level 2 item 05
Level 2 item 06

Every 'top level' term (or categorie) has links that need to be in their own color.
For Example: The product that is linked to the term 'Top level item 01' and all linked subitems need to have 'red' links. While the product that is linked to the term 'Top level item 02' and all linked subitems need to have 'blue' links.

I was thinking of adding a css class somewhere in my theme so that I could do something like:

.red a { color: #f00; }

But I can't seem to find how I should do that. Can aynone help me with that?

Try something like this in your theme's template.php file (put it into MY_THEME_preprocess_page(&$variables) function):

if(arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $tid = arg(2);
    $term = taxonomy_term_load($tid);
    $parent = taxonomy_get_parents($term->tid);

    if(empty($parent)) {
      $variables['classes_array']['parent_cat_color'] = $term->name;
      // or $variables['classes_array']['parent_cat_color'] = 'parent_cat_color' .. it's up to you..
    }
  }

and open page.tpl.php and put $classes variable into your wrapper div..


Custom field "required" validation I built a custom field type using the Field API. In hook_field_validate I have some logic to validate some very custom stuff, but when I tried to add a "This field is required" validation, I realized this hook runs on the from that you fill when you're adding a field to an entity. Then, I implemented hook_field_is_empty, which I know runs when the entity saves. Problem is, even if the hook runs and the field is empty, no validation occurs (i.e. the user doesn't get the "this is required" message, and the form submits).

So, what's the right way to do a "this field is required" validation?

Probably a stupid question but have you tried using the #required setting when you created the field i.e.

'#type' =>
'textfield',
'#title' => t('Subject'),
'#default_value' => $node->title,
'#size' => 60,
'#maxlength' => 128,
'#required' => TRUE,

from Form API reference https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#required


How to turn off " " surrounding vars in the output of t()? In my module I display a menu inside a block using drupal_render(menu_tree('my-menu')).

In the output the variables printed with t() are surrounded by  .

Drafts (4)
Inbox (2)

How do I turn this off?

There is actually an excellent comment in the documentation for this. Pasting here for completeness

There are three styles of placeholders:

!variable, which indicates that the text should be inserted as-is. This is useful for inserting variables into things like e-mail.

$message = t("If you don't want to receive such e-mails, you can change your settings at !url.", array('!url' => l(t('My account'), "user/$account->uid")));

@variable, which indicates that the text should be run through check_plain, to escape HTML characters. Use this for any output that's displayed within a Drupal page.

$title = t("@name's blog", array('@name' => $account->name));

%variable, which indicates that the string should be HTML escaped and highlighted with theme_placeholder() which shows up by default as emphasized.

$message = t('%name-from sent %name-to an e-mail.', array('%name-from' => $user->name, '%name-to' => $account->name));


Posting to a form via external URL I am writing an application (non-Drupal) that is POSTing to a 3rd party public form written in Drupal. The problem I am running into is that the 3rd party form never processes the request, it only returns the original form. Is there a trick to posting to Drupal forms? The URL that I am attempting to post to is:

https://www.modelaircraft.org/membership/verify?ama_number=123&last_name=smith&op=Submit&form_id=membership_verify_form

The response should have the following fragment:

Error message

  No match found for AMA 123 and last name smith. Please verify.

But it does not.

There is no special trick to posting to Drupal Forms.
But, the way that form is set up, at least for validation errors, is ajax-based. Which means that you need to post to this URL instead:

https://www.modelaircraft.org/membership/verify?ajax_form=1&_wrapper_format=drupal_ajax

with the following parameters

_drupal_ajax    1
_triggering_element_name    op
_triggering_element_value   Submit
ajax_page_state[libraries]  classy/base,classy/messages,core/drupal.ajax,core/html5shiv,core/jquery.form,core/normalize,extlink/drupal.extlink,google_analytics/google_analytics,nt_ama/nt_ama,omega/omega,responsive_menu/responsive_menu.javascript,responsive_menu/responsive_menu.styling,system/base,tb_megamenu/theme.tb_megamenu
ajax_page_state[theme_token]
ajax_page_state[theme]  nt_ama
ama_number  123
form_build_id   form-pqXufm7ga3qhXz5_dpM6_AiGcgcExovHqBG6kkqcIIE
form_id membership_verify_form
last_name   smith

That should give you a json response, similar to this:

[{
    "command": "update_build_id",
    "old": "form-pqXufm7ga3qhXz5_dpM6_AiGcgcExovHqBG6kkqcIIE",
    "new": "form-_2pgVtOL0WW10yWGP8iS1o95GyJ5pMxo5M1Mk3Jy90c"
}, {
    "command": "insert",
    "method": "html",
    "selector": "#messages-wrapper",
    "data": "    \u003Cdiv role=\u0022contentinfo\u0022 aria-label=\u0022Error message\u0022 class=\u0022messages messages--error\u0022\u003E\n          \u003Cdiv role=\u0022alert\u0022\u003E\n                  \u003Ch2 class=\u0022visually-hidden\u0022\u003EError message\u003C\/h2\u003E\n                    No match found for AMA 123 and last name smith. Please verify.\n                \u003C\/div\u003E\n      \u003C\/div\u003E\n    ",
    "settings": null
}]

which contains the message you mention.

Good luck!


How do I hide Devel tab from users? I just noticed that Devel tabs are showing on my Basic Pages, even when the user is not logged in. Anonymous users should not see "View" and "Devel" tabs! I can't find a setting for this in the Devel configuration page. Any ideas how to prevent the tabs from displaying? Thanks!

Duh... It isn't the Devel config that controls it. It's the "Access developer information" permission. Someone had turned it on for anonymous users. Doh!


Commerce product variations switching I have setup a product which has multiple variations as the image shows:

My variations have a colour taxonomy which I'm trying to use for when a user wishes to switch between variations on the same product.

My problem is the product node is not presenting any option for selecting the list of available colour nor is there an add to cart form.

I'm sure I'm missing one or two things ... I could use a second opinion, please.

UPDATE:

I already had the "Enable this field to function as an attribute field on Add to Cart forms" selected but didn't work.

I noticed in step#2 of the answer you directed me to, the taxonomy field is created in a Variation entity type.
However, I don't see a Variation entity listed on my site.
I'm adding my colour taxonomy field into the product type entity as shown in the image below:

You need to enable the taxonomy field to be used as attributes so it is exposed to the cart form.

Here you've got the step by step guide here: https://drupalcommerce.org/commerce-kickstart-2/adding-taxonomy-field-product-attributes


additional Social icons in ShareThis module I am using ShareThis module for social icons. Can anybody please tell me how to add a new social icon not provided by this module? Flickr,Feed and Email icons are not present in the list.

You can do this by using Social Media Links Block module.

  The modules provides a configurable block that display links (icons)
  to your profiles on various popular networking sites.

For Flicker, use Flicker module.


How do I use Panels to replace a default node page? In my Drupal 7.8 installation, I have defined a custom content type "Reviews" which has several fields. Instead of displaying the normal Reviews page for every review, I want to display a panel layout with the fields stuck in different panel regions. I have absolutely no clue how to begin doing this, and I couldn't find any simple instructions.

I have Views, Panels, and CTools modules already installed.

Thanks!

I found using Views, panels and Ctools a complex and steep learning curve.  Two resources have been very helpful. 1. The video series from Nodeone.se has two video series that can help, "Taming the Beast' (views) and 'Learning Pagemaker'which includes panels. 2. The new book "Drupal's Building Blocks" by Earl and Lynette Miles (Merlinofchaos at drupal.org).


cant loop through array with ajax_command_html im beginner in drupal and i would like to ask why is this not looping , it just gives me first result

$string = $form_state['values']['search_block_form'];

  $query=db_select('node','n');
$query->join('field_data_body','b' , 'n.nid = b.entity_id');

$query
->fields('n',array('nid', 'title'))
->fields('b', array('entity_id', 'body_value'));

  $db_or = db_or();
  $db_or->condition('n.title', '%' . db_like($string) . '%', 'LIKE');
  $db_or->condition('b.body_value', '%' . db_like($string) . '%', 'LIKE');
  $query->condition($db_or);

  $result = $query->execute();

while ($row = $result->fetchAssoc()) {
      $node_title = $row['title'];
      $node_id = $row['nid'];
      $entity_id = $row['entity_id'];
      $body_text = $row['body_value'];

  $commands[] = ajax_command_html("#block-system-main", "<h1> $node_title </h1> <p> $body_text </p>"  );
  return array('#type' => 'ajax', '#commands' => $commands);

}

I want replace div with id block-system-main with found content

Try with this:

  $string = $form_state['values']['search_block_form'];

  $query = db_select('node', 'n');
  $query->join('field_data_body', 'b', 'n.nid = b.entity_id');

  $query
    ->fields('n', array('nid', 'title'))
    ->fields('b', array('entity_id', 'body_value'));

  $db_or = db_or();
  $db_or->condition('n.title', '%' . db_like($string) . '%', 'LIKE');
  $db_or->condition('b.body_value', '%' . db_like($string) . '%', 'LIKE');
  $query->condition($db_or);

  $results = $query
    ->execute()
    ->fetchAll(PDO::FETCH_ASSOC);

  $commands = [];

  foreach ($results as $result) {
    $node_title = $result['title'];
    $node_id = $result['nid'];
    $entity_id = $result['entity_id'];
    $body_text = $result['body_value'];
    $commands[] = ajax_command_html("#block-system-main", "
" . $node_title . "

" . $body_text . "
");
  }
  return array('#type' => 'ajax', '#commands' => $commands);


Recommended file permissions Similarly to what described in https://www.drupal.org/node/244924, which is for Drupal 7, is there any script to set the right permissions for Drupal 8?

How can we take care of the file permissions for contributed modules? For example, I know a few modules which would have different permissions for files like .htaccess and other private folders in the modules. Is there a way we can reset the file permissions to initial versions?

I've been running the same script included on that page for sites running either Drupal 7 or Drupal 8, with no adverse effects. I would recommend just using that.


Views Relationship/Contextual Filter for sibling nodes I have a content type 'property' and a content type 'park'. I'm using an Entity Reference field in the property to reference a park. The park is essentially a parent or neighborhood or that contains the property.

On the property page, I want to display the sibling properties (the ones that share a common park/parent). I'm able to show child properties on the park page, but can't for the life of me figure out the relationship/contextual filter combo to use to get this working. I see many examples online that use taxonomy, but this is an entity reference relationship. Setting up a relationship I have options for Entity Reference: Referenced Entity - A bridge to the Content entity that is referenced via field_master_park and Entity Reference: Referencing entity - A bridge to the Content entity that is referencing Content via field_master_park and I assume I use (at least) one of these combined with a contextual filter?

Anyone able to at least point me in the right direction?

There are two ways to do this that come to mind:

Option One

You could create a node template for nodes of type property and use an Entity Field Query in a manner roughly following this pseudo-code:

  $park = $node->field_park['value'];
  $query = new EntityFieldQuery();
  $query
     ->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'property')
    ->propertyCondition('status', 1)
    ->propertyOrderBy('created', 'DESC')
    ->fieldCondition('field_park', $park)
    ->range(0,10);
$result = $query->execute();

This will load a list the NIDs of all nodes that have field_park matching the value of $node->field_park['value'] (or wherever the node object stores your actual field value). To get more info than just the NID, you will want to do some kind of foreach($result) that does a node_load($nid) on each NID returned by the EFQ.

Option Two

Option two is no-code: you could create a View and embed it on your node with something like Insert View. You would create the view with the following steps:

Add a contextual filter that takes the node ID. This is so you can pass it a value so you get a view specific to each node you want it to appear on. Exactly how to do this is out of the scope of this question.
Add a field for the node title. You can remove this later but it will keep you from getting confused while making the view. Give it a label if you want, make it grouping field number one, and exclude it from the view.
Add a relationship. Choose "Entity Reference" for the relationship type, and then select "entity that is referenced via field_park" or whatever your node reference field is called.
Add another content: title field. Under relationship, choose the relationship you just created. Set it to group by that field, create a label called "park:", and set it to exclude from display.
Add another relationship. Choose type "Entity Reference" and this time choose "referencing entity": "entity that is referencing Content via field_park"
Add another field for node: title and this time select the relationship you just created. Give it a label like, "sister property:" if you want.

Violá. Now you have a view that will allow you to pass an NID and will tell you the title of that property, its park, and all sister properties.


How to hide share content option under profile type? There is an option "Share Content" under every profile type. It is being displayed to all users apart from admin. I just want to hide it. I searched for it enabling Devel module but did not get anything belongs to the option. Please share your answer if anybody knows how to do it?

Presumably this is a field, so under Profile2 you can change 'Manage Display' for all fields - set it hidden


Is it possible to set a single member of a complex-variable inside the variable table I want to use Drush vset to modify a subset of values stored in the 'variable' table's theme_themeName_settings record.

I've found references to vget and vset but all I've found so far is for the entire complex-variable.

Any help would be appreciated.

Drush does not support modifying elements inside a complex variable directly.  You could instead use php-eval to do this:

$ drush php-eval '$v = variable_get("theme_themeName_settings"); $v["key"] = "value"; variable_set("theme_themeName_settings", $v);'


Create a route for AJAX requests How should I implement a callback to a single Drupal class (in my case it's Transliteration). I don't need a full Drupal load/bootstrap, but one independent class.

The purpose of the AJAX code would be the following:

User inputs 'áéíóű'
The input is sent via AJAX
The Transliteration class changes the input to 'aeiou'
The result is returned to the client

I've found this related issue, but it would be nice to have a simple example (and documentation) for it.

How should I implement a callback to a single Drupal class (in my case it's Transliteration). I don't need a full Drupal load/bootstrap just one independent class.

Taken literally, within the confines of Drupal, I don't believe you can. We rely on PSR-0 for class loading, so at the very least you must bootstrap Drupal to get the class loader running. (Though not necessarily a full bootstrap).

To truly just load a single class, you'd need a to call a different file than index.php where you'd hard code the class loading.

I haven't looked at how Ajax requests specifically have changed from D7 => D8, but thanks to D8's DI, only classes that are used in a single request will be instantiated, so the need to try to speed optimize things out, as you seem to want to do, should be lessened.


Redirect in multidomain sites My story is:

I use module Domain Access for Multi domain feature and Internationalization, Domain Variable for the multilingual features. I have these domains:

www.domain-a.com (main domain)
www.domain-b.com
www.domain-c.com

All is set to use www. prefix.

Now I have www.domain-d.com.au replacing www.domain-c.com. So I delete www.domain-c.com from Domain list in Drupal and add www.domain-d.com.au.

I also set redirect. So when user visit www.domain-c.com or domain-c.com, they'll redirected to www.domain-d.com.au. I add a rule in .htaccess:

RewriteCond %{HTTP_HOST} ^www.domain-c.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^domain-c.com$ [NC]
RewriteRule ^(.*)$ http://www.domain-d.com.au/$1 [L,R=301,NC]

Result is:

Visit www.domain-d.com.au. Page opened OK.
Visit domain-d.com.au, redirected to www.domain-d.com.au
Visit www.domain-c.com, redirected to www.domain-d.com.au
Visit domain-c.com, not redirected (fail).

Question is:

How to make domain-c.com to redirect to www.domain-d.com.au? Is here something wrong with my .htaccess.

I uncomment the with www. prefix in Drupal .htaccess and add the rule right below the

...

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

...

You have domain aliases with Domain Access, so you can edit your www.domain-d.com.au domain and add aliases that you need with redirection rule.

When you edit the domain you'll notice Aliases tab, there you can find explanation how to create the pattern and you just add the pattern that you need.

So, you don't need .htaccess for this.


How to make a specific post RTL? I have a page where i post English articles by default. but sometimes I have a Persian article that should be posted inside this page. After posting, it shows left to right and is very bad looking. specially if there is bullet points included in the articles. I want to know if there is a module for this or a way to edit my theme files.

Basically what you want to do is conditionally add a class to the field that aligns text to the right. I was wrong in my comment about hook_page_alter, I don't believe it has access to everything you need.

set up a new field, called field_content_persian, check boxes/radio buttons, valued English and Persian, default to English
in Manage Display, hide the label, and move the new checkbox field ABOVE the body. It must render first for this method to work
add CSS - ie. style.css

.align-text-right{
  text-align:right;
}

to template.php add:

function THEMENAME_field__field_content_persian__CONTENT_TYPE_MACHINE_NAME($vars){

  if($vars['element']['#items'][0]['value'] == 1){
    drupal_static('isPersian', true);
  }
  return "<!-- empty -->";
}

function THEMENAME_field__body__CONTENT_TYPE_MACHINE_NAME($vars){

  if(drupal_static('isPersian'))
  {
    $vars['classes_array'][] = 'text-align-right';
    $vars['classes'] .= ' text-align-right';
  }
  return theme_field($vars);
}

If you have a theme named Bartik, and a content type named Article, they would look like this:

Bartik_field__field_content_persian__Article() and

Bartik_field__body__Article()

What this does:

in the first function (field_content_persian), it checks for the value of the checkbox, and if it finds it is 1(persian if order of elements in checkbox is correct - modify as desired), it sets a temporary static variable. Then it returns an empty string so that the field itself doesn't display - NOTE: this function MUST return something, anything, or Drupal will bypass the function and call the default
in the second function it checks for the variable, and if it finds it, adds the class to the body field.


Create a custom block programmatically and specify region and pages on which created block must shown on For create block programmatically I use

$block = BlockContent::create([
  'info' => 'block 3',
  'type' => 'basic',
  'langcode' => 'en',
  'body' => [
    'value' => '
Block's body
',
    'format' => 'full_html',
  ],
]);
$block->save();

It works good enough but is it possible also to specify region and then on which pages created block must shown on?

You have to create a block config entity to place a block:

use Drupal\block\Entity\Block;

  $placed_block = Block::create([
    'id' => 'block_machine_name',
    'theme' => 'classy',
    'weight' => 0,
    'status' => TRUE,
    'region' => 'footer',
    'plugin' => 'block_content:' . $block->uuid(),
    'settings' => [],
    'visibility' => [
      'request_path' => [
        'id' => 'request_path',
        'negate' => FALSE,
        'pages' => '/path',
      ],
    ],
  ]);
  $placed_block->save();


Temporary files directory not fully protected .htaccess I've been getting this error on my status page since I updated to 7.24 (I'm on 7.34 now).

I do have my other files directories protected. I just am having a real hard time figuring how to shut this one off. I've checked at admin/config/media/file-system for the temp file directory, and it's set to /tmp. I think that's the default. But I checked /tmp, no file of that name exists, nor is it in my sites/default/files.

Nothing seems to be broken, at least with file manipulation and storage, so it seems like Drupal is handling things fine, I just am not sure where this folder is supposed to be, or if it's supposed to be a physical file, and if not, how can I protect it with a .htaccess file if it's not a physical folder.

Ugh, so I just realized that the directory was /tmp, not tmp. Meaning that directory is at the root of the file system, not at my site's root. I checked at / and low and behold, there is my tmp folder. Now I know where to place this .htaccess file.


How to get historical content having historical date that happened in current week in Views? I have a content type having date field contains historical date like 1897-06-15. Now i need to fetch it by week if historical date's week matches current week in Views? How to do it in views.Any suggestions?

I used DAYOFYEAR function.

$startDateNumber = date('z', strtotime("-4 days"));
$endDateNumber = date('z', strtotime("+3 days"));

$query = db_select('field_data_field_historical_date', 'fd');
$query->fields('fd');
$query->where('DAYOFYEAR(fd.field_historical_date_value)>=:startDate', array(':startDate' => $startDateNumber));

$or = db_or();
$or->where('DAYOFYEAR(fd.field_historical_date_value)<=:endDate', array(':endDate' => $endDateNumber));

$nid = $query->condition($or)->execute()->fetchField(3);

if (!is_bool($nid)) {
    print_r($nid); exit;
} else {
    print 'no';
}


How can I tell drush to use another php.ini file? I've gone through the setup instructions on https://github.com/drush-ops/drush, but I can't seem to get drush to use a different configuration file, very frustrating.

I've already added the PHP_INI environment variable to my .bashrc and sourced it, seems like there is something I'm missing.

I copied my php.ini file to my home directory, and then ran:

$ PHP_INI=~/php.ini drush status

The "PHP configuration" line accurately reflected the new location of my php.ini file, so I believe this is still working on Drush 6.x and master.


Migrate Paragraphs from CSV I am migrating Paragraphs from CSV file. I have Paragraph called Text with two fields -> title and body.

The problem is that I would like to also migrate translations for them, which currently don't know how to achieve. Tried with the migration_lookup plugin and translations: true option, but receive error for duplicate primary key ids.

What is the way to do this?

A simple solution could be the content import module that allows you to import among other things paragraph content from CSV I believe and you can specify language for each field.  Give it a try


Two different gallery in one gallery I created two gallery with different content type and different views (gallery1 & gallery2)...and i want to make it in one gallery containing one image of each gallery (one of gallery1 & one of gallery2)...   please help me with video or something else...and tell me what i have to do ?              i use Drupal 7               & thx

Create a new View and add the two content type in Filter criteria

Add the two image fields in Fields section

Under Multiple field settings set "1" in display option for both images

Select your Format for views, hope it helps you!!


"Favorite" Module for drupal 7 I am looking for module that would let users of a site save nodes as Favorite, so that these nodes can be found back later via a "My favorite" interface.

Has anyone heard about such a module ?

THanks all in advance

I was thinking that would be a great idea, until I remembered that Drupal contributors have already offered quite a few solutions for this as demonstrated by a quick search of the Drupal site. Of course, Flag module provides a great abstract way of creating these types of systems. There's also Favorites and Add to favorites, but those are for Drupal 6 only right now. I would recommend Flag I think just because I've used it for precisely this type of thing as have many others (even though it's still in beta), and quicksketch and fago are great Drupal developers.


Programming a custom redirect in a Drupal Site I would like to know what is the best option to setup a Drupal redirect process that will look at the current time of day and then redirect the user to a page based on this information?

Since I have not had to do this before in Drupal, I'm looking for one or two suggestions on how to do this with the user starting the action from a menu item.

One thought I had is that I could create a page that is PHP content and determine the redirect there, but I'm unsure of how to code that in that location.

Also, I'm not sure if I've overlooked a module that could help with a conditional redirect or if all the references to form redirects might be applicable to what I'm trying to do.

You could do something along the lines of this:

function MYMODULE_menu() {

  $items['MYMODULE/whattodo'] = array(
    'title' => 'Where should I go now, George',
    'page callback' => 'MYMODULE_whattodo',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function MYMODULE_whattodo() {

  $foo= // code to get the current time of day in whatever form you want that matches the switch cases below

  switch($foo) {
     case // morning:
        drupal_goto(// page for the morning);
        break;
     case // afternoon:
        drupal_goto(// page for the afternoon);
        break;
     case // evening:
        drupal_goto(// page for the evening);
        break;
  }
}

which means when a user went to www.mysite.com/MYMODULE/whattodo, they would be redirected to whatever page you set up via drupal_goto()


How do I simply make the whole site use a secure connection? In Drupal 7, I used the Secure login module to run the site on a secure connection, but it seems it doesn't revert back to http on logout. I would like to just run the whole site as https:// as a simplification.

Is there a simple way to do this without the use of module?

If you want to redirect all of your pages to be forced to use SSL then add this to your .htaccess file.

# Redirect to HTTPS
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This should be placed directly after RewriteEngine on if you have no previous rewrites.


How do I create a rule that closes comments on node after 30 days? I am on Drupal 7, and I am trying to make a rule that closes comments on a node 30 days after they have been created. I am assuming I need to make a component that has an action of "set data value:" to change the "node:comment" to 1. Where I am confused is how to schedule that component to fire 30 days after the node has been created.

Do you have any suggestion?

You need at least 2 rules to make this happen. One is an actual "rule" and the other is a "rule component".

You are correct about the second one being a component which sets the data value on node:comment.

The other one, the rule, needs to be set to activate on the event "After saving new content."

An action for this rule needs to be "Schedule component evaluation". Setting this action then requires you to configure the evaluation, where you set the particular rule component to be evaluated, and then set "Scheduled Evaluation Date" as well.

To make it happen 30 days in the future, enable Data Selection mode, and select "site:current-date", then for the offset field which now appears below it, select 30 days. This will cause your selected rule component to be evaluated 30 days from the current date/time.

After configuring all this and testing it, you can check to see if it works by going back to the Rules interface and going to the "Schedule" tab. Your scheduled task will be listed there.


How to get the site url in views custom output I want to print the site url in views field with a custom output, I tried [site:url] token, It doesn't work.
I already have entity token and entity_token enabled in my site.
Is there a way to do that with or without tokens?

Try to add field handler "custom text" and rewrite result as on the screenshot

but put there your field name instead of [title].


How (and Where) to store downloadable commerce files outside the file system..? I’m building a Drupal Commerce site and am selling downloadable mp3’s. It was recommend that the downloadable commerce files should be kept outside the sites file directory. I’ve tried setting this directory in the admin in 2 places, as separate attempts:

First i created a folder called commerce_files and set it one level up from the Drupal install

Then i tried referencing this folder in 2 places (as 2 separate attempts)

Configuration->Media->File System
Configuration->Product Variation Types->My MP3 Content type->File

Neither worked.

When searching the internet for this topic nothing much is coming up. Does anyone here have any insight or info on this topic? it would be appreciated, thanks

Or maybe i was misled and it is perfectly acceptable to store within the file system, using the Config->Media->Private Folder setting in the admin as i have been doing....?

FYI - have gotten almost no responses when posting the Drupal commerce.org,

You can configure the "Private file system path" to be outside your Drupal installation by changing it in the admin/config/media/file-system. and you configure your commerce files there. this should do the trick. either way Drupal do not provide direct url access to the private files.


I can see the changes I made (as an administrator) but as an anonymous user, I can't Have you had any problems like this before? I appreciate your help.

When I'm an admin and update a node (custom module), I can see the changes I made (as an administrator). However, when I'm an anonymous user, just to check the data, I can't see the changes I made. (note: I have flushed the site, it will work, but only when I run flush)

I thought it was something related with the permission, from a Custom module I created, but I'm not sure of that. I included a permission.yml file and gave full access. It didn't work.

find the attached images:

I had built the code in the Controller folder/file:
I have two public functions called retrieveArrayOne and retrieveArrayTwo. Each one has different data for me to query later (retrieving the data from these two functions).

public function mainviewlist() {
  $array1 = array($this->retrieveArrayTwo());
  $array2 = array($this->retrieveArrayOne());
  $retrieveData = array_merge($array1, $array2);
  $content = "

";
  foreach ($retrieveData as $key1 => $finalValues) {
    if ($key1 == 0) {
      foreach ($finalValues as $disCrop) {
        $content .= "";
        $content .= '' . $disCrop . '';
        $content .= "";
      }
    }
  }
  return array(
    '#type'     => 'markup',
    '#markup'   => $content,
    '#attached' => array(
      'library' => array(
        'modulename/modulename',

      ),
    ),
  );
}

Here is the function from the $array1 and array2. Both are similar.

$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'content-type-name');
$query->sort('title', 'ASC');
$entity = $query->execute();
$options = array();

foreach ($entity as $n) {
  $node = \Drupal\node\Entity\Node::load($n);
  $options[$node->id()] = $node->getTitle();
  $elementA[] = [//
    'nid'        => $node->get('nid')->value,
    'title'      => $node->get('title')->value,
    'body'       => $node->get('body')->value,
    'field_crop' => $node->get('field_crop')->value,
  ];
}

return $elementA;

OK, I found the problem.

In my routing file, I was missing:

  options:
    no_cache: TRUE

That fixed it.


What's the difference between combining Rules conditions with AND and just have them follow one after the other? Is there a difference between using AND in Rules Conditions and simply adding Rules Conditions one after the other?

No difference, except if you want to do something more complex like this:

____ AND _____ OR _____ AND _____

You can only do that with conditional rules. (If I recall correctly)


Drupal 8 - "Implement menu links as plugins", trying to build a menu tree In a previous Drupal 8 menu question here, we determined that menu tree building was now a service. In my D8 contrib theme, I was then able to render the main menu tree as:

function gratis_preprocess_page(&$vars, $hook) {
// Build the main menu links tree.
  if (!empty($vars['main_menu'])) {
    // Build links.
    $config = Drupal::config('menu.settings');
    $menu_enabled = Drupal::moduleHandler()->moduleExists('menu');
    // When menu module is not enabled, we need hardcoded default values.
    $main_links_source = $menu_enabled ? $config->get('main_links') : 'main';
    $vars['main_menu'] = \Drupal::service('menu_link.tree')->renderMenu($main_links_source);
    $vars['main_menu']['#attributes']['id'] = 'main-menu-links';
    $vars['main_menu']['#attributes']['class'] = array('links', 'clearfix');
    $vars['main_menu']['#theme_wrappers'] = array('menu_tree__primary');
  }
}

The key to this is the use of:

$vars['main_menu'] = \Drupal::service('menu_link.tree')->renderMenu($main_links_source);

This worked great to fix my main menu tree in Drupal 8 Alpha 11. However, there have been more sweeping changes to the menu system since then and now in Drupal 8.0.x Alpha14, this breaks again with the error:

Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "menu_link.tree". Did you mean this: "menu.link_tree"? in Symfony\Component\DependencyInjection\Container->get() (line 303 of /Users/danny/Sites/Drupal/d8/drupal8/core/vendor/symfony/dependency-injection/Symfony/Component/DependencyInjection/Container.php).

The thing that stands out from the above seems to be:

Did you mean this: "menu.link_tree"?

I tried

$vars['main_menu'] = \Drupal::service('menu.link_tree')->renderMenu($main_links_source);

... but that does not work either.

I filed a core issue here and that lead me to "[META] New plan, Phase 2: Implement menu links as plugins" and the very same change notice which I used to upgrade this code originally.  Admittedly, I am pretty lost here.

You may need to render it as below:

  // Build the main menu links tree.
  if (!empty($vars['main_menu'])) {
    // Build links.
    $config = Drupal::config('menu_ui.settings');
    $menu_enabled = Drupal::moduleHandler()->moduleExists('menu_ui');
    // When menu module is not enabled, we need hardcoded default values.
    $main_links_source = $menu_enabled ? $config->get('main_links') : 'main';
    // Allowed max depth.
    // @see MenuTreeStorage::MAX_DEPTH
    $level = 9;
    $menu_tree = \Drupal::menuTree();
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($main_links_source);
    $parameters->setMaxDepth($level);
    $tree = $menu_tree->load($main_links_source, $parameters);
    $manipulators = array(
      array('callable' => 'menu.default_tree_manipulators:checkAccess'),
      array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
    );
    $tree = $menu_tree->transform($tree, $manipulators);
    $vars['main_menu'] = $menu_tree->build($tree);
    $vars['main_menu']['#attributes']['id'] = 'main-menu-links';
    $vars['main_menu']['#attributes']['class'] = array('links', 'clearfix');
    $vars['main_menu']['#theme_wrappers'] = array('menu_tree__primary');
  }

P.S: Make sure you clear cache after update, as it looks like the cache-tag is aggressive and doesn't show same menu in all page at the first run.


How to create a special autoincrement field? I have a "Property" content type created for a real estate web site. The Property content type has a taxonomy field called "Type" where type can be House, Office, Apartment and so on...

I want to create a "code" field that has to be something like "H-1" where H is for Home and 1 must be an incremental number, so houses will have each a different code: "H-1", "H-2", "H-3" ... "H-188", etc. And so on for Offices "O-1", "O-2"..."O-479". I see that there is a Serial module, but that module helps me only creating autoincremental numbers for each content type, not based on other fields of that content type.

I was planning to use auto_nodetitle + serial module + rules to create the letter+number format for my field, but I will have the same problem: If I create "H-1" and then create an Office, it will have "O-2" code, and not "O-1" code.

Is there a module than can help me? If not, how can I make it?

The obvious option would be to have a serial field for each type. Whether or not that is feasible based on your business rules (are there lots of types, are the types likely to change, etc.) is another question.

Another module that may be very useful in these types of problems is the computed field module.

Another option (probably the one I would choose) is to make it completely custom.
Either a custom entity property or a custom field of some sort that does database queries to determine the next value instead of auto_nodetitle + serial module + rules.
Be careful of race conditions when doing something like this though.


only allow to upload profile pictures of a certain size I want to limit the user to only upload profile pictures of 160x160 size. What is the simplest way to validate that the resolution of uploaded avatar picture is actually 160x160, and provide an error message if it's not?

You need to form alter user_account_form().  Remove user_validate_picture() as the validator.  Duplicate that function into your own module, and add as a validator.  Inside that, update the size line to be:

'file_validate_image_resolution' => array('160x160', '160x160'),

This should enforce the same value for both minimum and maximum size before the file gets saved off.  I don't think you can add a second validator; I think the size check needs to be done in one step.


Patch Status for 'cweagans/composer-patches'? It seems that 'Drush Patch File' (https://bitbucket.org/davereid/drush-patchfile/src/master/) isn't compatible with Drush 9. It, however, has one important function - Patch Status - which enables developers to check that all the required patches were successfully applied.

I was unable to find any way how to do this via the actually recommended Composer patch management (cweagans/composer-patches)... Is there any way how to (via Composer or Drush command) check the status of the patches? Or is there a clone of 'Drush Patch File' working with Drush 9?

Any help highly appreciated!

I found no available solution, so I've created a new Drush Command for this: https://github.com/SeoGow/patch_overview/tree/master.

I hope this helps somebody.


Limit account applicants with certain email addresses Hi I am working on a website for a student organization of my college.
In order to prevent spams, I have been looking for ways to limit account applicants only with email addresses from the college but haven't figure out how

In drupal 6 you can use the built in Access Rules to limit user sign ups to certain domains. It can be found at admin/user/rules/add

This no longer exists in drupal 7 because the functionality was moved into a contrib module called User Restrictions


hook_nodeapi called multiple times with op='update' I am using the media_mover module.  I added some debug code to media_mover's hook_nodeapi:

function media_mover_api_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  dsm ("entering hook_nodeapi.  op=$op");
  switch ($op) {
    ...
    case 'update':
       ...
       break;
  }
}

When the user edits and saves a node, hook_nodeapi is getting called twice with $op='update'.  Anyone know why this might be?

If media_mover calls node_save during the process of saving the updated node, might that cause hook_nodeapi to be called multiple times with $op='update'?

(I am using Drupal-6.x)

You are spot on.

If a module calls node_save, nodeapi will be called either with update or insert, depending on what happened.


Including a PHP file in Drupal via BLOCKS, or REGION Hi I am newbie in Drupal, I have problem about theming.

I have a PHP file ads.php that contains random advertisements now just wondering what is the perfect way to include that ads.php

Can I just use the PHP include command

include('ads.php');

or import it as a block for example block--ads.php  or region--ads.php  I DON'T KNOW IF THIS IS POSSIBLE. I am still confused on how drupal theming works.

Please help me.

You need to create a block template in your themes template folder.

To do this, you would create a new block, in Structure > Blocks, give it a bit of dummy content and save it in a region.

Then inspect the ID of the block in the source, or in Chrome Dev Tools, or Firebug, it should be something like block-block-1

In your themes template folder, copy the file block.tpl.php and rename the copied file block--block--1.tpl.php

In that file, you should see something like...

<div class="content"<?php print $content_attributes; ?>>
    <?php print $content ?>
  </div>

Just replace the <?php print $content ?> with your content from ads.php

Then, in Performance > Development, flush the cache, and you should see your template replace the content of the block you created.


Can't add a custom filter criteria I try to add a new filter criteria to my views with a custom module.

I manage to display my new filter on the filter criteria list but when I select it and go to "Add and configure filter criteria" I have an error saying:

  The handler for this item is broken or missing. The following details
  are available:

  Enabling the appropriate module may solve this issue. Otherwise,
  check to see if there is a module update available.

Here is my content_search.module :

function content_search_views_data_alter(&$data)
{
    $data['node']['content_search_filter'] = [
        'title' => t('Content search filter'),
        'filter' => [
            'title' => t('Content search filter'),
            'help' => 'Filters nodes on its content',
            'field' => 'nid',
            'id' => 'content_search_filter',
        ]
    ];
}

And here is my ContentSearchFilterPlugin, placed in content_search/src/Plugin/Filter/ContentSearchFilterPlugin.php

namespace Drupal\content_search\Plugin\Filter;

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\filter\FilterPluginBase;

/**
 * Filters nodes on on their content
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("content_search_filter")
 */
class ContentSearchFilterPlugin extends FilterPluginBase {
  /**
   * {@inheritdoc}
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $this->valueTitle = t('Content search filter');
  }

  public function query() {
    parent::query();
    // TODO: custom query here
  }

}

What am I missing ?

I think you have a problem with plugin file organization. It should be :

content_search/src/Plugin/views/filter/ContentSearchFilterPlugin.php

...instead of

content_search/src/Plugin/Filter/ContentSearchFilterPlugin.php

And the namespace for this file should be

namespace Drupal\content_search\Plugin\views\filter;


Some feedback please on my hook_search_execute function? I'm following along with Pro Drupal 7 Development by Apress (page 321) and using it as a guide to create a module that searches a legacy database of pages I've yet to import into a drupal install. I'm also using the API as a guide as well.

Everything works except for the number of results returned by dynamic query.  What happens is, despite having PagerDefault and using a limit of 10, only 1 item shows up on the page. I can switch the number to any number and it's still 1.

I know for a fact there are 240 items that should be returned. And, indeed my pager list 24 pages (24 pages of 10 results). Again, however, there is only 1 result per page for a total of 24 results.

Here is my function:

function searchharvest_search_execute($keys = NULL) {

    // Set up and execute the query
    $query = db_select('search_index', 'i')->extend('SearchQuery')->extend('PagerDefault');

    $query->join('url_data', 'ud', 'ud.id = i.sid');
    $query->searchExpression($keys, 'searchharvest');

    //If there weren't any results return a blank result set
    if(!$query->executeFirstPass()){
        return array();
    }

    //If the first pass returned at least 1 record execute the search
    $found = $query->limit(10)->execute();

    //dsm($query);
    print_r($query->__toString());
    //Create the search results output
    foreach($found as $item){
        //dsm($item);
        //get found items from db
        $note = db_query("SELECT url, stripped_html from url_data where id = :sid",
                array(':sid' => $item->sid))->fetchObject();

        $results[] = array(
            'link' => $note->url,
            'type' => t('searchharvest'),
            'title' => 'my title ' .$item->calculated_score,
            'score' => $item->calculated_score,
            'snippet' => search_excerpt($keys, $note->stripped_html),
        );

        return $results;
    }

Thoughts on where the error is? Here is a photo as well with the query 'print_r' 'ed at the top

The return $results was inside the foreach loop, which stopped the iteration, hence only 1 result.


Is there a module to show photos on Drupal site that come from Facebook user profile/Facebook page, like Wordpress Fotobook Wordpress Fotobook plugin will show photos from a user's Facebook profile (assuming the user has set the appropriate permissions for them to be made visible, and that suitable Facebook App settings and id have been setup).

I wondered if there was an equivalent module for Drupal?

I would prefer a module that doesn't locally copy the photos onto the site but rather links to the original photos on Facebook. This preference is be efficient with bandwidth, storage space, and backup. Effectively, I'm looking for something that makes Rvisible album photos in a similar way to RSS feed (doesn't have to be exactly the same format as RSS but the same kind of idea whereby the original content is not copied.)

I am developing sites for two friends who actively use Facebook but want photos on their own sites. With the Drupal 7 Media module, multi-image batch uploading is very capably handled in Drupal, however this still requires double effort to upload photos both to their profiles and their sites.

Let me know if a module is available. I am considering writing one myself, learning from Fotobook, but didn't want to duplicate effort.

Kept this open for a while but there has been no answer so I guess not. So, another module for my to do list to write, once I am fluent in writing modules and the Facebook APIs.


How can I set up roles and allow users to choose which role to be? I have some users and I want to offer them the chance to choose their role which will have different permissions settings? How can I include a field on their user profile to allow them to choose the role? Is having a select list and then check that value the best option or is their a module that takes care of this kind of 'roles and responsibilities' stuff. For example, there is a 'facilitator' role which I want to give more permissions with regards to messaging users.

There is a module that is supposed to cover that https://drupal.org/project/autoassignrole.

Or if you want to make it supper slim, you can add custom code to add dropdown with existing roles to account edit form and update user account on form submit.


Changing workflow status programmatically in Drupal 7? It appears that though Drupal 6 offered workflow_transition(), that function is not available for Drupal 7. Is there an equivalent? If not, what else are we supposed to use?

workflow_transition() is a function implemented from the Workflow module, and it still is implemented in the version of the module for Drupal 7.


Add restriction to content on the basis of various User I am new in drupal, So I want to know how can I restrict my content in content listing according to various users. e.g. I have four contents named A,B,C,D. Now I want Customer1 to see and edit only content A and B. While Customer2 can do the same with C and D only.
I've done my research and read about "form_node_admin_content_alter" but not sure how it works. So kindly provide me an efficient solution for this.

Thank you

Creat role and assign role to the different user. Based on role set permissions of view content under people permission page.

If A role user can see A type of content so you can allow permission to view that content type page.


Is node:nid missing? I installed Drupal 8.1.0 and created a view, but I don't have the option of choosing the node ID (as a contextual filter, for example) but I can select the content ID. If it isn't the same thing, why would the node ID be missing as an option?

Content Id is the node id in Contextual filters for Drupal 8 views.


404 error on AJAX file upload I get 404 errors on file uploads on a D7.19 website. The displayed error is the usual oversized file but I'm sure it's unrelated (see below).

Here is the apache log message :

POST /file/ajax/field_photos/und/form-YJgDfzca9S88uWmWhrE2GGYBM_sIEKXLGvVKQD34xeU HTTP/1.1" 404 1563 "http://dev.domain.com/node/add/animal" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/536.26.17 (KHTML, like Gecko) Version/6.0.2 Safari/536.26.17"

I'm sure the server setup is OK because some other sites hosted on it have AJAX working flawlessly.

Disabling Javascript makes file uploads work OK, so it's definitely some Javascript getting in the way somewhere.

What I tried yet :

changing JQuery version (update or no update)
put the website in english (prod will be in french)
disabling any compression and caching
enabling any compression and caching
disabling some modules (Superfish, dev modules, UI stuff)
different browsers : error is the same everywhere (Safari, Chrome, Firefox).

... and browsed the web like crazy, not finding anything about this precise error.

The only vague hint I have is a file called jquery.cookie whose code doesn't seem to be aliased correctly ((function ($) { // code here })(jQuery); ) but I doubt it could be it.

At this stage, any idea would be welcome. The website is supposed to go live tomorrow (!).

Solved it !

Explanation :

A file with a name like 'file.xxx' was present at the root of the site. I removed it and everything started to work.

I then put back an empty file named 'file.txt' at the root of the website, and the same error rose again.

It can happen more often than it seems. In my case, I downloaded a patch for the  filefield module which was named file_something.patch and forgot to delete it after applying. Easy to do, easy to forget, hard to remember once you've moved on to something else.

Bottomline : keep your webroot clean of anything not Drupal or you're in for trouble. Can't believe I lost two days with such a simple problem.

Thanks to Mohammed Shameem for his try, and to anyone who gave this a thought.


Parse error on JSON response containing URL value In my code it is making Ajax request for json data. For JSON output I am using drupal_json() function.

But on browser side it is invoking error handler instead of success handler and getting 'parsererror'.

The JSON data is like this:

{
    "affiliate_urls": {
        "4131": {
            "nid": "4131",
            "title": "play.com - Books",
            "file_path": "sites/default/files/playlogo.gif",
            "url_value": "http://www.play.com/Search.html?searchstring=asd+asdasd\x26searchsource=0\x26searchtype=allproducts"
        }
    }
}

When put on http://jsonlint.com/  I am getting this error:

Parse error on line 7:
...       "url_value": "http://www.play.com
-----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

What is wrong with passing URL value over JSON? and still using drupal_json().

Please help on it.

Thanks

The problem is with drupal_to_js() which is called by drupal_json() to do the job. drupal_to_js() will perform str_replace(array("\r", "\n", "<", ">", "&"), array('\r', '\n', '\x3c', '\x3e', '\x26'), addslashes($var)) to every string it receives. Converting '&' to '\x26' is making problem to me here. Anyway I cannot use json_encode() because of PHP dependency (Drupal 6).

I solved the problem by URL encoding the URL value on server side using PHP function urlencode() when preparing JSON data. And URL decoded it on browser side by JS function decodeURI().


pecl uploadprogress installed, but I don't see it anywhere I've successfully installed the PECL uploadprogress extension and restarted my server. Here's an exerpt from phpinfo():

However, when I add a piece of content and I choose to upload a photo or a video or a generic file, all I see is the normal ajax spinner but I don't see any kind of upload progress UI that I see on the drupal site (Install PECL uploadprogress), which looks like this:

What am I missing?

Ah, I stumbled upon it right after posting. It needs to be configured on each Field in particular. I edited my Content Type and changed this setting: