A node in two different points I am using Drupal 7 and i have the following problem:
I have

The content type: issue,

Two views (which select nodes from the content type issue) with each view appearing from a different menu link

Two menu blocks, each one of them appearing based on the view i have selected from the corresponding menu link

I want the titles of my view nodes to be links to the content of type issue. I want, by clicking on this title, one menu block (from the  previous two) to be appearing based on the view I have clicked the title.
I can't solve this problem with two different aliases. Any ideas??
Examples:
Here is the first case:
I have a view which lists Issues nodes and the activity block is appearing on the left. By clicking on the titles, i go one more level inside and i have this result:
Now, another view which lists the same Issues nodes,as above, exists in my site in a different point:. With this view, the resources menu block is appearing on the left. By clicking the titles from this view, i want to go one more level inside (as above) and display the resources menu block and not the activity menu block, as in the first case.

Following the instructions with Contextual Filters as follows, I have the following results:By clicking on a title from the first view :
and by clicking on a title from the second view:
As we can see, although the appropriate blocks appearing in each case, but i don't see the original content that includes each view node.
I thought that having two different url aliases for each view node the problem could be solved. But this couldn't be a solution, sine by testing this case if i click the title from any view, only the resources block is appearing. Apart from this, i want the URL aliases to be defined automatically and Pathauto module doesn't allow this functionality: for a content type to define two different patterns
Any other ideas please???

What if you rewrite the title field of your node results with HTML so that each title links to the view you have created? Your view already displays all nodes with category "issue".

Edit:
To link your titles to the view, I assume that in your view fields you are able to see a filed that looks like "Content: Title (Title)". Click on the field and on the field edit for visit the section "Rewrite results" and check "Output this field as link". In the "Link path" field, fill in the path to your view. I think this will work

Now for your blocks you can configure them to appear only when your view is being displayed, e.g.

Configure block
Show block on specific pages:
Check "Only the listed pages":
In the field below enter "path_to_your_view/*"


Programmatically load node edit form I'm able to load node create forms like so

$node    = \Drupal\node\Entity\Node::create(['type' => 'avenue']);
$content = \Drupal::service('entity.form_builder')->getForm($node);

return $content;

However what if I want to load an edit form for a pre-existing node? I looked on this page https://api.drupal.org/api/drupal/core!modules!node!src!Entity!Node.php/class/Node/8.2.x but I can't find anything that would relate to the edit form. Is there a way to load the edit form for a specific node?

Yes, on the linked page you would find Node::load() to get a pre-existing node:

$node    = \Drupal\node\Entity\Node::load($nid);
$content = \Drupal::service('entity.form_builder')->getForm($node);

return $content;


How to pre-fill form fields with data from the node? I have a site that list different courses that take place in real life (not virtual courses). For each course, there are different fields :

title of the course
start date
end date
place where the course will happen
type of course
...

With View I have created a table that list all the courses. I would like that logged users can subscribe to a course by just clicking on it, and then I would receive an e-mail (or see in the back-end) that tells me that user X has subscribe to course Y (and I will have in the same time all the informations about the course the user subscribed to : title, dates, place...)

For the moment when a logged user click on a course, another page loads that displays informations about the course, and a form where the user have to write out again all the informations in blank fields...

Is there a way to pre-fill the form fields with the informations of the course ?

Or is there a smarter way to do this ?

Thanks

You could use Prepopulate module to prefill fields in subscriptions. But:

I would redesign the model in order not to save the same information you already have in courses again with the subscription. It's redundant to store title, date, place, etc. twice, with all the implications changes of the primary information in courses would have.

Said this content type "subscription" only should save a entity reference to courses. I propose to add a link to each course in Views which allows to subscribe to it. To do this, follow this steps:

Add field "ID" and check "Exclude from display".
Add "Global: Custom text" to your fields and put a label like Subscribe.
Under Rewrite results, check "Output this field as a custom link".
In field "Link path" enter node/add/subscription?edit[course]={{nid}} - where "course" is the name of entity reference field in content type subscription and "nid" is the replacement pattern for the course id.
Install and activate Prepopulute module

Clicking a subscription link in Views should now open subscription form and prefill the referenced course field. Making a custom module would allow you to create this content type without showing the form to the user.


load a node content into a lightbox2 (without headers and footer and other blocks) is it possible to load a node (from an id) into a lightbox 2 without having to load all the additional blocks ? just what the node has to display

I want to make some popups on some links to allow some nodes to be shown inside..
no submission will be made in this case (comments are disabled)

another cool thing will be including webforms in a lightbox..
Again no headers..but I believe that that's more complicated because it's form submission... so ajax in required

There are many ways to do this, and this gets asked a lot, please have a look at my answer in this question.

Look at this doc page from the Lightbox2 documentation.

Right now though I highly recommend using the Modal Frame API and Automodal for things like this.

** Drupal 7 update

The colorbox module doesn't offer out of the box support for nodes yet (they are working on a patch for this), but in the meantime you can use this approach. You can also use the Shadowbox module, have a look at this and this issue.


Can't restrict permissions on forum topics? I have like a bit of an issue with my forum-topic content types : any authentificated user can edit and delete any post in the forums (node or comment of forum-topic type). It's not the case for any other content type where permissions works normal (user can edit/delete their own content, but not any content).

My features are the following:

User's permissions :

  Forum topic: Create new content -> auth user : YES ; admin : YES
  Forum topic: Edit own content -> auth user : YES ; admin : YES
  Forum topic: Edit any content -> auth user : NO ; admin : YES
  Forum topic: Delete own content -> auth user : NO ; admin : YES
  Forum topic: Delete any content -> auth user : NO ; admin : YES
  Bypass content access control -> auth user : YES ; admin : YES

The modules installed in the forums : Advanced forum, Forum Access.

Forum permissions (in admin/structure/forum/)
view this forum - post in this forum - edit posts - delete posts : all checked for auth users and admin.

-> Disabling Forum access only make delete and edit any comment/reply on forum topic disappear. But any auth user can still delete or edit any topic.

-> Disabling "bypass content access control" make forum topic unvisible to auth users.

I hope it is somehow clear... And you can find what's going wrong.

Thanks !

The problem is that you selected "Bypass content access control" for the authenticated users. That means the previous permissions you chose for the authenticated users are not considered: You didn't give the permission of editing any forum topic, but as authenticated users are selected to bypass the content access control, Drupal will not check if they can edit any forum topic, and it will give them that permission.

If you look at the code of node_access(), the function that returns TRUE when a user has the access passed as argument for the node passed as second parameter, you will notice that it execute the following code:

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

What you reported are only the Drupal core permissions, not the one set by the Forum access module. For the Drupal core permissions, you didn't report if the authenticated users have the "View published content" permission; without that, any published content would not be visible to any users, except the user #1, and the users with the "Administrator" role, for which Drupal automatically set all the permissions, but then leave you the possibility to disable some permissions.

The other problem is the conflict between Drupal core permissions, and the permissions set by the Forum Access module; when you use that module, you should not use the permissions used by Drupal core core, such as the ones you reported. If Forum Access needs to control the permissions, then the permissions you shown for the forum topics should not be set.

If the users get an "Access denied" error for every node, even if those are not forum topics and they have the permission to view published nodes, then the problem is something else. The first think I can think of is that those nodes are unpublished: There is an option in the content type settings that set its nodes as published, when created; if that option is not selecte, the nodes are created unpublished. It could also be a problem with an installed module (which is not Forum Access, as it doesn't handle permissions for other content types); in that case, I would not be able to give a hint about which module is causing the problem, but I see the same problem when the theme used as default theme was not enabled.


How can I make views show 10 items if there are actually less (and add placeholders)? I have a view output that shows user-profiles. Each view is a group on it's own and has a maximum of ten members. How can i show always ten items, if there are currently -let's say- only 7 assigned? So it would show 3 empty slots with maybe a custom text.

I don't find any logic that's out-of-the-box views behaviour for this. Can someone please point me in the right direction?

Thanks!

EDIT: Adam Balsam pointed out the grid format, which has an autofill feature. Unfortunately it's just an empty table row that is created. It's also not useable for responsive layouts... bummer.

You can add the empty rows to the view in the View's Style output template. Assuming you are using the unformatted style, the template name would be views-view-unformatted--[view-name].tpl.php.

Using the default views-view-unformatted.tpl.php as a starting point, add the following to the top of your custom template:

<?php
$num = count($rows);
$add = (10 - $num);
for ($i=0;$i<$add;$i++) {
  $rows[] = '
Empty Row
';
  $classes_array[] = 'views-row views-row-' . ($num + $i);
}
?>

If you're worried about the views-row-last classes, etc, the same sort of logic could be applied earlier in the view build process using something like hook_view_pre_render(), but depending on your scenario, the above should suffice.


Drupal 8 Apply Custom Theme To View I have a Drupal 8 installation set up that is using a custom Bootstrap theme as the default theme. I have a View created to be a blog, and want to give it a different custom theme than the default. I have the path set as "/blog". Is there a simple way of doing this through code (specifically referencing either the URL or the view) or a menu option I've overlooked?

I've looked at other related questions on here such as: How to apply theme to Drupal view or block

But in my View display settings there is no "Theme : Information" option available.

Any help is greatly appreciated! If there is more details I can provide for a solution, please let me know!

Drupal 8 views doesn't have a Theme: Information section, or at least it doesn't have information about themes.

Twig is the themeing engine, so you'll need to get information there. You can enable twig debugging in a services.yml file:

parameters:
  twig.config:
    debug: true

This will print out theme-able names for views in the html. On a site I'm looking at the print out only gives one option for the view:

<!-- BEGIN OUTPUT from 'themes/custom/sitename/templates/block--views-block--our-leadership-senior-management.html.twig' -->

But the block that holds the view has a number of options:

<!-- FILE NAME SUGGESTIONS:
x block--views-block--our-leadership-senior-management.html.twig
* block--views-block.html.twig
* block--views.html.twig
* block.html.twig
-->

The x indicates that's the template I'm using.


FAPI #states for multiple selections. I've used the FAPI #states system before to show/hide conditional fields. It's great.

However, when I am trying to show a field based on another field's value, I'm running into a problem. The documentation for this only explains how to show/hide a field based on whether my independent field has a particular value. In my case, I don't care what the exact value is, but if it has multiple values selected from a select list, I'd like to show my dependent field, and hide it otherwise.

Does the FAPI #states system support this? If so, where can I find the syntax for how to use it?

You should be able to define something like this:

'visible' => array(
  array(
    ':input[name="ELEMENTNAME"]' => array(
      array("value" => 'VALUE_1'),
      array("value" => 'VALUE_2'),
    ),
  ),
),

See this question  for more details


add custom header in term listing tpl page I want to add some header information in header of term listing. This is my requirement.

I achieve the listing of terms (store) with the help of term-taxonomy--store.tpl.php template but how to add Find stores alphabetically portion in header, because if I add that portion in term-taxonomy--store.tpl.php , it repeats with every store. what i have to do for that ?

I think you're not trying to do that in the right place. The data manipulations should be made (in my opinion) in the modules part or in your template.php, not in your files.tpl.php...

If I were you, I'd proceed with Views module that allows exactly to do what you're trying to get. Answers to this question could help you to create an alphabetical pager with Views.


How can I check in Twig if an advanced theme setting option is unchecked? I've a list of advanced theme option(checkbox) to not display, such as search bar.
I did many research about custom advanced theme setting, but all the samples are
{% if remove_searchbar %}{% endif %}. This render if the option is checked but I want the opposite.
How do I make a statement for if an option is unchecked? I really don't want to do {% if remove_searchbar %}{% else %}{% endif %} or make everything checked by default.

The following answer is credited to @leymannx.
{% if not remove_searchbar %}
  do something
{% endif %}

After some research I found twig syntax. You also can find the "if statement" syntax and samples on Twig Symfony website.


Unable to specify different grid columns settings for page and attachment I am trying to build a views grid display where I have two rows of 3 items each, and then one row of of four items. To me, the logical approach would be to use a primary display in a grid format, and then an attachment, since the layout is slightly different. However, this does not work, because it is impossible to have different grid settings for the primary display and the attachment.
For instance, I set the number of columns to 3 for the page display. However, when I create the attachment display, set the columns to 4, and attach it to the page display, when I go back to the page display, the columns in the grid settings is set to 4. In order to get 4 items in a row in the attachment without affecting the parent display, I have to use the unformatted format and do theming.
Is there a way to have separate grid settings for an attachment vs the parent display? There is no option in the grid settings for overriding for just that display.

You can apply different Format to different Views Displays.
In your Attachment Display you have to click on the Format option, not on the Settings link. This will open the modal dialouge where you change the Format for the Attachment, but before you save make sure you change the For option to This attachment (override).

The default option for the For is "All displays" so if you change it under Attachment, it will automatically change on your Page Display as well, unless you override it like I described above.
Just remember that the overriding option appears on the modal dialogue where you're choosing the option, not on the "Settings" modal that depends on which option is set.


How to designate a region for regional shipping charges by weight with drupal commerce? My commerce shop needs different shipping charges by weight to different regions in the U.S.; the east coast, the mid-west, and the west-coast.

Such that a 6oz package would have three different shipping charges depending on where it was going.

I would imagine this need three different weight-based rules for shipping, I am specifically wondering about how to implements the conditional statements for these. I would imagine one way to implement this would be a series or AND/OR statements in the conditional, but for a case like the US, thus means sometimes 20+ AND-OR conditions on a state by state basis.

Is there an easier way to designate a geographic region as a collection of states? Or is this the best and only way to implement this?

You can try out Commerce Shipping Postal Code Weight, which sounds like it might solve your problem.


How can I add a extra feature to repeating date field? I have a content type named Tasks and it has a date field.

I use this date field for weekly tasks and I want to add a simple on/off checkbox for these dates.

For example I add a weekly task for 11 November 2016 and I pick repeting option to every week.

I want this;

Field Collection is exactly what you looking for. It allow you to create a group of fields, and then add this group of field as a field on your content-type (and made it repeatable as your date field).

In your case, you create a field collection constituted by a checkbox field, and a date field. Then add this field collection to your Tasks content-type and made it repeatable (Unlimited).


multiple content items on one page Hope that someone can help me with this question.

I am using the latest version of Drupal 7.

I appreciate that what I am trying to do can in part be achieved with Views, Panels, combinations of the aforementioned or other things like taxonomy and CCK. Perhaps I am not understanding them fully enough to get their full power. However, I am hoping that there is perhaps a module to do what I want to do. As I said, I know I can do some of what I want to do using Views and Panels but I can only figure out how to do what I want to do on a specific 'page' by 'page' basis by using the interface provided in the views and/or panels sections for each specific page. What I am want is a more dynamic way of creating a view without having to go through the process of creating a view each time.

I know that nodes are not traditionally used as I want them to be. However, I want to be able to give an admin user the ability to place multiple content types (multiple nodes) on the same 'page' without having to design their own view and/or panel set up for each 'page'. For example on one page they may want to put a content type called Article, then beneath that article they want to put a Video, under that a basic page, then an Image, then an image with a text wrapped around it and then another specific article and so on. There could be any combination of the content types (nodes) on each page and any number of pages.

I appreciate that generally speaking a "basic" node is generally considered or rendered as an individual "page" or grouped together in some way to display as a blog BUT I want to give an admin user the ability to dynamically combine any node not just the type with an easy to use interface. Even it is just drop down menus of the different content types. I also want to give them the ability to move these up and down the page preferably using drag & drop or at least a text box to put in the weight of each item.

I have found the command "node_view" and can sort of see a way of using that but I wouldn't know how to use it in a dynamic way or how to set it up for use on user created "pages". I am fairly new to Drupal and I maybe barking up the wrong tree. Perhaps there is already a module out there that I haven't found.

Thanks in advance for any help...

we had a similar requirement for a site we built recently. In this case we ended up creating a content type representing a "page" with entity reference fields used to pull in the other content to be displayed.

We also used the Entity Connect to make the users' lives a bit easier by providing the ability to add new content from within the page edit form.

So just to clarify, there's one content type you might call a "page" or "container", and several other content types used to comprise its contents. Each entity reference field was laid out in a different area of the page when displayed, and could have multiple values.


Why is my view not displaying Solr index results? I have a multilingual site and I created a Solr server, created an index (for all content types), added fields, generated the search (it displayed that all my nodes were succcessfully indexed 8/8), then created a view using that index and selected render entity and the view has no results. I tried fiddling about with every setting in the search_api options/index, rebuilding the index, clearing the cache, and the view results is always empty. Ideas?

The problem was i forgot to look at the php-error log/watchdog. There was a custom module which had some code which was causing a fatal error on all links being generated. Fixed that issue, all was working after.


drush error - how to apply patch? When I try to update modules or clear cache with drush on my local dev machine (Mac OSX) I get the following four times at the beginning of the command result, and it fails.

  Invalid argument supplied for foreach() pm.drush.inc:584

My sites are D7, and the drush version is 6.0-beta1.  I can't find what the latest version is anywhere.  Is this it?

I looked on drupal.org and found a patch here: https://drupal.org/node/2041875

But I don't know how to apply a patch to drush. Can anyone point me to that information or tell me how to do it?

Drupal has a wealth of community documentation related to this:

Patch guide
Applying patches
Applying patches manually

However, for your first problem. Drush is pretty much version independant. If you have the latest version of drush it will work with drupal 7, 8 and most likely 6.

Finally, the issue you linked also mention that it's been fixed in the latest version of drush as well.


Add a last edited by column to find content results In the admin area when a user is on the find content page /admin/content I would like to add an extra column to the results table to display the user who last edited the node.

I'm fine with actually querying to get the data I'm just not sure of the best way to add the extra column to the results table.

Thanks

You are looking Extra Columns

  This module allows additional columns/data to be added to the node,
  comment, and user tables in administration area. It provides a list of
  fields defined in your drupal installation as well as a few custom
  fields to choose from.

Alternatively you can try Administration Views module.


How do I remove JOIN in hook_views_query_alter()? I have a view with two filters (A + B). Filter B should only be included in the query, if a specific value in filter A is set (like a "conditional filter").

So I tried to remove the where condition of filter B in hook_views_query_alter by unsetting it:

if($remove_filter_B){
  foreach ($query->where as $condition_group_key => &$condition_group) {
    foreach ($condition_group['conditions'] as $condition_key => &$condition) {
      if($condition['field'] == 'field_B_to_remove'){
        unset($condition_group['conditions'][$condition_key]);
        break;
      }
    }
  }
}

I successfuly removed the where clause but the INNER JOIN on the table of filter B is still part of the query. How can I remove it? I've tried unset($query->tableQueue['node__field_B_to_remove']) but this doesn't work because tableQueue is protected.

Maybe I'm going the wrong way. Basicly I just want to have a "conditional filter".

Some aditional info: The view lists nodes of two different types. You can filter those node types with filter A. The field of filter B only exists in one of the node types. So if you choose filter B you only get nodes of one type. And when you select the other one in filter A you get no result. And that's the issue.

you can add field B as a relationship and use as a reference term in your View UI


Drag and drop content on user side in drupal 6 I am developing a Drupal 6 site in which I need to allow user to drag and drop
blocks of content, but the arrangement of the content for each particular user should be persistent whenever they visit the site. I have completed the drag and drop functionality but after each refresh the content reverts to its original layout.

Here is the example site: http://portal.opera.com/

How can I make the results of D&D functions persistent?

Save the arrangement of blocks using some client side storage (e.g. cookies) when it is changed. After the page is loaded, use JavaScript to recreate the arrangement from the stored information.


hook_block_view_alter() is not invoked I am trying to change the way "Search results" header is rendered in D8. Unfortunately HTML is hardcoded in SearchController and not themeable. I figured I could use hook_block_view_alter to change the $build['search_results_title'], but the hook implementation from my theme never gets called:

function labweb_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  if (isset($build['search_results_title'])) {
    unset($build['search_results_title']);
  }
  kpr($build);
}

Any ideas? It seems that this hook never gets called...

...but the hook implementation from my theme never gets called:

hook_block_view_alter() will not be called for themes; it is invoked only for modules. This is why your hook is never invoked.
To implement this hook, you need to create a custom module. If you need help to create a module you can check here to start.
I strongly suggest to read block_view_alter docs too.
Look at Theme Hooks to see what you can 'hook' in your theme.
For more information about hooks look here.


How to redirect to a certain page after logout from any link Does anyone know how to redirect to a certain page like mysite.com/message-board-page/23
from any link, for example from mysite.com/node/add/message-board/23 or mysite.com/message-board-page/23

Currently I am doing like this, but it just works for any link that has $arg = 3

$arg = arg(3);
  ....
  href="/user/logout?destination=message-board-page/'.$arg.'"

Any help would be appreciated!

If i am correct you want the user to to redirect to a certain page say test-page-3 from any page or url after logout.
Enable the Trigger Module. In configuration go to Actions, -- there in Create an advanced action Select Redirect to URL and press Create. Then label it as you want it and in URL add the page URL you want the user to redirect.
Then go to Structures and Select Triggers,  here select USER Tab in Top Right corner.
Then in Trigger: After a user has logged out , Select the action the action u have created.

Hope that helps and tick if u find it useful.


Strict warning: Only variables should be passed In Drupal 7. I am printing a cck field image to my page.tpl like this

<?php print render(field_view_field('node', $node, 'field_slide_photo1',
array('label'=>'hidden'))); ?>

and I get this error php  Strict warning: Only variables should be passed by reference in include() (line 59 of var/www/html/upgrade2a/sites/all/themes/themea/page.tpl.php

But I can use this in node.tp with out errors?
    print render($content['field_upload_thumbnail']);

How do a print a field that is available in the page template?

You should attrubute the result of function to variable and then pass to render. The difference is that in sencond case you're passing certain variable instead of result of function.


CKeditor adds extra  tags CKeditor adds many <p>&nbsp</p> tags for all new lines when editing as HTML source. I found a discussion:

http://drupal.org/node/669114

But I don't understand, how to fix it. If anybody fixed this, please, tell me, what should I write in CKeditor config file.

You need to set ckeditor configuration setting

config.enterMode

to proper value

(1) The default creates a paragraph element each time the "enter" key is pressed:

config.enterMode = CKEDITOR.ENTER_P; // inserts

(2) You can choose to create a "div" element instead of a paragraph:

config.enterMode = CKEDITOR.ENTER_DIV; // inserts

The setting that you are looking for *

(3) If you prefer to not wrap the text in anything, you can choose to insert a line break tag:

config.enterMode = CKEDITOR.ENTER_BR; // inserts

The application developer indicates that using the ENTER_BR setting is not recommended.
http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html#.enterMode

There are three more settings that are somewhat related to this subject:

config.fillEmptyBlocks
config.forceEnterMode
config.ignoreEmptyParagraph

A complete list of the available configuration options can be found here:
http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html


Views show fields is set, but only "Content" options are available to select - why? Simple question. I thought I knew views, but right now I'm stuck. All I want is a view with the body field of a certain content type.

I have "Fields" selected:

But when I go to add a field, my options are severely limited:

(There is no such thing as a "Content: Body" option to select.)

What happened to the rest of the categories in the Filter dropdown? I'm missing something obvious here...?

The Content: Body field should be there as long as it exists in the content type.

A couple things you can try in this order:

Ensure all permissions are set properly
Flush all caches
Flush the views cache at /admin/structure/views/settings/advanced
Disable views cache just to see if that's an issue
Update Views

Here's a current issue of the problem


What steps do I need to take to use Drush Make on a Windows machine? I have the Drush Windows installer. I download the Drush Make module and put it in the drush\commands folder. Still I don't have any luck with Drush Make on Windows.

I found the solution on this page. There were several steps but it really wasn't that difficult. For some reason it doesn't download items from Github but that might be something to do with the path variable not being set correctly and I just downloaded a few modules from Github manually.


Using hide($submitted); in a tpl? Right now I'm working in a tpl file and in a specific place I have <?php print render($submitted); ?> and this works just fine. However, later when I do <?php print render($content); ?> it will render the submitted by link there as well. Normally I just:

<?php
  hide($content["comments"]);
  hide($submitted); //this does not work like it does with hiding comments and links
  print render($content);
?>

However, the copying the way to do it for comments and links does not work with submitted and it continues to render the submitted by in the content.

There must be 2 variables holding the "submitted" string, $submitted and also $content['submitted']. You should either forget the $submitted variable and if you render($content['submitted']) then it should put that as #printed => true. Then later if you render($content) it shouldn't print the submitted text as it's already printed.

The second option would be to render($submitted) and then do hide($content['submitted']) before render($content).


Trying to print a form with a shortcode I'm currently working on a drupal module and I want to print a specific form called by a shortcode. So I've use this tuto and here is my code :

Info :

    function custom_shortcodes_shortcode_info() {
      $shortcodes['form'] = array(
        'title' => t('Link form'),
        'description' => t('A simple form.'),
        'process callback' => 'custom_shortcodes_shortcode_form',
      );
      return $shortcodes;
    }

Callback:

    function custom_shortcodes_shortcode_form($attrs, $text) {
      $attrs = drupal_get_form('custom_shortcodes_shortcode_form_attributes');
      return $attrs;
    }

Form :

    function custom_shortcodes_shortcode_form_attributes() {
      $form = array();
      $form['PrjLogement'] = array(
        '#type' => 'textfield',
        '#title' => t('Field1'),
        '#required' => TRUE
      );

      $form['MenageRevenuM'] = array(
        '#type' => 'textfield',
        '#title' => t('Field2'),
        '#required' => TRUE
      );

      $form['MenageApport'] = array(
        '#type' => 'textfield',
        '#title' => t('Field3'),
        '#required' => TRUE
      );

      $form['submit'] = array(
        '#type'=>'submit',
        '#value'=>t('Submit')
      );

      return $form;
    }

Now the thing is that every time I'm calling the form with the specific shortcode the output is just "Array".
Is there any way to print this form ?
Thanks in advance for your help.

Basically, drupal_get_form doesn't render the array - it just returns the renderable array from the form function. You need to render it yourself.

Try this:

function custom_shortcodes_shortcode_form($attrs, $text) {
  $form = drupal_get_form('custom_shortcodes_shortcode_form_attributes');
  $attrs = drupal_render($form);
  return $attrs;
}


When can I use a custom field type instead of a custom entity? I come from an SQL background and I'm still navigating fields/entities. I have a custom entity (analysis) to record information about a laboratory sample (what it is, when and where it was taken, and what analysis method was applied to it). The analysis will return many independent results. I was thinking of making a second entity (results) with an entity reference to the analysis entity, the name of the chemical that was measured, and the concentration that was measured.

However, could I instead make a custom field_type that is combination of the chemical name and its concentration? Then I could include this chemical_result as a field in my analysis entity with

->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)

to include multiple chemical results in one analysis, right?
When is it appropriate to use a custom field versus an entity?

I also have an entity called "chemical" that has information on chemicals of interest. If I use an entity for my results, I know I can make an entity_reference to the chemical entity, which would allow some more complex queries down the road. Can I do the same with a custom field? If not directly, I'm assuming I could program the add_analysis form to only allow certain values for chemical name  when adding data to the result field, correct?

Custom entities and custom fields are not mutually exclusive, you can use them together.

You can build a custom field type with more than one property. See for example the Password field which defines three properties:

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Field%21Plugin%21Field%21FieldType%21PasswordItem.php/function/PasswordItem%3A%3ApropertyDefinitions/8.2.x

You can also extend the entity references field. See for example the File field:

https://api.drupal.org/api/drupal/core%21modules%21file%21src%21Plugin%21Field%21FieldType%21FileItem.php/function/FileItem%3A%3ApropertyDefinitions/8.2.x

The File field adds two properties to the reference field. In your case you would add the properties chemical name and concentration to a reference field which points at the analysis entity.


Custom submit handler never gets called I want to check a data when an user submits a form. I set a custom submit handler in form alter, but my custom handler function never gets called. I don't understand why.

This is my code :

/**
 * Implements hook_form_alter().
 */
function custommodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
    if($form_id == "node_test_form") {
        kint("toto"); //toto is displayed when I load the form page
        $form_state->setSubmitHandlers(array("_custommodule_test"));
    }
}

function _custommodule_test(&$form, \Drupal\Core\Form\FormStateInterface $form_state){
    kint("mwahahaa?"); // never displayed
    die(); // doesn't work, the submit form page loaded successfully
}

I cleared cache, but the issue is still there.

Edit ##

I tested add a validate handler, the problem persists.. The code :

/**
 * Implements hook_form_alter().
 */
function custommodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id)
{
    if($form_id == "node_test_form") {
        kint("toto"); //toto is displayed when I load the form page
        $form_state->setSubmitHandlers(array("custommodule_myform_mysubmit"));
        $form_state->setValidateHandlers(array("custommodule_myform_myvalidate"));
        $form_state->getSubmitHandlers(); // display array("custommodule_myform_mysubmit")
        $form_state->getValidateHandlers(); // display array("custommodule_myform_myvalidate")
    }
}

function custommodule_myform_mysubmit(&$form, \Drupal\Core\Form\FormStateInterface $form_state){
    kint("submit ?"); // never displayed
    die(); // doesn't work, the submit form page loaded successfully
}

function ccustommodule_myform_myvalidate(&$form, \Drupal\Core\Form\FormStateInterface $form_state){
    kint("Validate ?"); // never displayed
    die(); // doesn't work, the submit form page loaded successfully
}

validate and submit handlers are added to the corresponding form element, e.g. $form['actions']['submit']['#submit'][] = 'foo'.  and same for #validate.

Honestly no idea what those methods are used for, never used them. Maybe internally, during form processing.

Also note that the node form currently has multiple submit buttons (save as published, unpublished and so on), so you'd probably need to add your submit to all of those.


How to automatically post a message with the discount on the site? I have a store with Commerce 2 and Drupal 8.

In my store I created a reminder of 20% on the whole site.

I want a message to be posted on my site with the conditions, the percentage, the end date and the description of the discount.

A bit like this :

How can I do this ?

Thank you

There is no tool for general messages like this, because every site will construct its front-end differently. If this is only an occasional matter, you'd be best just creating the content manually. If it's going to happen with some regularity, you may just be best using custom code to define a template that can load a promotion entity and fill in the offer details from its fields.


How to iterate over all field collection items in an eMail body using Rules? I'm trying to write a rule (using Rules) that will send an email to users of a role. Within the body of the email, I'd like to display the contents of a nested field collection.

I've tried using what Rules gives me for data selectors, but I can't seem to put it together. Specifically, I have two field collections: field-boat-lineup and field-equip-rowers.field-equip-rowersis actually nested withinfield-boat-lineup. The contents offield-boat-lineupare consistent. That is, their fields are fixed values except forfield-equip-rowers.field-equip-rowers` is variable and can consist of up to 8 user names.

Any pointers in the direction of how to display the contents of the field collections in the body of an email? Do I need to write some PHP code to make this happen? If so, what's the critical piece I'm missing?

On a side note, I find the field collection syntax used when working with the Rules data selector somewhat confusing. Specifically, the use of what appears to be an index. For example,

[node:field-boat-lineup:0:field-equip-boat-name:title]

I see the usage of a '0','1', '2', and '3' in the above token. I'm never quite sure what to select: 0, 1, 2, or, 3. Can anyone shed some light on the purpose of the numbers?

Update:

While I understand the example shown in the existing answer, I can't seem to conceptualize how I would be able to write a Rules "loop" to display the field collections in an email. The email body of the Rules module does not seem to have the ability to "loop" over content.

Part 1: Processing field collections in a rule

Consider a configuration with a field collection like so:

The machine name of the field collection is field_treatment_details, and the number of values for it is unlimited.
This field collection has 2 fields:

a text field labeled "Doelpubliek" (Dutch for "Target audience") with machine name field_doelpubliek.
a boolean field labeled "Betalend" (Dutch for "Payable") with machine name field_betalend.

Assume a node with "some number of" field collection items, with values that look like so (with some number = 2 in this case, but that could be any number as per the "unlimited" above):

Doelpubliek=Baby with Betalend=Nee
Doelpubliek=Moeder with Betalend=Ja

Let's assume you want to display these data via a Rule, using Rules Action "Set message", and using Rules Event "Content is viewed", so that such message looks like so:

This is a demo of a node containing a field collection ...

About this demo:

The machine name of the field collection is field_treatment_details, and the number of values for it is unlimited.
This field collection has 2 fields:

- a text field labeled Doelpubliek with machine name field_doelpubliek.
- a boolean field labeled Betalend with machine name field_betalend.

Part 1: The field collection with machine name 'field_treatment_details' looks like so:

Doelpubliek: Baby
Betalend:    Nee

Doelpubliek: Moeder
Betalend:    Ja

Part 2: The result of a Rules loop that iterates for each of the field collection items (using its unique ID) ...

The unique ID of the field collection item: 2
The host entity of this field collection item: 43
Field "field_doelpubliek": Baby
Field "field_betalend": Nee

The unique ID of the field collection item: 3
The host entity of this field collection item: 43
Field "field_doelpubliek": Moeder
Field "field_betalend": Ja

Here is the Rule (in Rules export format) that produced the above "message":

{ "rules_field_collection_demo" : {
    "LABEL" : "Field Collection Demo",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_view" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_treatment_details" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "\u003Ch2\u003EThis is a demo of a node containing a field collection ... \u003C\/h2\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EAbout this demo\u003C\/strong\u003E:\u003Cbr \/\u003E\r\n\u003Cbr \/\u003E\r\nThe machine name of the field collection is \u003Cstrong\u003Efield_treatment_details\u003C\/strong\u003E, and the number of values for it is unlimited.\u003Cbr \/\u003E\r\nThis field collection has 2 fields:\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n- a text field labeled \u003Cstrong\u003EDoelpubliek\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_doelpubliek\u003C\/strong\u003E.\u003Cbr \/\u003E\r\n- a boolean field labeled \u003Cstrong\u003EBetalend\u003C\/strong\u003E with machine name \u003Cstrong\u003Efield_betalend\u003C\/strong\u003E.\u003Cbr \/\u003E\u003Cbr \/\u003E\r\n\u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 1\u003C\/strong\u003E: The field collection with machine name \u003Cstrong\u003E\u0027field_treatment_details\u0027\u003C\/strong\u003E looks like so:\r\n\u003Chr \/\u003E\r\n[node:field_treatment_details]\r\n \u003Chr \/\u003E\r\n\u003Cstrong\u003EPart 2\u003C\/strong\u003E: The result of a \u003Cstrong\u003ERules loop\u003C\/strong\u003E that iterates for each of the field collection items (using its unique ID) ...\r\n\u003Chr \/\u003E" } },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-treatment-details" ] },
          "ITEM" : { "treatment_details_item" : "Treatment details item" },
          "DO" : [
            { "drupal_message" : { "message" : "The unique ID of the field collection item: [treatment-details-item:item-id]\u003Cbr \/\u003E\r\nThe host entity of this field collection item: [treatment-details-item:host]\u003Cbr \/\u003E\r\nField \u0022field_doelpubliek\u0022: [treatment-details-item:field-doelpubliek]\u003Cbr \/\u003E\r\nField \u0022field_betalend\u0022: [treatment-details-item:field-betalend]\u003Cbr \/\u003E\r\n\u003Chr \/\u003E" } }
          ]
        }
      }
    ]
  }
}

Admitted, this is a slightly simplified field collection configuration (no "nesting" involved). But apart from that it is similar to what you will need to specify in your Rules logic. Here are some more details to explain the above rule:

You need (repeat: need) a Rules Condition "Entity has field" (prior to being able to use it anywhere later on in your rule), which refers to your field collection field.
The 1st Rules Action (which produces the data below "Part 1" in the message) just displays the entire field collection, simply by referring to token [node:field_treatment_details].
The 2nd Rules Action (which produces the data below "Part 2" in the message) is simply a Rules "loop", which iterates over each of the field collection items (it uses a variable that I named treatment_details_item to actually display a message for each item). You will then be able to use any of the typical tokens (in the replacement patterns) related to that variable, such as how I used them to create my message I wanted to display, i.e.:

The unique ID of the field collection item: [treatment-details-item:item-id]

The host entity of this field collection item: [treatment-details-item:host]

Field "field_doelpubliek": [treatment-details-item:field-doelpubliek]

Field "field_betalend": [treatment-details-item:field-betalend]

Notice how, in the message I wanted my rule to display, I was able to refer to my "Doelpubliek" and "Betalend" fields (part of my field collection).

Part 2: Performing a loop within

After posting Part 1 of my answer, this "Update" got added to the end of the question (after it was first posted as a comment below this answer):

  While I understand the example shown in the existing answer, I can't seem to conceptualize how I would be able to write a Rules "loop" to display the field collections in an email. The email body of the rules module does not seem to have the ability to "loop" over content.

I think you're right about 'The email body of the rules module does not seem to have the ability to "loop" over content', or at least I've never discovered anything to do so. However, if what you're looking for is not available, then just make it available ... The trick to do so is similar to what is shown in the Rules example included in my answer to "How to concatenate all token values of a list in a single field within a Rules loop?". In your case, you could make it work like so:

Populate some new Rules variable before the Rules Action to send an eMail, say you name the variable field_collection_var_for_email_body. And the value of this variable should consist of a concatenation of the appropriate values of your nested field collection.
Within the Rules Action to send an eMail, you'll be able to select the token for field_collection_var_for_email_body to include anywhere in your eMail body.

Attention: even though it should technically possible to do all this in a single rule, such rule would possibly get pretty complicated to understand/maintain. That's why if it was up to me, I'd probably implement the Rules logic (as explained in this Part 2) in a separated Rules Component, which provides ... (cfr Rules Component terminology) field_collection_var_for_email_body!!!

Voilà ...

Happying Rules-ing! ... Also with (unlimitted) field collections ... even inside the body of an eMail created with a Rules action to Send an eMail.

PS: No need to write some PHP code to make this happen ...

PPS: For the newbies out there, it should look something like this:

Note that the fields are different here, and not the same as the example/scenario provided above.

Important: Make sure you select True for the uniqueness option in Add an item to a list, other wise this will trigger a bug that causes your fields to become empty or get readed multiple times. Once you get this bug, the only fix is to restore to a DB backup as you are not able to remove these fields even after turning off the Rule. Some more details about the bug (to avoid):

The bug causes the edit form field collection fields to disappear, while the fields do show up when viewing the node.
In another case, the bug causes the field collection field to be added over and over again. Also, when you click remove, the field doesn't get removed.


Mac to Windows Database issue I've been developing a Drupal site for over a year on my MacBook. The production server that the Drupal site will run on is Windows Server 2008 R2. As I try and load the SQL file from my MacBook, I'm getting this error from my MySQL client: "This file contains mixed linebreaks. They have been converted to Windows linebreaks." Then the import crashes. Can anyone share some tips with me on how to sucessfully migrate the Drupal database to Windows w/o carrying over assorted character/encoding problems?

Also-because the Drupal URL of the site on Windows is something other than "localhost", I end up having to edit the exported SQL file(s) either in TextMate (on Mac) or in Notepad++ (on Windows) to change the URLs. Could this also be contributing to the problem? I have also noticed in Sequel Pro that in the "field_data_body" table that there are hard returns everywhere. Is this normal?

Sorry if this is a dumb question, but I'm at my wits end and on a tight deadline. Thanks so much,

Jason

--Added on 2/9/14--

Here's some additional details related to my original question.

First, I realized that the Mac version of my database contains Windows line breaks (\r\n) and not OSX line breaks (\n). If my production MySQL server runs on Windows, should I even bother to try and convert the incorrect line breaks on my mac development site?
Importing using Backup & Migrate doesn't usually work from my Mac to my Windows server because the Windows server usually crashes. So I have to start the site off on Windows by importing the schema and data files separately. Schema imports fine, but the data file import encounters SQL errors from these issues: apostrophies in block of text (i.e., Drupal's, site's); brackets (i.e., 'Your membership request was approved for '[og_membership:group:label]' in an insert statement), anyplace where % or @ occurs.

I've tried putting a backslash before the offending characters in some tables, but don't want to do this for the whole data file. Is there something I'm doing wrong when exporting SQL files on my Mac that is causing these problems?

One thing I just remembered is that I had to uninstall and then reinstall MAMP on my Mac two weeks ago. Before this, I never encountered these type of import errors, on my Mac at least. I checked my MySQL config. file and the only difference is that I declared InnoDB as the default storage engine. I did not have this in my previous MAMP installation.

Thanks for any assistance.

Jason

First, I would suggest using the Backup and Migrate module to move Drupal databases between hosts. That may solve your line breaks issues, and YMMV, but loading Drupal dbs via other MySQL methods can cause other issues.

Second, have you tried setting the $base_url config variable on your production server? You shouldn't have to change URLs in the SQL files. It's a best practice to use relative paths in content. There are modules/filters that will convert them to absolute paths on the fly.

Cheers!


Open a specific View node with a link in an image I'm stumped. I'm not even sure how to ask the right questions to search out an answer.

What I have is a View of User Account images in a gallery. So far so good. I have another view of all User Account fields data presented as a node. So far so good there as well.

I want to click on the User Image in the gallery and go directly to that User's node in the other view.

The problem is not with attaching a URL to an image, but enabling sequential URLs to call the correct View node.

I feel like I'm missing some organizational overview understanding here. Maybe it's simple and I'm a doof.

Thanks for any insight.

From what I gather there are two possible approaches to this:

Either add a field for Link and then "Rewrite Results" to the content by referencing the node_id. Or do the rewrite on the image itself to the appropriate node_id. You might have to massage the urls for the other View or find a pattern to make this work.
Add a relationship to the gallery view to the Node that contains the UA fields. Add this relationship to the image field and then work it that way.

Hope this helps!


How to append #rss to each RSS feed item's URL built with Views? Problem

I have an RSS feed built with Views on a Drupal 7 installation. I want to append the following string to each feed item's URL but don't know how: "#rss"

For example, let's assume my RSS has a feed item linking to a blog post

http://www.example.com/blog/post.html

I would like to add the hashtag to the end of it, so I get

http://www.example.com/blog/post.html#rss

Why?

This hash tag will allow me to see who is visiting the site from my RSS feed as it'll appear on my Analytics program.

I could use Feedburner or other 3rd party feed tracking alternatives, but I am purposefully staying away from them, for reasons we don't need to go into.

Anyhoo, I only managed to get the Views RSS to work recently and have no idea how to modify the feed item URL. Can anyone help? Please assume I am a novice at this.

In the RSS view, look at the format section. If you're like me, you'll have the following

Format: RSS feed
Show: Content

Make sure to switch "Content" to "Fields", otherwise you won't ever see the "rewrite" options that the commentators keep mentioning above. Add all the necessary fields you'll need for the RSS feed.  You should get something like this (Ignore the field Hardcoded...)

Now, click on the "Content:Path" field (which you should've added), expand the "Rewrite Results" section, and tick the "Rewrite the output of this field" checkbox.
In the provided textbox, add your custom URL parameter. In my case, I wanted a hashtag, so I added the following:

[path]#rss

And, you're done! You may be asking, how did you know what to put in that textbox? Scroll down a bit and expand the "Replacement Patterns" section. You can add all types of stuff. I found this post useful. Of course, I discovered it after I had solved the problem. Still good to know.

Feels good solving my own problem, though special thanks to Remi who pointed me in the right direction.

It seems pretty obvious after the fact and maybe that's why no one wanted to actually write out an answer but for beginners like me, it's obscure. Anyway, I wrote this out in detail in the hopes you won't get stuck here. Hope it helps :)


User redirect after changing profile information I am having a problem trying to get the user to redirect to their profile page (user/uid) after they update their profile (user/uid/edit), I don't want them to remain on the page they just edited. I have looked high and low on drupal answers, google, and the documentation I can't get this to work.

Here is the code;

function form_redirect_form_alter(&$form, &$form_state, $form_id) {

    global $user;
    switch ($form_id) {
         case 'uprofile_node_form':
             $form_state['redirect'] = 'user/'.$user->uid;
             break;
    }
}

I have tried everything including a submit_handler and that doesn't work. I have tried including the base_url - doesn't work either. What am I overlooking. I figure that this should work.

I read somewhere online that redirects will not work if $form_state['storage']['values'] is not empty. If this is the problem, how would I overcome it?

Thanks.

There were a bunch of issues with your example, but this should work:

function YOURMODULE_form_alter(&$form, $form_state, $form_id) {

  switch($form_id) {

    case 'user_profile_form':

      $form['#redirect']='user/' . arg(1);
      break;

    // any other forms here

  }

}

which will redirect to the user page of the user being edited after editing that user.  This way, if an admin is editing another user, it redirects to that user's page, not that of the logged in admin.


What is the best way to show custom field information in node.tpl.php in Drupal 7 Hi I want to show in node.tpl.php this information about a custom filefield :
File name , File type , file weight and link to download

Something like this might demonstrate the fields available

<?php
$file = $node->field_yourfieldname[ $node->language ][0];
$mime = $file['filemime'];
$size = round($file['filesize'] / 1024 / 1024,1); // in MB
$description = $file['description']; // optional
$filename = $file['filename'];
$link = file_create_url($file['uri']);
?>

Hmmm, if $node's not available try something like this at the start

$file = $content['field_yourfieldname']['und'][0];


Field Permission Issue even without Field Permission Module I ran into a strange issue.

I have a content type with a field for user-reference (say XYZ). Now, I used the module nodeaccess_userreference to grant the referenced users in the field XYZ the permission to edit the node.

The edit button did show up and the referenced user was able to edit the content except for one field : "Body" field!!

I've no module for field permissions or anything like that. Why is it happening? All the fields are editable. I've been trying to debug the issue but so far no clue.

Kindly suggest what the problem might be or some approach to debug it.

I will update here as soon as I find some solution.

UPDATE:
The issue has been resolved. It was a text-format permissions issue. If anyone ever comes across such an issue, be sure to check your text-format permissions. They are the ones that never cross your mind.

Sorry to trouble you guys, but I figured it out just now. It was really a silly mistake from my side, but I had been hitting my head ever since.

Anyways, turned out that I had not provided the permission to the user for that particular text format!! The article was created by admin using "Full HTML" but the user had no permission for that format.

Anyways, I figured it out using a hack method which was really cool.

The text box was showing this message when it denied permission :

This field has been disabled because you do not have sufficient permissions to edit it.

I copied this and searched for this complete sentence in the contributed as well as core modules' directory. The "culprit" was filter.module. The function which was doing this was properly commented and said that "deny the users with no permission to the given text format".


Modify Userpoints List FormTo Show Entity ID? How does one modify the List used to display userpoints?

eg.

http://example.com/user/123/points

I'd like to be able to modify that (table) to display the Entity ID (the source transaction id).

Apparently, it is generated as a form/table in the Userpoints module, right? I think that SQL field is already part of the query. But is there a way to hook into that form and add columns without hacking the module? How is that done?

The form ID is userpoints-list-transactions

I see a hook in userpoints.api.php

function hook_userpoints_list_alter

so I created a function in my own module (which I know is loading and working for other functions)

 function jch_utilities_userpoints_list_alter(&$output) {
    dpm($output);
    }

...and it never fires. What am I doing wrong?

Do you have the Devel module installed? dpm() won't work without that.


Why can't I run krumo() on a node page? I called krumo() inside hook_node_load().

function mymodule1_node_load($nodes, $types) {
    krumo($nodes);
}

It works on my front page, but not on a node page. I get this error message:

  Fatal error: Call to undefined function krumo() in C:\wamp\vhosts\mydrupal72\sites\all\modules\my_customs\mymodule1\mymodule1.module on line 126

Why can't I run krumo() on a node page?

An option would be using module_load_include(). Manually making sure it's loaded


What exactly is the global context? I have been reading the documentation for module_load_include() and there's a warning that says:

  Do not use this function in a global context since it requires Drupal to be fully bootstrapped, use require_once DRUPAL_ROOT . '/path/file' instead.

Now I'm not sure what this "global context" means. I guess a page callback function is not in global context because I'd have to do a global $user to access the user entity. The only global context instance I can think of is in the index.php file at the root directory, but I don't think people normally  code on this file because it'd be "hacking" Drupal core.

Am I just missing the whole concept of global context as used in Drupal?

It means the global scope, ie anything outside a function and namespace. It's the PHP 'global', not anything specific to drupal.

People tend to use module_load_include at the top of .module files to bring in includes, much like in a traditional standalone PHP project.

This is potentially bad because the required elements might not have been bootstrapped at that point, which can lead to errors; hence the warning not to use it in a global context.


Cannot Change Max Upload Size in File Field From 8mb I have made changes to etc/php5/apache2/php.ini to increase max file upload size to 100mb but when I try to raise or lower the file upload size when creating a file field in a content type, it says that the current limit 8 MB even though the field saves the previous input. Anyone have any experience with this issue and could provide a solution?

There are three variables in php.ini that could be limiting your upload size.

Look for the following in php.ini:

memory_limit = 32M
upload_max_filesize = 10M
post_max_size = 20M

I imagine one of these is set to 8M in your case.

Also, you will most likely have to restart apache after making the change to php.ini.


Filtered View gives duplicates I'm creating a View that creates a page based on filters.

Filters are:

Published AND
Content: Type (= Student Resources) AND
Content: Resources Tag (Both or Prospective)

In the end, this should retrieve "Student Resources" that are Published and that have been tagged as either "Prospective" or "Both".  It does this without problem.  However, what it also does is show the output multiple times:

Only one of each of these content exist, but each is showing up 6 times.

Please help me troubleshoot.  What other information can I give you?

You can refer this article Remove Duplicate Views Results. Yo can use second option from that article.

Generally, it is done by the Enabling Aggregation: Yes under Views UI. This all has been mentioned at that link. Hope it will help.


How to fix special characters in node titles? When I imported content from my legacy system using the migrate module some special characters didn't get imported correctly.

For example the " character got changed to &#34;  and is showing as such in the node title.
Is there an easy option fix that when displaying or do I have to replace it at the database level?

Drupal does check_plain on titles which removes all html and does some conversion of chars (& -> &amp;). Depending on how the migration went, that could be part of the problem (escaping escaped content). But it's hard to say what the problem is without knowing what you actually got in the database.

Drupal uses the philosophy to store everything raw in the database, and escape it on output. If the legacy system did it differently, you could have the data stored differently than what Drupal expects, and would then need to fix it at the database layer.


disappeared comment fields in content type, how to put them back I'm working on a drupal page and recently encountered a problem when I couldn't enable comments on a certain content type. Looking for the problem I found that there were no fields for the comments in that content type.

I checked the other content types where comments were enabled without problems and checked which fields were enabled for the comments.
I tried to enable the comments in the first content type by adding an existing field for comments, but the comment fields were not available to choose.

Here i attach an image of what it looks like on the drupal (It's in spanish but I hope you can get the context)

This is how it should look like with the comment fields:

Is there a way to retrieve this fields so comments can be enabled for this content type?

Basing on the code for comment_field_extra_fields(), I think that what you are noting can be explained with the comment_subject_field_$type persistent variable being set to a value different from 1. ($type is the machine name of the content type.)

function comment_field_extra_fields() {
  $return = array();

  foreach (node_type_get_types() as $type) {
    if (variable_get('comment_subject_field_' . $type->type, 1) == 1) {
      $return['comment']['comment_node_' . $type->type] = array(
        'form' => array(
          'author' => array(
            'label' => t('Author'),
            'description' => t('Author textfield'),
            'weight' => -2,
          ),
          'subject' => array(
            'label' => t('Subject'),
            'description' => t('Subject textfield'),
            'weight' => -1,
          ),
        ),
      );
    }
  }

  return $return;
}

comment_form() contains the following code.

  $form['subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#maxlength' => 64,
    '#default_value' => $comment->subject,
    '#access' => variable_get('comment_subject_field_' . $node->type, 1) == 1,
    '#weight' => -1,
  );

Only when the 'comment_subject_field_' . $node->type persistent variable is set to 1 the users have access to that form field.

Changing the value of that persistent variable to 1 should restore those form fields you are expecting to see.


What does test status postponed for a patch on d.o mean? I've added a patch for the rules module. The patch detail page says the test status is postponed.

What does that exactly mean? Is there anything I should do to get the patch tested?

The problem is that the current Rules branch is currently failing an already commited test. While this should obviously not be possible, as tests should be green before they are commited, rare circumstances will cause this to happen from time to time.

Since an already existing test does fail, we know that testing with your new patch will also fail, whether your patch is correct or not. Thus all tests are postponed until the existing and breaking test is fixed.


Using drupal_add_content_region() I am trying to dynamically add content into a region.

In the preprocess function, I use the following code.

function firsttheme_preprocess_page(&$vars){
   drupal_add_region_content('dev', "I am reserved for development only");
}

In the template file, I print the region.

<?php if ($page['dev']) print render($page['dev']); ?>

Although I am setting some sontents in the dev region, it's always shown as empty array every time.

How do I fix this?

As with most things in Drupal someone else has already been there and done it...

http://api.drupal.org/api/drupal/includes!common.inc/function/drupal_add_region_content/7#comment-48353


Term reference translation I am using term reference in "select list" configuration. I do not know how to translate them, I have Taxonomy translation and Entity translation activated, but none of them worked.

Even I have already done the Field display translation settings and also the taxonomy translation settings!

Can you please give a guide? thank you

While adding vocabulary, you need to select third option for translate your     vocabulary and its terms. Ref. attached image.

After adding the terms and its translation, and configured term reference as a "select list", you can see there are both translated terms shows into select list while adding a content.

Hope it will be helpful.


How can I create internal links? Can someone please explain how site internal links work in Drupal? What is the most reliable way to display a link so that it goes to the same location every time?

I'm working on a preliminary website and right now, the only reliable way I can get a link to work the same way on all pages is to use absolute links (starting with http://and including the domain name for the host)  for each link. Since this website is currently local, this is not practical because I'll need to change all the links in the website when it goes live.

Eventually, I'd like to put these links in a menu I've got displayed at the top of all pages in my site.

In HTTP, links starting with http:// and including a domain name (e.g. http://example.com/foo/bar) is known as absolute paths.  On a Drupal site, they should only be used for off-site links.  Links not starting with http:// (e.g. /foo/bar) is known as relative paths. Relative paths should be used for internal links on your site. When a relative path starts with a slash (/) it is relative to the Drupal site root.  When it does not, it is relative to the location where it is embedded.

By making sure all internal links are specified using relative paths, they will not have to be changed when you move your site from one server to another.

For example, to link to /node/42, (provided you've clean URLs enabled) you can use the following markup:

 Link to node 42

(For menu items, as described bellow, you should omit the initial /, as menu items are always relative to the Drupal root.)

  Eventually, I'd like to put these links in a menu I've got displayed at the top of all pages in my site.

Support for this use case is already in place in Drupal.

Navigate to: Administration » Structure »  Menus and click on the link "List links" for the Main menu.  Then click on Add link.  In the field "Path" type in the relative path to the location (e.g. node path) in your site you want this menu item to point. Also provide meaningful "Menu link title" and "Description" strings.  End by clicking Save. Now the link will appear in your main menu, which in most (including the default "Bartik") themes are displayed at the top of all pages on the site.


draggableview on grouped taxonomy tag I have a content type with a taxonomy tag and some fields.

i use these content type in a view which groups the nodes by its tag and print out some fields.

now i want these tags in a specific order, which should be easily changed, e.g. by draggableviews and i also need the content under these tags in a specific order.
so i need a draggableview inside a draggableview... (yo dawg)
somehow...

is it somehow even possible to sort these tags and then sort the content in the tags?

Okay, found out it works when just applying one draggable view and sort a list of all nodes.
if the taxonomy tags are allready in the right order and are under another, the grouping will be sorted by the order of the nodes...

this is sufficient for me, but maybe someone has a better solution?


Centering pager for view using Bootstrap 3 I am using Drupal 7 and Bootstrap Business, which is a theme that utilizes Bootstrap 3. I have found that my pager in my views pages is not centered.
I know that Bootstrap 3 for non CMS work has a particular css markup that you use to center pagers, but in Drupal 7 there is no UI in the view that allows you to alter the css for the pager that the view uses.

Here is the non changeable html for the pager for a view in Drupal 7

1

2

3

4

5

6

7

8

9

…

next ›

last »

Bootstrap centers the pagination by wrapping it in a

There are definitely a few ways of doing something like this, only going to list the main two.

At the theme level you would want to override theme_pager in your template.php with special attention being paid on the return statement.

Original theme_pager() return (see link above):

return '
' . t('Pages') . '
' . theme('item_list', array(
  'items' => $items,
  'attributes' => array('class' => array('pager')),
));

Modified theme_pager() return to center pagination (taken from Bootstrap Theme):

return '
' . theme('item_list', array(
  'items' => $items,
  'attributes' => array('class' => array('pagination')),
)) . '
';

Looking at the code between these you can see that all that is added is the text-center wrap, plus the Bootstrap theme actually uses the pagination class from Bootstrap unlike Bootstrap Business (seems like a weird thing to say when I said it out loud).

I couldn't actually get the other CSS answer to work with the demo of the Bootstrap Business theme but that doesn't mean that it won't or is wrong per say. Just incase you have an issue with that one here is one that I got to work with the demo site:

ul.pager li a, ul.pager li.pager-current {
  display: inline-block;
}
.item-list ul.pager li {
  float: none;
}

That being said I would go with the way Bootstrap does this, it's already proven and holds up better than changing those lines of CSS I believe.


How to programmatically enable and set taxonomy access control for role I want to be able to programmatically enable and set taxonomy access control for the anonymous and authenticated roles. Specifically, I want to deny anonymous and authenticated users from being able to view or edit nodes tagged with a particular term. I know how to do this through the admin interface. But I'd like to be able to do this programmatically.

I can see functions to get the grants for a particular role, but not set them.

Thanks!

/**
 * Implements hook_node_access().
 */
function accommodation_node_access(\Drupal\node\NodeInterface $node, $op, \Drupal\Core\Session\AccountInterface $account) {
  if ($node->bundle() == 'accommodation' && \Drupal::currentUser()->isAuthenticated())  {
    if ($node->get('field_accommodation_category')->entity->getName() == 'Category 1') {
      return \Drupal\Core\Access\AccessResult::allowed();
    }

    return \Drupal\Core\Access\AccessResult::forbidden();
  }

  return \Drupal\Core\Access\AccessResult::neutral();
}


Using Webform Hooks to submit and display custom module forms? So i created my custom module form and submit handler...then realized i needed to use Webform hooks to save and hopefully view. Basically i wish for webform to manage the heavy lifting by taking care of the save and submissions.. also is it possible to save the values from the form as nodes or send them as emails? please any help is appreciated iv been staring at the webform API for days..

Webform has nothing to do with your form if you created it in a module.Your form is a form not a webform type node.
Form API! reference is what you need and to install Devel module

Then

dpm($form)

inside your form builder function to check which function is your #submit which is your #validate and add[] your own if you like

form values are stored in $form_state array
dpm($form_state) it also in your submit function and do whatever you want with these submitted values.

Store them in drupal database using variable_set() , mail them using drupal_mail() etc.

Some links

http://drupal.org/node/717740
http://api.drupal.org/api/examples/form_example%21form_example_tutorial.inc/7


The drush command 'migrate-manifest' could not be found Not sure if it's a dupe issue, couldn't find it. Just trying to run an upgrade in drush8 and get:

The drush command 'migrate-manifest' could not be found.  Run drush cache-clear drush to clear the commandfile cache if you have installed new extensions.

Tried with previous 8.* version and got the same problem.

answering my own question, this is now in the contrib module migrate-manifest:


Resizing image from one field and save result in another field As mentioned on the comments on this question, on my node-editing-form there are fields for WIDTH, HEIGHT, and an IMAGE. I would like to resize the given image by the dimesions WIDTH and HEIGHT and to save the result in another image field. I hope someone could outline (or even concretise) how to build that module.

have you seen Imagefield Focus?

This would give your users a much nicer UI to edit and crop images, and more importantly choose the correct regions to crop.


Rules to Flag a node referenced by Commerce Order Line Item I have a site selling edit access to specific nodes. The site uses Drupal 7, Commerce, Commerce License (selling a Role with edit permission), Rules and Flag.
On the Add to Cart I have a Line Item Entity Reference where the customer selects the Node they want access to. Upon payment a 12 month license is generated and the Role with edit permissions is added to the User. That all works fine.

Here's what I need:
When the payment is successful I need a Rule to trigger and set a Flag (premier_listing) on the Node that was selected during the Add to Cart process.
However I can't seem to access the Node Entity in Rules or access the Line Item Entity Reference that the User selected.
Anybody have an idea how this could be done?
Thanks

I believe you'll either need to access the node ID from the line item entity using a loop within the Rules UI or what I think a simpler way would be to create a custom Rule that accomplishes the same task.

Something like:
Event:  order is completed. I guess you could use order paid in full.
Conditions:  Here is where a custom condition would come into play.  You'd need to dig through the order line items to the user-selected node, and then pass that node_id to the Rules action as a parameter.  Note:  you could also do this entire check within the action and then programmatically set the flag to avoid passing the node_id as a parameter.
Actions:  Set a flag on a node.  (The node parameter).


Extending the content administration pages I have a lot of different content-types and many of them refer to other content-types.

In the administration it's becoming harder and harder to find a specific node, so I was thinking of writing my own theme and possible a module to make the administration easier.

It would be nice to have a free text search box in the administration, that would let one search for nodes of specific types.
Also in the listing of found nodes it would be great to be able to add specific fields so that you could see the relation between different content-types and so on.

Right now I'm using hook_menu to add a new page with a link link for each content-type, then in the callback I collect information about all nodes using a simple db_query call and then display the result using theme('table',...).

Can anyone point me to some tutorials on how to achive this?

I would recommend you to have a look at the Views Bulk Operations module. With VBO you can create custom views with any exposed filters and criteria you need. VBO adds to every row a checkbox which can fire different operations which you also can define on the view itself.


Generate a view with parent - child taxonomy terms Is there any way that I can create a view of parent-child taxonomy terms that would look alot like this? I was thinking I could use the parent relationship and then group terms and print in a grid but there is no options for parents to be a group field.

http://www.amazon.com/gp/site-directory/ref=nav_shopall_btn

I figured the answer. There is a relationship select box that appears on existing fields. I had to add twice the name field, make one of them use the parent relationship and exclude it from display and then use this as a grouping variable for the grid.


Views sorting with list item text I have a list field (category) associated with content type

Fruit|Good Fruit
Meal|Fantastic meal
Thai Coffee|Coffee

In views, I used sorting as category ascending. Now, I expected result to be sorted as: Coffee, Fantastic meal and Good Fruit. BUT it is sorting using value of list item as: Fruit, Meal and Thai Coffee.

Is there any way I can sort it using list item text but not with list item value?

Thank you.

The best way to accomplish this is to use a term reference field rather than a list field, for a number of reasons:

The taxonomy module is made specifically for categorizing things, so it's a natural fit for  a "Category" field.
You don't have to edit your Category field every time you want to add options; you can simply add more taxonomy terms. This is better for Features-driven development (assuming you've exported your fields to code).
You can sort by the taxonomy terms' titles in Views by using a Views relationship between the node and the term via the term reference field.

AFAIK, there is no way to sort by value labels in a list field like you're trying to do. I'd definitely recommend going with a term reference field instead.


Notifying drupal user on publishing I'd like to be able to notify a fellow publisher within the drupal permissions group that a new piece of content relevant to their page has been published. NOT an end-user alert, but just an internal alert on Drupal.

Sounds like a perfect use case for the Menu Badges module, which can be used to add notifications to any menu item and/or menu tab of your choice. Here are some details about it (from its project page):

Provides a method for adding iOS-style badges to menu items. (see screenshot)

Because of how it integrates with the Views module, you basically reduce the solution specific to your question here to something like this:

Create an appropriate view about "new pieces of content relevant to their page has been published" (as in your question).
And create a menu item or menu tab for it.
Grant access to that view for those users who fit "a fellow publisher within the Drupal permissions group" (as in your question).
Perform the required Menu Badges configuration to tell it which menu item/tab you used for it in your view.

Refer to the video Defining Menu Badges with Views in Drupal (from the module maintainer) for more details. It shows a scenario that might be close to what you'd want to implement also.
PS: I'm assuming this question is about D7 ...


Help Needed with a Hook_form_alter Module I've written the following module and it's not working. By that I mean it's not printing the #prefix to the webform above the 'resource_name' field. In fact, it's not printing it anywhere on the page. I'm trying to alter a webform-created node. I've already verified the form_id is correct as listed. And according to the webform the 'resource_name' is the field key for the field above which I want to place the #prefix markup. Any help is appreciated, thanks.

Note also that yes I've enabled the module.

    <?php

    function webformalter_form_alter(&$form, &$form_state, $form_id) {
      // Check when the right form is passed
      if ($form_id == ' webform_client_form_289') {

        // Add the directions
        $form['resource_name'] = array(
          '#prefix' => '
Do you know of a high-quality resource that should be in our
listings?

Please let us know! We will review it before publishing it, and we will
follow up with any questions.
',
        );
  }
}

I think your not setting the prefix correctly. I think you want to do something more like this:

if ($form_id == ' webform_client_form_289') {
    // Add the directions
    $form['submitted']['#prefix'] = '
Do you know of a high-quality resource that should be in our listings?

Please let us know! We will review it before publishing it, and we will follow up with any questions.
';
}

Looks like what your trying to do on in your code is set resource_name to be an array with just prefix in it.


Help with db_delete using both LIKE and IN.. I'm trying to delete many rows whilst having a wildcard I'm writing a custom cache clearing module for blocks.

At the moment, I can delete cache for one user and their multiple languages.

$uid = 7094;
$module = 'custom_home_panes';
$block = 'custom_home_panes_news_group';
$theme = 'framework';
$table = 'cache_block';

$cid_start = $module . ':' . $block . ':' . $theme . ':';
// Wildcard in middle for language code
$cid_end = ':u.' . $uid;

$delete = db_delete('cache_block')
  ->condition('cid', db_like($cid_start) . '%%' . db_like($cid_end), 'LIKE')
  ->execute();

But I'll need to do this for an array of UIDs and I believe I need to use IN like the snippet below..

->condition('uid', array(1,5,7),'IN')

I thought I could add what I did to an array and got this far.. The LIKE is really confusing me here and I think I'm going about it the wrong way.

foreach ($uids as $uid) {
    $queries[] = db_like($module . ':' . $block . ':' . $theme . ':') . '%%' . db_like(':u.' . $uid), 'LIKE';
}

The end result should be a query that removes records such as the ones below.

custom_home_panes:custom_home_panes_news_group:framework:vi:u.7250
custom_home_panes:custom_home_panes_news_group:framework:en:u.7250
custom_home_panes:custom_home_panes_news_group:framework:vi:u.7253
custom_home_panes:custom_home_panes_news_group:framework:en:u.7253

Any help appreciated.. My SQL skills are abysmal. Thanks!

You can't combine LIKE and IN in the way you are attempting.

You will need a run a different query for each UID.

E.g.

$cid_base_pattern = db_like($module) . ':' . db_like($block) . ':' . db_like($theme) . ':%:u.';

foreach ($uids as $uid) {
    db_delete('cache_block')
      ->condition('cid', $cid_base_pattern . $uid, 'LIKE')
      ->execute();
}


How to use Rules to auto populate field B with the value of field A after saving a new node or updating an existing one? This must be easy, but I just can't figure it out ...

My scenario is like so:

I have a content type with field A (title_field - text field) (that contains the title) and field B (field_tagged_as taxonomy reference).
I need to auto populate field B with the value from field A, after saving a new node or updating an existing node.

Is there a way to do this using the Rules module?

Here is a rule (in Rules export format) that does exactly what your question is about:

{ "rules_auto_populate_fields" : {
    "LABEL" : "Auto populate fields",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "title_field" } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_tagged_as" } }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "node:field-tagged-as" ],
          "value" : "[node:title-field]"
        }
      }
    ]
  }
}

Notice the "entity has field" conditions, for both fields. Those conditions will make the fields available in the Rules Action ... (so that you can reference field A and set the value of field B).

If you have the Rules UI enabled, and if the machine names of your fields are indeed "title_field" (for field A) and "field_tagged_as" (for field B), you should be able to just import this rule in your own site. If you're using other machine names, just adapt the machine names prior to importing this rule (and apply similar changes in the fields mentioned in the Rules Action).


Why is my sub-menu not loading in main menu? <div class="row" id="mainNav">
 <?php print theme('links__system_main_menu', array(
    'links' => $main_menu,
    'attributes' => array(
      'class' => 'menu',
    ),
  )); ?>
</div>

I've used the above code to load main menu in page template. This code fails to display submenus. Please suggest.

Go to /admin/structure/menu/manage/main-menu
Edit your parent link
Enable "Show as expanded" checkbox
(Repeat the same for all the parent links)
Go to the front page and see the main menu expanded.

Update:

You can use next code to render menu:

 $main_menu = variable_get('menu_main_links_source', 'main-menu');
 $tree = menu_tree($main_menu);
 print render($tree);


Get all the machine names of the date formats I have searched the Drupal documentation but until now I have not found the way to obtain the machine names of the date formats that the user creates from the Drupal administration.

They would be the formats that appear in the following route:

admin/config/regional/date-time

What would be the way to obtain them?
Is there any service for this?

Date formats are entities so you can use the Entity Type Manager service:

$formats = \Drupal::entityTypeManager()
  ->getStorage('date_format')
  ->loadMultiple();

$ids = array_keys($formats);


How do I effect the page that a menu item redirects to? I am trying to do something that seems simple, but I have yet to have to do it with my development because I have always dealt with forms and views.

On the page that I get redirected to when I click on a menu item, I want to have a page with a href on it.

So for example, I have created a menu item as follows:

$items['admin/vendor/auth-stripe'] = array(
        'title' => 'Authenticate Stripe Account',
        'description' => 'In order to receive payments, you must authenticate your Stripe Account.',
        //'page callback' => '_bh_vendor_auth_stripe',
        'access arguments' => array('vendor administration'),
        'type' => MENU_NORMAL_ITEM,
);

When I click on this menu item, I am taken to a page.  I want to add items to this page.  Namely an href link.

Do I need to create a block that only shows up on this page?  If so, how do I add a link on the page.  I know how to create a block programmatically using hook_block_info, but I am not exactly clear on putting content in this block programmatically.

hook_menu serves, among other things, to map paths onto callback functions.  Whatever function is marked as the page callback for that path will be responsible for returning a either a rendered string of HTML or a Drupal render array.  So, for your very simple use-case, you could do the following (assuming your module's name is bh_vendor):

function bh_vendor_menu() {
 $items['admin/vendor/auth-stripe'] = array(
        'title' => 'Authenticate Stripe Account',
        'description' => 'In order to receive payments, you must authenticate your Stripe Account.',
        'page callback' => '_bh_vendor_auth_stripe',
        'access arguments' => array('vendor administration'),
        'type' => MENU_NORMAL_ITEM,
 );
 return $items;
}

function _bh_vendor_auth_stripe() {
 return l('My link', 'my/path');
}

You could, in fact, define a block using hook_block_info() and hook_block_view(), then embed that block on your page by calling module_invoke('bh_vendor', 'block_view', 'yourblockdeltahere') but that really only makes sense if the stuff you're embedding is re-used elsewhere.  If it's only meant for this one page then you should stick the code to generate that markup in your page callback directly.

Another option, if this isn't for a module that's to be widely distributed and is only configuration for a specific site: use the Panels module.  You can create a panels page at a specific url (admin/vendor/auth-stripe) and embed whatever blocks/content you wish.  If you want it in code it is exportable and/or can integrate with Features.


How to hide a block or text if user can edit node? In a block there's a flag where users can ask for permission to edit the node. The admin gets a mail when the node is flagged. Admin can grant acces with node-acces to a particular user. This part is working.

However, when the user can edit the node, this block (or snippet; could use if else statement) should be hidden. I'm looking for (and can't find it) a snippet like

if user can edit
    {'you can edit'}
else
    {show flag}

How should I do the first part?

Seems it can be done via this PoC

if (node_access('edit', $node, $user)) {
  {'you can edit'}
}
else {
  {show flag}
}


How to deal with exploding node_access queries? I'm working on a pretty complex workflow site, which has a number of interlocking levels of components (content types, really).  To summarize and simplify a bit:

Users can create Companies.
Companies can have Projects and Members (other users affiliated with
the companies).
Projects can have tasks.

Each of these things have access controls::

Companies can be public, private, or member-only
Projects can be public, private, or member-only (but limited by the
company specification)
Tasks are member-only

This gets (more) complicated in a couple of ways:

Users can have different roles in Companies and Projects (admin,
user, visitor, and such)
The access rights of the higher-level thing can determine and even override the rights of the lower-level things: If a Project is marked member-only, that Project's tasks can only be seen by other members of the Company that owns the Project.  In the same way, changes to Company access rights determine the actual access rights of Projects and Tasks.  For instance, if a Company's status is changed from public to private, access to all its Projects and Tasks are blocked to everyone but the company's owner, even if they're marked Public.

I've gotten this working by setting up a collection of node_access functions for the various components.  These install appropriate access rights into the node_access table based on the components' access settings.  A parallel set of node_grants functions then build up comparable sets of grants for each of the users, based on their roles in the organization.

The good news is that this actually works.  The bad news is that the queries being run against the database are getting huge, as the node_access mechanism produces a very large number of query clauses, each looking to see how the user's roles line up against the various kinds of access rights.  For instance, there's a whole string of clauses testing, for each task, whether the user is a member of the project that contains that task.  There's then another string of clauses testing whether the user is an admin of the project, and another string testing whether the user is a visitor to the project.  And so on, leading to a future where these queries become larger and larger and worse and worse as the site becomes more successful and people put more projects and tasks into it.  Blurgh.

So (finally), my question: Is this just the inevitable cost of living with Drupal and its node_access architecture?  Is there another way I can control access to all these pieces of stuff without having the database calls explode on me the way they seem to be?  I'm not looking for a free lunch, but I'm getting more and more worried about the complexity of these access routines and the amount of money I'm likely to have to pour into database servers to keep things running.  Any advice out there?

I don't know how much of an answer this is, but: the approach I was taking to node_access that led to the original post was almost certainly wrong.  In particular, I was setting up separate gids for each item I was writing into node_access, rather than keeping gids associated with user IDs as they are almost surely meant to be.  After a bit of work, I was able to restructure this aspect of the site around this more correct approach, and was able to cut down the number of clauses added by node_access by about a factor of 10.  Life is a learning experience, I guess; I could probably elaborate a bit if anybody cares...


Module uninstall dependencies I'v got a question regarding dependencies & configuration. I created a module providing a content type, field type, widget & formatter.

While wanting to uninstall the module, I get the following message:

  The following reason prevents module from being uninstalled:

  Fields type(s) in use

So I go to structure, try to delete the content type & get the following:

  module's content type is used by x pieces of content on your site. You may not remove module's content type until you have removed all of the module's content type content.

I go delete all my nodes first as it seems this needs to be done first. I retry uninstalling the module & get message:

  Fields pending deletion

I run cron & am now able to uninstall my module with message:

  The following modules will be completely uninstalled from your site, and all data from these modules will be lost!

I can see that dependencies are met well, but this gives it a long run before one can uninstall a module.
Is there a way I can keep dependency integrity while once I am willing to uninstall the module to automatically remove configuration & content from start till end dependency?

You can, if you write the code for doing that yourself. Core currently doesn't offer a way to do that automatically.

See Impossible to uninstall Flag and the linked issue for Simplenews for inspiration.