Change in view hooks file name/location in core 8.3.x? I have a custom module that uses a couple of view hooks, and in 8.2.x I had them in my_module.views_execution.inc, in my module root directory. However, with the update to 8.3, my hooks are not being found. I'm looking at the 8.3 docs, but the incredibly verbose hooks overview page doesn't mention it, and neither does the page with the list of hooks.

So where do my view hooks need to be placed in 8.3 so they can be found?

I was finally able to get the hooks working again by putting them in the my_module.module file. I thought I read about that when I was first implementing these hooks when the site was still in 8.2, but it worked in the views_exection.incfile and not .module then. I haven't been able to find any documentation on this change so far, so if anyone could shed some light on it, I'd appreciate it.


How to put the Bootswatch theme locally? I  am using this sub-theme
and I can't find any help.

bootstrap-barrio-installation

barrio-starter-kit

I am currently using Bootswatch Flatly in CDN mode. I want to put everything locally.
Here is what I did:

I ran the following 2 commands on my server :

mkdir -p web/libraries/bootstrap
cp -R vendor/twbs/bootstrap/dist web/libraries/bootstrap

I modified the bootstrap_subtheme_front_office.info.yml file :

name: Bootstrap Subtheme Front Office
type: theme
description: 'SASS starter kit for a Bootstrap Barrio SubTheme.'
# version: VERSION
core: 8.x
core_version_requirement: ^8 || ^9
base theme: bootstrap_barrio

libraries:
  - bootstrap_subtheme_front_office/bootstrap
  - bootstrap_subtheme_front_office/global-styling
libraries-override:
  bootstrap_barrio/global-styling: true
  bootstrap_barrio/file: true
regions:
  navigation_collapsible_first: 'Navigation (Collapsible first)'
  navigation_collapsible_left: 'Navigation (Collapsible left)'
  navigation: 'Navigation'
  navigation_collapsible_right: 'Navigation (Collapsible right)'
  navigation_collapsible_second: 'Navigation (Collapsible second)'
  breadcrumb: 'Breadcrumb'
  header: 'Top Bar'
  sidebar_first: 'Primary'
  highlighted: 'Highlighted'
  help: 'Help'
  content: 'Content'
  sidebar_second: 'Secondary'
  footer: 'Footer'

# Information added by Drupal.org packaging script on 2020-10-11
version: '5.0.2'
project: 'bootstrap_subtheme_front_office'
datestamp: 1602444143

And I modified the bootstrap_subtheme_front_office.libraries.yml file :
global-styling:
  version: VERSION
  js:
    js/popper.min.js: {}
    js/bootstrap.min.js: {}
    js/barrio.js: {}
    js/custom.js: {}
    js/back-to-top.js: {}
    js/copy-to-clipboard.js: {}
  css:
    component:
      css/style.min.css: {}
  dependencies:
    - core/jquery
    - core/drupal
bootstrap:
  js:
    /libraries/bootstrap/dist/js/bootstrap.bundle.min.js: {}
  css:
    component:
      /libraries/bootstrap/dist/css/bootstrap.min.css: {}

I downloaded the 4 Bootswatch Flatly files to my computer:

I copied the 4 files in the folder
/libraries/bootswatch/dist/flatly

I executed the gulp and drush cr command.

MY PROBLEM
How to declare Bootswatch? Where to put the files?

The theme can not read the SCSS file. You have to covert them to CSS. To do this, follow the following instruction.

Create a new SCSS(Let's name it the "custom.scss") and import all the SCSS to this file. and convert it to CSS."
In the new "custom.scss" file, import the "_bootswatch.scss" and "_variables.scss". To do this, use the @import function. Add the following code to your "custom.scss".
@import 'bootswatch', 'variables';

Use a SCSS compiler to covert the SCSS to CSS.
Covert the "custom.scss" file to "custom.css", then minify the file to "custom.min.css".

On your "bootstrap_subtheme_front_office.libraries.yml" file, include the "custom.min.css". Add the following code below the "css/style.min.css: {}"
css/custom.min.css: {}


View sorting on hidden ID not Name I have a field in the View called Dealer Name. Dealer Name is populated from a list that looks like this:

#111 | Dealer 1
#112 | Dealer 3
#113 | Dealer 3

I need this field to be Alphabetically Sortable but when I apply sortable it sorts on the ID. What befuzzles me is that in the HTML only the Name is printed not the ID so how does it know to sort on the ID? (see below)

<td class="views-field views-field-field-da-dealer">
    Dealer Name
</td>

How can I change this behaviour to sort on the Name?

When you edit your view, you should see "Sort Criteria" at the bottom of the left column. I think it defaults to "Updated date". If anything is in this section, you'll probably want to delete it and then click on "Add" to pick the id as your real sort criterion.


What is the difference between a JOIN and a RELATIONSHIP in hook_views_data_alter() What is the difference between these two as implemented on hook_views_data_alter()? Why choose one over the other?

I did notice that in setting up a relationship between mytable1 and users tables, the Views UI gave me the option to add the mytable1.uid field under the relationship section, that way allows me to add users fields into the query.

What am I supposed to notice on the views-UI when I implement a join on a table? My implementation is as follows:

mymodule_views_data_alter(&$data){

    $data['mytable1']['table']['join']['users'] = array(
        'left_field' => 'uid',
        'field' => 'uid',
    );

}

I did this without a relationship setting, so I can observe the exclusive effect of each(join vs relationship)

From my experience, a join is always done when the query is executed. This means that you can utilise the fields on the joined tables without adding a relationship in the view. When a join is used, I don't think the views information tied to that table is pulled in. For example, you won't be able to add relationships tied to that table.

A relationship is a choice that the user can make on the view. They can choose to add the relationship (from the section on the right side of the view). When a relationship is added, the views information tied to that entity is also pulled in. For example, you will be able to add relationships linked to that table.


Remove Node Reference in the upcoming weeks my client want me change some node reference options on his page.

I got 2 content types, press release and press office.
When they create a new press release, they are able to reference to a press office via the "References" Module.

Now they want me to remove some of the press offices and add some new. Thats not the problem,  when I remove the old press offices the old nodes lose their references as well. But they want  the old nodes keep their references, which sounds logical to me, but I've no idea how to do that.

Greetings from germany

sg

If I'm clear, you don't actually want to remove any of the press offices because existing press releases should still be able to reference them, you just want to remove the option to associate new press releases with certain press offices (while at the same time, creating some new press offices that can be referenced).

So really, we just want to filter the list of press offices that can be referenced by new press releases.

I would suggest that you add a new boolean field to the press offices, something like: "Can be referenced". Then create a view that filters press offices on that field. Finally, configure your Entity Reference field Mode to use "Views: Filter by an entity reference view" and select the view you just created.


How to "disable" certain paragraph types? I am not sure if this is possible or not (which is why I have come to you fine folks), but I have searched for this and still haven't found an answer...

Is it possible to just "disable" paragraph types in a D8 site instead of deleting them? I know you can "disable" content types in D8 and D7, but I just want to disable some of the paragraph types that we have on our customer's sites without completely deleting them in case the need for them happens to come up from individual customers.

When I go to the full list of paragraph types, the only options that I'm given are:

Manage Fields
Manage Form
Manage Form Display
Manage Display
Edit
Delete

So, any help with this would be greatly appreciated, even if it's just to say, 'nope. not possible.' :)

Thank You!
Nicole

Sure this is. Per field. So let's say you have a "Paragraphs" field (field_paragraphs in the screenshot below) in the "Article" content type. Then you edit this field and there you have to select which paragraph types you want to include or exclude.


Check if node is displayed as page? In Drupal 6 to check if node is displayed as page we can use:

Select the condition to add - > Check a truth value

Truth value - > <?php echo $page ?>

How to do this in Rules 2.x for Drupal 7? I don't see the condition with name Check a truth value

Assuming I have interpreted what you're trying to do, try adding the Event "Content is viewed", with the Condition "Content is of type" and configure the Condition to be of node type: 'Page'. If you could explain exactly what you're trying to achieve I may be able to suggest a better solution!


Complex conditional logic for Webform field in YAML format I have a complex scenario in Webforms, where field #states depends on multiple OR / AND conditional logic.
For Example:
field_d has a visibility condition where field_a must be filled and either of field_b or field_c must be filled. I am not sure how to proceed with that kind of Yaml logic. I have tried something like below but it seems not to work.
field_d has below conditional logic under field advance tab -
visible:

  ':input[name="field_a"]':
      filled: true

  and

  (
  ':input[name="field_b"]':
      filled: true

  or

  ':input[name="field_c"]':
      filled: true
  )

Thanks.

Nested states can be tricky. Make it two conditions:
visible:
  - ':input[name="field_a"]':
      filled: true
    ':input[name="field_b"]':
      filled: true
  - or
  - ':input[name="field_a"]':
      filled: true
    ':input[name="field_c"]':
      filled: true


Notification of new comments for author and comment writers I'm trying to implement a rule (in D7) that will automatically (no check box or opting out):

send an email to the author of node if new comments
send email to all users who have commented on that node
not send email to author of own comment

I did find instructions for one of the above, but not for all of them in the same rules. And this is where I failed.

Any help?

Have a look at this rule (in Rules export format), which does what you're asking for:

{ "rules_notify_users_about_new_comment" : {
    "LABEL" : "Notify users about new comment",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional", "comment" ],
    "ON" : { "comment_insert" : [] },
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "list\u003Cuser\u003E" },
          "PROVIDE" : { "variable_added" : { "users_to_notify" : "Users to notify" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "comment:node:comments" ] },
          "ITEM" : { "current_comment_item" : "Current comment item" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT data_is" : {
                      "data" : [ "current-comment-item:author" ],
                      "value" : [ "comment:author" ]
                    }
                  },
                  "DO" : [
                    { "list_add" : {
                        "list" : [ "users-to-notify" ],
                        "item" : [ "current-comment-item:author" ],
                        "unique" : "1"
                      }
                    }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "comment:author" ], "value" : [ "comment:node:author" ] } },
            "DO" : [
              { "list_add" : {
                  "list" : [ "users-to-notify" ],
                  "item" : [ "comment:node:author" ],
                  "unique" : "1"
                }
              }
            ]
          }
        ]
      },
      { "LOOP" : {
          "USING" : { "list" : [ "users-to-notify" ] },
          "ITEM" : { "current_user_to_notify" : "Current user to notify" },
          "DO" : [
            { "mail" : {
                "to" : [ "current-user-to-notify:mail" ],
                "subject" : "New comment to node with id [comment:node:nid]",
                "message" : "There is a new comment added to the node with id [comment:node:nid]",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

I translate the "... in the same rules ..."-part of your question like "I want it to be a single (monolitic) rule". For that you'll need an additional module, i.e. the Conditional Rules module, while the above rule does use a few of the more advanced techniques available in the Rules module.

If you're familiar with reading/digesting Rules in Rules export format, I'd hope the rule is self explaining. If not here is a summary of the above rule:

Rules Event: obvious ... After saving a new comment.
Rules Conditions: feel free to add whatever fits (eg limit to selected content types only).
Rules Actions:

Add a variable "users_to_notify" (= a list of users).
Loop over all existing comments, and for each comment author, check that it is not the user who just created the comment (which you can check if you have the Conditional Rules module enabled). If that's the case, then add that user to the list of users (= users_to_notify).
If the comment author differs from the node author (which you can check if you have the Conditional Rules module enabled), then also add the node author to the list of users (= users_to_notify).
Loop over the list of users (= users_to_notify) ... again, which we just created and populated). And for each user in that list, do your thing, in this case "send an eMail". The "To" value is crucial here, the body, the from, the title, etc is up to your own imagination.

If you don't want to use the Conditional Rules module, you could also rework the Rules Actions that require this module to performing Rules Components (in which you add the appropriate Rules Conditions), so that you don't need this extra module (for more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?").

If you want, just import the above rule in your own site (using the Rules UI, which should be enabled to do so), but only after you enabled the Conditional Rules module.

That's really all it takes ... a Rules variable, Rules lists and loops, and Conditional Rules.

Note that the above rule does actually more as compared to what is asked here:

As per the "unique" in Rules Action nr 2, it will not create duplicates in that list of users, to avoid the same user would receive duplicate eMails (i.e. if a user commented multiple times).
As per the "unique" in Rules Action nr 3, it will not create duplicates in that list of users, to avoid the node author would get duplicate eMails (i.e. if the node author also commented already).
This rule will NOT send an eMail if the comment was posted by ... the node author (which seems to me like a contradiction in item 1. and 3. of the question ...). If you disagree on that (i.e. that it should send an eMail anyway: just delete Rules Action nr 3.

Unit testing the rule

If you want to (unit) test the above rule, you may want to add another Rules Action within Rules Action nr 4. I.e. add some sort of "Show a message on the site" (located within Rules group "System"), to produce a message for each user included the list of users (= users_to_notify).

That way, if for some reason your site has not been correctly configured yet to send eMails, those messages will help you confirm that the rule itself is not the cause of that.

Video tutorials

For anybody not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework, organized in 7 chapters. Especially these tutorials, which are related to subject of this question:

Notify author of comments.
Notify of comments replies.


Address field tokens and country display I have some user profiles with address fields attached. I created a view of these profiles, with the country as a contextual filter. I'm showing a summary of the results in one of my Views displays, so I can show the countries represented in my data set, with the number of matches for each:
US (12)
CA (6)
DE (3)
and so forth.
I'd prefer to be able to show these as country names rather than 2-letter codes (though the 2-letter code is useful for linking to another part of my view...)

Is there a way to get Views to output the country names in this scenario?
It does just fine when displaying them in fields or full content modes, but not in the result summary.

Any advice appreciated.

The addressfield_tokens module extends the addressfield module by adding full token support. It also adds some convenient addressfield formatters and provides a webform addressfield integration.

Addressfield Token Module


Combine multiple Fivestar rating fields into an average I'm building a rating site and using Views to display top rated (Fivestar + Voting-api) content -- but calculating what is top rated is where I'm lost now. Here's my View:

http://dl.dropbox.com/u/2188345/views-sorting.png

As you can see  I've got things nicely set up, they are sortable etc. but now I'd need to add a final column showing the average score of those three combined, per node. I first thought I'd achieve this easily by creating a views template, and it was ok partially, but sorting didn't work as one would expect (since values were summed on the fly, not before the actual sorting happens).

Is there some smart way to combine values of those three relations via Rewriting - or some other means?

Would Computed Field be of use to you here? You might need to duplicate the three ratings fields with a different output (and hide them) but then you should be able to do some calcs on the result.


Secondary navigation on pages I want to have navigation menu inside few pages on the left panel apart from the website's main menu on the top, and these menu items will be different for different pages. Is there a module for that?

Take a look at http://drupal.org/project/menu_block.  It allows you to slice up your menus and might do what you need.


Cannot find image properties when uploading I'm building an LXC based on an existing and working well website. I've checked that all settings where the same.
However, when I want to save a content after having uploaded an image on my LXC, I get the following error:

  PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer
  value.

I have thoroughly searched the web all the day to read every close topic but none gave me a suitable answer.

The fact is when the Field SQL Storage module try to get the properties of my image; it is unable to find its parameters, so the width and height properties are empty and the SQL query is crashing.

Why Drupal can't read my image properties and store them in database?

I finally found the answer. There was missing packages in my server configuration...I needed to install those :

aptitude install php-apc php-pear php5-curl php5-gd php5-mcrypt


How should I call a form in a theme? I read How do I find the search block form ID? several days ago. I want to use the answer given there in my project.

Where should I add this code in my project? Where can I find more information about it?

$form =\Drupal::service('class_resolver')-getInstanceFromDefinition('Drupal\mymodule\Form\Mymodule\SearchBlockForm');
$form->setFormIdentifier('some_custom_value');
return \Drupal::formBuilder()->getForm($form);

The key line of code here is this one:

$form->setFormIdentifier('some_custom_value');

Can you explain me what the code does?

As per the comments from Jaypan, the first thing to do is extending SearchBlockForm so you can give it a custom ID. Put the code in mymodule/src/Form/MymoduleSearchBlockForm.php.
Add the following code in the custom class (in this case, FoobarblkBlock) to create a custom block. Put the code in mymodule/src/Plugin/Block/FoobarblkBlock.php

/**
 * @file
 */
namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Creates a 'Foobar' Block
 * @Block(
 * id = "block_foobarblk",
 * admin_label = @Translation("Foo Bar block"),
 * )
 */
class FoobarblkBlock extends BlockBase {

    /**
     * {@inheritdoc}
     */
    public function build() {
      $form = \Drupal::service('class_resolver')->getInstanceFromDefinition('Drupal\mymodule\Form\MymoduleSearchBlockForm');
$form->setFormIdentifier('some_custom_value');

return \Drupal::formBuilder()->getForm($form);
}

Place the block in the required region.
The resulting form will be:

<form action="/search/node" method="get" id="search-block-form-some-custom-value" accept-charset="UTF-8">


How to provide template for particular view mode? I want to theme the search result view mode with a template.

I had it in my head that naming a template file node--article--search-result.tpl.php would do the trick, but I'm obviously wrong about that.

I realise I can do node--article.tpl.php and within this check $view_mode, but this is awkward with all the other view modes that I don't want to template.

Ideas?

Adding theme hook suggestions in a node preprocess function should do the trick:

function MYMODULE_preprocess_node(&$vars) {
  if ($vars['node']->type == 'article' && $vars['view_mode'] == 'search_result') {
    $vars['theme_hook_suggestions'][] = 'node__article__search_result';
  }
}

After clearing the caches you should be able to use node--article--search-result.tpl.php for your template file name.

NB. You could also do this in your theme's template.php file by calling the function MYTHEME_preprocess_node() instead.


Fatal error: Call to a member function diff() on a non-object I have an entityform that has a computed field.
In computed field,
I have to compute two time fields.

When I tried using this code that declares value for the two time field, it works fine

$timefrom = '06:00PM';
$timeto = '8:30PM';
$from = DateTime::createFromFormat('h:iA', $timefrom );
$to = DateTime::createFromFormat('h:iA', $timeto );

$ot_hour =  $to->diff($from);
$ot_minute =  $to->diff($from);
$hour = $ot_hour->format('%h');
$minute = $ot_minute->format('%i');
$hourtominute = $hour*60;
$total = ($hourtominute+$minute)/60;
$entity_field[0]['value'] = $total;

But when I used the variables from the entityform,

$timefrom_value = array_pop(field_get_items($entity_type, $entity, 'field_time_from'));
$timeto_value =array_pop(field_get_items($entity_type, $entity, 'field_time_to'));

$timefrom = $timefrom_value['value'];
$timeto = $timeto_value['value'];
$from1 = DateTime::createFromFormat('h:iA', $timefrom );
$to1 = DateTime::createFromFormat('h:iA', $timeto );

$ot_hour =  $to1->diff($from1);
$ot_minute =  $to1->diff($from1);
$hour = $ot_hour->format('%h');
$minute = $ot_minute->format('%i');
$hourtominute = $hour*60;
$total = ($hourtominute+$minute)/60;
$entity_field[0]['value'] = $total;

It show error "Fatal error: Call to a member function diff() on a non-object"

Why is this happening?
I need some help to solve this. thanks a lot!

It seems like you're getting confused with your $to and $to1 objects. There is typo in your code. Try this on your later code:

$ot_hour =  $to1->diff($from);
$ot_minute =  $to1->diff($from);
$hour = $ot_hour->format('%h');
$minute = $ot_minute->format('%i');
$hourtominute = $hour*60;
$total = ($hourtominute+$minute)/60;
$entity_field[0]['value'] = $total;


How do I add a prevent duplicate item RULE to my commerce site I am learning/working with RULES in my Drupal7 Commerce store.  I thought this would be a fairly simple rule to create, but I can't find a work around for my need.  I have a commerce site, that has our team uniforms.  Each member is entitled to one and only one patch.  If they add a second patch to their cart, I want a message to appear telling them that they can only have one patch in there cart and the add to cart process stopped.

So here is the scenario.

Click the Add to Cart button for first patch, order/item/patch goes
into cart
Click the Add to Cart button for a second patch, message
appears "you can't do that" and item does not go into cart

Where I am stuck is,  what to select in the RULES UI, so it will check to see what is in the cart, look at the sku or item number [both of these are unique to the item], determine if the item that is to be added a duplicate, if so, pop up warning message, do not continue the process of adding that item.

Any help would be greatly appreciated.

You're looking for the action 'commerce-order: commerce-line-items' in Rules as a way of inspecting and testing against what the user already has in their carts. The recipe outlined here goes through how to add this rule in and do some preliminary testing, I've tried to modify it for your use case:

Create rule, name it; Event: before adding a product to the cart
Add your conditions, ex. check if content is a patch
In Actions add Loop through commerce-order:commerce-line-items
Create component, single rule, name it
Create following variables of the component and name them as you wish:

Commerce line item (line item of the order from the loop of the main rule)
Commerce product (product added to the cart)

Add condition to the component: Entity has field, Entity: [line-item-in-order], Field: commerce_product. this will bring us the product from actual line item in current order (shopping cart).
Add condition to the component: Data comparison. Data to compare: line-item-in-order:commerce-product with product-added-to-cart -- This would be where you would determine if it is also a patch
Add action to the component: Remove an item from a list. List: [order:commerce-line-items], Item to remove: [line-item-in-order].
This will completely remove duplicated product from the shopping cart and from the order as well.
Eventually add another actions. At least Display some message to the user to inform him/her that the item has been removed sounds sensible.

Come back to your main rule created in step 1. Add action to the loop and select the component you have just created in steps 4. - 9. and set the variables.


Can I add a template preprocessor that's more specific than an existing hook? I have a preprocessor function in my model that runs on the views_view_table hook. I want it to be called only for a specific view. If it were a hook, rather than a preprocessor, I could use, for example views_view_table__myview. Can I do that with just the preprocessor, too, or do I have to register a matching hook? If so, how do I make sure it does exactly what the base hook does?

For the Views module, if you want to know its template file suggestions:

Open edit for your view
Click on 'Theme information'
Use whichever template name that meets requirements
Go back to your view and, at the bottom of 'Theme information', click 'Rescan template files'
Your template file should be highlighted in this list


Block form: radio buttons selection not saved I have a block form with 1 radio button and one text field.
The problem is the selection for the radio button is not saved: in blockSubmit $values['colour_select'] is empty.
The value of the text box is saved and working fine.
What is missing for the radio button?

Thank you

class UnitSiteIdentityBlock extends BlockBase implements BlockPluginInterface{
  public function build() {
    $config = $this->getConfiguration();
    $colour_select = $config['colour_select'];
    $custom_colour = $config['custom_colour'];
    return [
     '#theme' => 'folwell_unit_identity_block',
     '#colour_select' => $colour_select,
     '#custom_colour' => $custom_colour,
    ];
  }
  public function blockForm($form, FormStateInterface $form_state) {
    //$form = parent::blockForm($form, $form_state);
    $config = $this->getConfiguration();
    $form['colour_select'] = [
      '#type' => 'radios',
      '#title' => $this->t('Pick a colour'),
      '#options' => [
        'white' => $this->t('White'),
        'black' => $this->t('Black'),
        'other' => $this->t('Other'),
      ],
      '#attributes' => [
        'name' => 'field_select_colour',
      ],
      '#default_value' => $config['colour_select'],
    ];
    $form['custom_colour'] = [
      '#type' => 'textfield',
      '#size' => '60',
      '#placeholder' => 'Enter favourite colour',
      '#attributes' => [
        'id' => 'custom-colour',
      ],
      '#default_value' => $config['custom_colour'],
    ];
    return $form;
  }
  public function blockSubmit($form, FormStateInterface $form_state) {
    //parent::blockSubmit($form, $form_state);
    $values = $form_state->getValues();
    foreach ($values as $key => $value) {
      \Drupal::messenger()->addMessage($key . ': ' . $value);
    }
    $this->configuration['colour_select'] = $values['colour_select'];
    $this->configuration['custom_colour'] = $values['custom_colour'];
  }
}

I found the problem with this: it was the name attribute. As soon as I removed it, $values['colour_select'] stored the selected color.


field_get_items gives me an array of node IDs. Can I filter these by type without using node_load()? I have an entity reference user field for more than one content type. I need to filter the node IDs by content type without using node_load(). Is it possible?

If not, how badly would it affect performance to send the user ID to a view and filter them there?

Unless you have a map of those ids -> types somewhere outside the DB to reference, no, it's not possible. You could go directly into the node table yourself, of course, and avoid node_load specifically, but there's no way to do it without a db hit.

It's impossible to say how performant a View would be without knowing how your site is built, server specs, traffic info, and so on. The best thing to do would be to try it and benchmark.


How to make user profile page display extra fields in drupal 7? I have added some extra fields to users under admin/people/ - when I click edit beside the user, I can see the extra fields I have added.

However, if I go to /user/ those fields are not displayed.

How do I display user profile fields when their profile is viewed at /user?

You most likely added the fields through this admin page:
admin/config/people/accounts/fields

To control which fields are actually displayed on the view page, go here:
admin/config/people/accounts/display

Also if you have the Field Permissions module enabled, make sure all necessary roles have the permission to view the fields you've added.


node_load_multiple does not respect node access grants I used $nodes = node_load_multiple(NULL, array("title" => "Foo Bar")); to fetch nodes by titles. But after going through Drupal security standards, node_load_multiple is not the right way to load all nodes.

node_load_multiple() will load ALL nodes regardless of access, so that must not be used here.

Solution suggestion is:

  Use an entity query instead. "When adding a node listing to your
  module, be sure to use an entity query, which will add a tag of
  "node_access". This will allow modules dealing with node access to
  ensure only nodes to which the user has access are retrieved"

But I'm not sure how to apply above statement programmaticly?

Is below query the right way that solves security issues?

\Drupal\node\Entity\Node::loadMultiple(NULL, array("title" => "Foo Bar"));

If not, please suggest an appropriate alternate of loading nodes by title that respects node access grants.

You can do it like this. First, query the NIDs, with a query that is tagged for node access, then load the nodes with the found NIDs.

$nids = db_select('node_field_data', 'n')
  ->fields('n', ['nid'])
  ->condition('title', $my_title)
  // The node_access tag will check access rights.
  ->addTag('node_access')
  ->execute()
  ->fetchCol();

$nodes = Node::loadMultiple($nids);

Untested in D8, but it should work.


Image preview not showing on add/edit page Preview of the uploaded images are not showing on the node add/edit page but images are uploaded correctly. We're using Lightning Acquia distribution and using Entity browser for the image field.

What could be the possible issue?

This is a known issue in the current version of entity_browser that ships with Lightning.  Upgrade the entity_browser module to 8.x-1.0-alpha10 or later to resolve the issue.

If you have used composer to install, simply update the drupal/entity_browser module via composer.


How to disable one sort/direction combination from a combined Better Exposed Filters field? Over at this previous question I figured out how to give a view a list of options that look like this:

  Sort by

  Date - Newest
  Date - Oldest
  Price - Highest
  Price - Lowest

Suppose there was a particular sort order combination of sort option and sort direction that didn't make any sense. For example, imagine an "Editor's Choice" sort, where staff apply a rating to products to give the best products a boost.

This makes sense:

  Sort by

  Editor's choice
  Date - Newest
  Date - Oldest
  Price - Highest
  Price - Lowest

This is just a bit strange:

  Sort by

  Editor's choice - most favoured
  Editor's choice - not favoured
  Date - Newest
  Date - Oldest
  Price - Highest
  Price - Lowest

...not least because 50%+ of products will be equally at the bottom of the "not favoured" list. This sort might also give the misleading impression that the product at the top of the "not favoured" list has something wrong with it, when actually it's equally not-singled-out-for-praise with 50% or more of the shop.

What I'm currently doing, is the brute force approach - using CSS to set the option based on 'Editor's choice Ascending' to display: none;. I don't like this, because the wrappers mean I have to use first/nth child selectors which could mean the option gets hidden in future after a seemingly inconsequential update or views config change.

Is there a more stable way to properly remove this option from the form?

I can't find a way to do it through Views or Better Exposed Filters settings, but I have found a way through hook_form_alter() in the theme template.php file:

Something like this, specific array keys are based on using the BEF combine option and may vary:

function YOURTHEME_form_alter(&$form, $form_state, $form_id){
  switch ($form_id)
  case 'views_exposed_form':
    if($form['#id'] == 'views-exposed-form-VIEWID-DISPLAYID'){
      if( isset($form['sort_bef_combine']['#options']['field_FIELDNAME ASC']) ){
        $form['sort_bef_combine']['#hidden_options']['field_FIELDNAME ASC'] = $form['sort_bef_combine']['#options']['field_FIELDNAME ASC'];
        unset($form['sort_bef_combine']['#options']['field_FIELDNAME ASC']);
      }
    }
  break;
  }
}


What is the difference between the config and the settings directories? I can see a folder named config in Drupal 8 core modules which contains sub directories like optional, schema and install.

I can see it is like a settings folder which is initialised during module installation. But how do they differ from each other?

schema
This folder is used for schema related things. This is most often used to tell Drupal how custom configurations and configuration entities will be saved.
install
The folder can contain configurations, for example a view. All configurations will be installed; if any configuration fails, the module can't be installed.
optional
The folder can contain configurations, for example a view. All configurations will be installed if possible. If a configuration has missing dependencies, it won't be installed.

Configuration installation only happens when the module itself is installed. Optional configurations can install missing configurations when dependencies are met by a new installed module.


Change search results pager to mini pager? How to change search result's pager to mini pager. I want to change default pager to mini pager in that search result page. Please help me. Thank you.

you can override   template_preprocess_search_results in your template.php and
instead

   $variables['pager'] = theme('pager', array('tags' => NULL));

use

   $variables['pager'] = theme('views_mini_pager',array('tags' => NULL));

( just make sure you installed views module)
also this question can get you some clue

How do I customize the search result page?


How do I add a class to the search block form? I want to add a class to the <form> element on the form_id 'search_block_form'

this is my current code

function THEME_form_search_block_form_alter(&$form, &$form_state, $form_id) {
  $form['#attributes']['class'][] = 'form-inline ';

}

You can use the template_preprocess_form

function THEMENAME_preprocess_form(&$vars) {
  // Add class to your specific form
  if ($vars['attributes']['id'] == 'search-block-form') {
    $vars['attributes']['class'][] = 'form-inline ';
  }
}

NOTE: the preprocessor you are using adds class to the block element


How to make a block showing the content entity the author of the node is linked to? I have a 'business' content type and an 'information' content type on my page.
The author of the business is the webmaster and from the information the authors are the users of the site. The contenttype 'business' has an entity reference field targeting the users linked to that business

On the 'business' pages there is a block showing the 'information'articles published by the users linked to that specific business. So far no problem.

I would like to have a block on the 'information' pages showing the business the author of that node/article is linked to. The author of the contenttype business is always the webmaster and the author of the article is the user. I think that I don't understand the relationship that I must make to get this correct. The block has to look at the author of the node where the block is displayed and see the business where that user is linked to.

I'm completely blocked getting that done. I'm new to Drupal, there were no serious problems so far. But this I can't get done.I'm missing something in the contextual filters and relationships.

You've stumbled into the issue of Context. Blocks can be placed anywhere, and has a very limited concept of context (the only context that Blocks know of are logged in user, and parameters taken from the url).

Normally one will use CTools (the Context specialist) and Panels to solve this type of problem. You are lucky in that Views has a relationship that can solve it for you.

Construct your block as follow:

Type Content, filtered by content type Information.

Contextual filter:

Content: Nid (The node ID.), no relationship, and for WHEN THE FILTER VALUE IS NOT AVAILABLE you add Content ID from URL

Relationships:

Content: Author (Relate content to the user who created it.), and Require this relationship
Entity Reference: Referencing entity (A bridge to the Content entity that is referencing User via field_users - Your field will be differently named, mine is field_users). Set the relationship to 'author' (the first relationship added), and Require this relationship.

Fields:

I assume you are adding the node title. Make sure to set the relationship to: Content referencing Users from field_users (the 2nd relationship you added - yours will be named slightly different)

If you add any other fields make sure to set the relationship as well.

If you find that it lists any duplicates, just go to OTHER in views, and under Query Settings, set it to Distinct (I'm sure this won't be necessary though).


How to customize welcome email Could anyone show me how to customize welcome email in Drupal 8, as I spend a lot of time trying to get it done.

I've already tried in Back Office but Drupal seems to ignore it totally.

Navigate to /admin/config/people/accounts and scroll to the bottom.


Problem with i18n_string + features + sites with different default language (I will talk about i18nviews in this question, but I think the problem applies equally to other cases of i18n_string)

Background

With regular Drupal t(), Drupal will always assume that the original string is in English.

With i18n_string, it is assumed that the original string is in the site default language.

Use case / problem

I have multisite with two sites, one with default language German, another with default language English.

I created a page view on the German site, with a page title "Produkte finden".

I exported this view as a feature, and want to enable this feature on the English site. On the English site, the page title should be "Find products".

I thought I can use i18nviews (which uses i18n_string) to translate the page title configured in the view.

However:

In the German site, Drupal thinks that the exported page title is in German.
In the English site, Drupal thinks that the exported page title is in English.

This means that Drupal will never attempt to translate the views page title. So I would get the same, non-localized page title on each site.

Question

I want to find a way to export a view into a feature that can be installed on sites with different default language, and have localized labels on each site.

If this can be done with i18n_string, great. If not, I am open for other suggestions.

Thoughts

I think to make this work, the exported feature would have to contain information about the language with which it was exported, which could then be picked up by i18n_string (which I assume it is not really capable of atm).

Or all sites would need to have default language = English.

My solution:

Do not enable i18nviews.
Create all views with English strings.
Use the core translation system to translate all those strings.
Optionally, use features_translations to export translations.

I do not claim that this solution works for all cases where i18n_string assumed source language causes trouble. But in this case it seems to be sufficient.


how to make node data available in the page.tpl.php I want to be able to print the contents of my node tpl up into the outer page region, accessible via the page.tpl.php (or an override). How exactly can I do this?

I originally thought about doing a variable_set in the node.tpl and then getting it in the page.tpl. However, if this would work, I would need to be able to create a template. I tried page--node--gallery-photo.tpl.php, but it doesn't seem to be the correct override.

What this the best way to do what I need to do here?

If you are on Drupal 7 you can edit your theme's template.php and add (or edit) the function

function <YOUR_THEME_NAME>_preprocess_page(&$vars) {
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

The same task in Drupal 6 is accomplished by adding/editing in template.php

function <YOUR_THEME_NAME>_preprocess_page(&$variables) {
  if (isset($variables['node']->type)) {
    $variables['template_files'][] = "page-" . $variables['node']->type;
  }
}

Then you can add page--<YOUR_CONTENT_TYPE_MACHINE_NAME>.tpl.php (or page-<YOUR_CONTENT_TYPE_MACHINE_NAME>.tpl.php in Drupal 6)  to your theme. Remember to clear the theme cache.


Two select field cck field I need to implement two select field in a content type.Currently cck modules allows only one select field. So how can I implement two select fields using cck.

Eg:- select field value for months and year.

Tks in adv
Vil

Try Date module. This provides the cck widget to select the date.

The Select List date widget presents users with a drop-down list or textfield for each part of the date (year, month, day, hour, etc.). The whole selector is collapsed onto a single line using css (except for the timezone selector, if date-specific timezones are collected). The selector is highly configurable and you can set it up to use 5, 10, or 15 minute increments for minutes and seconds, or make some parts of the selector use textfields instead of drop-downs, useful to allow any year without creating a huge drop-down selector.

For more Documentation See here


How do I name a theme file for view? I am trying to theme a block from my view.  I have a view called slides and it is creating a block.  I have a template file I want this block to use.  I have looked at the documentation for themes and the pattern to follow is

views-block--<viewname>.html.twig

or

block--views-block--<viewname>-displayid.html.twig

I can't find displayid for my block so I am trying to get that first option to work, but No matter what I do my block wont seem to take on the template I have written.

my template is named

views-block--slideshow.html.twig

What am I doing wrong with my names?

In your development.services.yaml file set twig debug to true and disable the cache by setting value to false.

After that you will see theme suggestions by inspecting element in browser.


Need to add media with embed code and NOT URL - how to do it? I'm trying to create an embedded soundcloud field in my drupal site but the embed is coming out too LARGE. In Soundcloud you can make the embed code reflect a smaller value in the sharing options, but there's no way to save it.

I can't find a way to actually use embed code in drupal. I've added the media module and the embedded media field module and the soundcloud module and the oEmbed module. None of them let me add embed code - they just accept a URL (and in fact they make me put the URL in twice for some reason). But the point is, they don't let me add embed code and I need to be able to add and tweak the embed code itself, not just add by URL.

I looked here and that doesn't help: how to add a cck field for youtube embed code?

Anyone know how to do this?

Create a new field on your content type called "Embed code", and create a new text format called "code" where HTML is allowed, and no WYSIWYG modules are enabled.

Use css to change the width and height of the iframe of the soundcloud widget. it will adapt automatically.

More control Using Views:

Hide that field from display on the "manage display" tab of your content type.
Create a view block display.
In that view, bring in the embed code field.
Add a contextual filter to the view. Use the nid and provide a default value "content ID from URL".
Place the block on your page.


How to create drop down while the menu structure is in array type? I have created menus with sub-menus in the header.

It is supported by some themes .

But some themes don't support this. e.g Bartik, fontfolio etc.

I want to use the drop down as customized in the main-menu region, so as to display in these themes also.

How can I edit this in the drupal page.tpl?

As I am new to drupal, please suggest me.

E.g Dropdown not Supported in this format:

    <?php print theme('links__system_main_menu', array(
      'links' => $main_menu,
      'attributes' => array(
        'id' => 'menu',
        'class' => array('links', 'inline', 'clearfix', 'menu'),
      ),
      'heading' => array(
        'text' => t('Menu'),
        'level' => 'h2',
        'class' => array('element-invisible'),
      )));
    ?>

I have found some possible answers related to your solution.

SOLUTION 1:

The main menu in Bartik only displays the first level. Since it's hardcoded in page.tpl.php there's nothing you can do about it.

Here's how to get the menu to work properly:

In your theme settings (admin/appearance/settings/bartik) disable "Main menu".
Go to admin/structure/block and add the "Main Menu" block to the header region (or wherever you want it).

Alternatively, you can also check out the excellent Menu Block module, which generates extra customizable blocks (1st level, 2nd level, etc) for each menu.

SOLUTION 2:

There are some useful resources that may help you to solve your problem.

How to create a drop down menu in bartik theme
Drupal 7 + Bartik + Dropdown for Main Menu Children
Add drop down menu support to Bartik
Drupal Responsive Bartik Theme with Dropdown Menus


Problem with cookie and session cache I have a problem with the Drupal cache. The cache remembers session and cookie values. Everything works fine when I'm logged in or when I completely turn off any cache.
Is it possible to use cookies and avoid they are cached for anonymous users?

First of all, you need to add the correct cache context when rendering cookie/session values. See https://www.drupal.org/docs/drupal-apis/cache-api/cache-contexts. Then you should no longer need to completely turn off caching and sessions should work fine, anonymous and logged in.
Using non-session cookies server-side can be a problem with reverse proxies in general and the built-in Internal Page Cache in specific. Disable it by triggering the kill switch on pages depending on cookies without a session:
\Drupal::service('page_cache_kill_switch')->trigger();

Don't use this trigger too often, it disables all page caching. If you need it on the majority of your pages then uninstall the Internal Page Cache, but keep the Internal Dynamic Page Cache enabled. If the dynamic page cache is too slow then put a third-party page cache in front which has the options you need to manage your cookies.


Drupal 6 + Twitter Bootstrap 3 theme I need help in setting up bootstrap 3 theme with Drupal 6.

With a lot of research I found that we have BootStrap module that supports D7 . Can anyone tell me how I can use Bootstrap in Drupal 6?

Prerit,

I think there is indeed one custom port to BS3 and that can be used in Drupal 6. Follow post #3 to get the idea. However, this is a custom theme made by an Drupal developer and its not in the drupal's project yet.
FYI, it does support jQuery version 1.7.2 by un-setting the default jquery 1.2.6 version which intern may break some functionality in your site.
The link to the Github Repo.

Personally I would suggest to use Zen or Omega for a Drupal 6.x site.


How do I hook into t()? Drupal uses t() in various places. I was wondering if there was a way to hook into this function. Basically, if Drupal calls:

t("some string");

I wanted to modify this string and add "BOOM" at the end. I was hoping it would be as easy as this

function mymodule_t($string)
{
   return $string.'BOOM';
}

But no luck... any ideas on how to get this right?

AFAIK Drupal's t() function does not provide any hooks for neither altering its input values nor its results.

However, if your intention is to override specific translations of the locale module, you can alter them within the translation interface of Drupal at '/admin/config/regional/translate/translate'.

If you don't want to alter the database stored locale translations, or don't have the locale module enabled, you can also provide according overrides within your settings.php by defining $conf['locale_custom_strings_' . TARGET_LANGUAGE][CONTEXT]. Replace TARGET_LANGUAGE with the target language shortcut, and CONTEXT with the context of the translation (usually an empty string):

$conf['locale_custom_strings_en'][''] = array(
  'some string' => 'some stringBOOM',
);


Code in URLs despite clean URLs turned on The site I'm working on, shows the URL like this: http://www.sitename.com/page-name#.Uad4adKmjoY

It shows "#.Uad4adKmjoY" at the end of url, even though I've enabled the clean urls.

Anyone know why it is showing this? I've not come across this before.

According to this posting on StackOwerflow and this one on Drupal Answers, these appear if there is Javascript in place to add "AddThis" tracking to the website.  They do no harm, and if it's not your site, you should leave them alone.

(Note that this has nothing to do with clean URLs in Drupal.  Drupal's clean URLs changes things like example.com/?q=node/123 into  example.com/node/123.  It does nothing with hashmarks added to URLs.)


Drupal 8: Rendeirng node fields in another region my content type contains several fields; body, field_meta_tags, field_image, field_date, etc.

In node.html.twig, using the without filter, I can replace the standard rendering of {{ content }} with {{ content|without('field_image') }} and all of the content, less the image, will display.

How can I expose this variable to another region and render the image through a different template, perhaps region--hero-image.html.twig?

Thanks!

Easiest way to do this is create a View with a block display, and set the node ID as the contextual filter. The output of the View should be "Content" and a view mode - this view mode can be set with its own twig template in the theme. You can add a view mode at Admin > Structure > Display Modes > View Modes, then go to whatever content type you need it for and configure the display. On the view mode, you can pick and chose what fields should display and what formatters they use.

Here is a good write up detailing it, and a YouTube video walking through view modes and what they are.

Once the View is created, you can place the block in the block admin, and set its visibility settings to only show on your content type(s) that you configured.


Help understanding how to modify lay out of pages within drupal I have built my website locally and I am trying to have three pictures display on all pages of the website. Those three pictures need to be on one line:

Now I have the pictures as such:

picture 1
picture 2
picture 3

I need:

  picture 1, picture 2, picture 3

I understand that I need to create a css file that will alter the structure of all the pages to display the pictures. I have done that following example on the net.

.field-type-image {
  float: left;
  padding-left:20px;
}

Now I have edited the .info file of my website to link the style.css but the pictures are still not showing the way I want. Moreover, they are only showing on one page.

What am I missing here ?

I have used firebug to try to find the css page on which I could have made the change for the pictures to appear but there were none. That is why I decided to create the style.css

I assume you are embedding the images in a block which you then show on all your pages.

If you reference a background-image from your style sheet as in url(../images/hello.jpg) all works fine because the style sheet, no matter what page you are looking at, references images from the style sheet directory as a base . If you embed an image tag on a page your img url will not be correct for pages of different depths as the page's url changes, and it is the page url that is the base. You have two quick solutions:

Pathalogic module - it is a text input filter that will rewrite
your embedded anchor and image paths automatically
PHP Filter - It is also a text input filter. Rewrite the path using the l() function, or concatenate it onto $base_url in a PHP snippet. This method is not preferred and support for the PHP Filter has been dropped in Drupal 8.

And as to the css and theming problems:

Marinelli is using a 960 grid system. There are lots of information on the web available on that and I suggest you read up on that.

In short, you must add appropriate classes to your images which will then take care of the css on your behalf. To float 3 images horizontally you need to add the following classes to your images.

image 1. class="alpha grid_4"
image 2. class="grid_4"
image 3. class="grid_4 omega"

And depending on your use case you might need to do a clearfix on the parent container.


How can I collapsible the facet search block with checkbox I need to create a  collapsible facet search block with check-box. Has anyone done this type of functionality.
I tried the Facet API Collapsible module but this modules provides the link and not the check-box.

I did work on similar functionality, where the client wanted a set of check boxes inside the collapsible Facet Block.
I found a module Collapsiblock which allows us to have check boxes inside the Facet Block.
This module will most probably help you.


Showing 2nd Depth term name and image along with it's associated node's title So I have a "Category" vocabulary on my website like this:

Parent Term 1:
  -- First Child Term:
     -- Second Child Term:
        -- Associated Node 1
        -- Associated Node 2
Parent Term 2:
  -- First Child Term:
     -- Second Child Term:
        -- Associated Node 3
        -- Associated Node 4

For Instance consider this:

Electronics:

      - Notebooks
        -- Asus
         --- Node 1
        -- Apple
         --- Node 2, Node 3 ...

What I want is to make a view to Show Popular Categories, The "Second Child Term" "Term Image (field)" along with 4 of it's nodes! so I can have something like this:

- Notebooks
-- Node 1
-- Node 2
-- Node 3
-- Node 4

I almost destroyed my laptop over this and couldn't figure this out, I ask you Views guru's to help out a newbie, Thanks.

Also note that I'll buy you dinner if you can help me <3

When you say 'Popular', do you mean the view must showing only the most popular/used term?  a bit more info please.

Ok, then I think I can help you get there, if I've understood everything correctly.

I've created a taxonomy that looks like this:
Vocab: Electronics
Terms:

Notebooks

Asus
Apple

Television

Panasonic
Sony

Then set up a view of Taxonomy Terms, using Filter Criteria to limit to your Electronics vocabulary (all straight forward so far).  What will help you is adding Advanced > Relationship > Taxonomy term: Content with term .  This will allow you to output the node fields that reference each term, per result.

Then enable Advanced > other > aggregation. This will allow you to group your results together by term.

To get closer to your required output, you can GROUP the fields using the FORMAT > settings.  Let me know if this takes you in the right direction, or even gets you close.  Or if you've tried this all before and I can remove the answer.

NOTE: the node will reference a specific TERM.  You can get access to that term's parent(s) tree etc, but bare in mind the relationships begin with the node->referenced TERM.


How to override the default image style for displaying user picture? I have Statuses Module installed on one of my site. I have created a view to display the status along with the user picture and the following comments.

The view displays the user picture along with the statuses, but the image style used is the default 'thumbnail' style. I have created my own image style for displaying these images.

Usually in a view when images are added we get a option by default to add image style to it. But in this case I dont have that option.

After a bit of searching I found the following code in the statuses.module to display the user picture:

function statuses_display_user_picture($account, $preset = NULL) {
  drupal_add_css(drupal_get_path('module', 'statuses') .'/resources/statuses.css');
  $image_vars = array('account' => $account);
  if (!empty($preset) && module_exists('imagecache_profiles')) {
    $image_vars['user_picture_style'] = $preset;
  }
  return theme('user_picture', $image_vars);
}

How do I override this code to display the image with my choice of 'image style'.

Use hook_preprocess_user_picture(). See template_preprocess_user_picture().

Here a sample code:

/**
 * Implements hook_preprocess_user_picture().
 *
 * @see template_preprocess_user_picture().
 */
function example_preprocess_user_picture(&$variables) {
  $style = 'your_style';

  $account = $variables['account'];
  if (is_numeric($account->picture)) {
    $account->picture = file_load($account->picture);
  }
  if (!empty($account->picture->uri)) {
    $filepath = $account->picture->uri;
  }

  if (isset($filepath)) {
    $alt = t("@user's picture", array('@user' => format_username($account)));
    $variables['user_picture'] = theme('image_style', array('style_name' => $style, 'path' => $filepath, 'alt' => $alt, 'title' => $alt));
  }
}


Views relationship between user and custom created entity I've an custom entity type : "card", witch has a property named "owner", an entity_reference to the owner of the card.

My custom entity is pretty basic and has been created trough Drupal Console.

If I create a view on Cards I can use the relationship to get the "owner" fields and properties accessible.

But if on a  Users based view, the reverse relationship is not present : I can't access card information's from the owner.

Am-I missing something ? Do I have to set up this reverse relationship somewhere ?

Thanks in advance !

Ok ! finally found out !

I had to use the hook_views_data_alter to put the relationship on the user :

/**
 * Implements hook_views_data_alter().
 */
function MYMODULE_views_data_alter(array &$data) {
  $data['users_field_data']['cards'] = [
    'title' => t("Users cards"),
    'help' => t("Link the users to their cards"),
    'relationship' => [
      'group' => t('Cards'),
      'label' => t("User cards"),
      'base' => 'cards', // database table
      'base field' => 'owner', //database field to join on
      'relationship field' => 'uid',
      'id' => 'cards',
    ],
  ];
}


How to move the user account/Profile 2 information from the content region to a sidebar region On the "My Account" page i.e. /user, the account and Profile 2 information is by default residing in the content region. I would like to move everything to the right sidebar region. Any suggestions on how I can achieve this ?

I am using Bartik

Thanks in advance.

You can create a View (show Users) with display "block" and add User:ID as Context Filter. For the Context Filter set "When the filter value is NOT available" to "provide default value - User ID from URL". Add all user fields that you would like to output to your view. Created Views block will then be listed on you Blocks page (structure > blocks). Once the block is there, you can drag it into the sidebar region.

If you need to remove user profile fields that are rendering in content region by default or override them, you can do so by overriding "modules/user/user-profile.tpl.php" - copying it into your theme's template folder and replacing  the line that renders user profile - <?php print render($user_profile); ?> with the desired content.

Page Manager Existing Pages + Panels is another convenient method of changing the layout of user profile. This method will work in combination with existing layout regions.


When should I add a new tpl.php file, and when should I implement a theme function? Two part question, both highly related.

Can all templates be implemented both as a function in template.php, and as a separate tpl.php file?
In the cases where you can do both, are there advantages to either of the approaches?

There are two types of theming something (theme('function', $args);)
Functions
The call to theme will result in a theme function being called: theme_foo with the arguments which will return the HTML string to be outputted. These can be overwritten by creating THEME_NAME_foo function in template.php
Templates
For template theme functions two things happens, preprocess_foo functions are called which will populate variables for the template. These can not be overwritten, but new ones can be added, as the alter an array which will contain all the variables used in the template by reference. The template file itself can be overwritten, by create a file withe the proper name. With use of suggestions, some can take precedence over others in certain cases. (node-forum.tpl.php used for forum type nodes vs node.tpl.php used for all nodes if no better match exists.)
Answer
So in short, it depends on the definition of the theme function if you should use

a template and/or preprocess function
a theme function

But there is never a case where you can use a mix of these.
So

No, no template file can be implemented as a theme function.
No, you can never use both a theme function and a template, but you can use a preprocess function and a template.


How to (double) opt-in the user registration process before admins are notified for approval? I was wondering if you can provide, with drupal core or any module, a double opt-in registration process.

Ideally, users who fill out a register form should receive an email with an opt-in activation link. Clicking that link, confirming their email, would it trigger the standard functionality of awaiting admin approval.

I tried LoginToBoggan but I'm pretty sure it does not provide double opt-in.

Is this implemented somewhere?

Edit: to prevent confusion: I know Drupal provides double opt-in for an "active user", but not for the registration itself. I would like users to verify that they want to register. Ideally:

Visitor enters their email to register
Visitor gets an email which he has to verify
After the link is clicked, the user gets created

How it currently is:

Visitor enters their email to register -> Blocked user gets created!
Either admin approves or user has to "double opt-in"

If I understand you correctly, this is default Drupal functionality.

Go to the Account settings (admin/config/people/accounts).
Under Who can register accounts?, Select the option Visitors, but administrator approval is required.
Directly below this option, select the checkbox Require e-mail verification when a visitor creates an account.

That's all.


Accessing Webform 4 Submitted data I have a webform on my site and on user submission, I want to send the webform data to some php application that get the value of some variables from the URL.

This task requires me to access the webform submitted data when the user clicks "Submit" button and construct a URL (/myphpapplication?query=....) containing user filled webform values.
Please help me to achieve this.

As Oswald mentioned, you have to implement some hooks in your custom module to redirect your form submission. Here is a quick example (assume your form_id is 'webform_client_form_1'):

// hook_form_alter()
function customform_form_alter(&$form, &$form_state, $form_id) {

if ($form_id == 'webform_client_form_1') {
    // Add form_submit() handler
    $form['#submit'][] = 'customform_webform_submit';
}

}

// form_submit()
function customform_webform_submit($form, &$form_state) {

// Submited values are in $form_state['values']['submitted_tree']
$field_values = customform_webform_values( $form_state['values']['submitted_tree']    );

// Build URL Query
$query = '';

foreach ($field_values as $value) {
    $query .= $value . '&';
}

$redirect = array (
                'myphpapplication',
                array (
                    'query' => array (
                        'query' => rtrim( $query, "&" )  // Get 'query' values with $_GET['query']
                    )
                )
            );

$form_state['redirect'] = $redirect;

}

// Recurse through webfrom submited values
function customform_webform_values($component) {

static $webform;

foreach($component as $key => $value) {
    if (is_array($value)) {
        customform_webform_values($value);
    }
    else {
        $webform[$key] = $value;
    }
}

return $webform;
}


How to display og group visibility in a view, even if user can't change it I'm working on a content pane view that displays a list of the groups the current user is a member of. Most properties of the groups are displayed in the view just fine, like the group title. But the group visibility is only shown to specific users.

I'd like to have a note in the group list whether a group is public or private, something along the lines of

  Group #1 | You're a member since... | This group is public

  Group #2 | You're a member since... | This group is private

  (and so forth)

But when I add the field "Content: Group visibility" to the view, the value only is visible for users that have permission to change the respective group's visibility (permission "Administer Organic groups permissions"). For any other user, the "No results behaviour" kicks in. The settings for the field "Group visibility" is public ("author and administrators can edit, everyone can view"), so shouldn't the field's content be visible to everyone?

I've found a solution - probably not the most elegant solution and quite "hacky", but it's working so far.

Even though some users are not allowed to see the group's visibility, the information is still provided to the view, but with a marker '#access' set to false. It's possible to alter the data displayed by the view by using the hook hook_views_pre_render. An implementation, for example in a custom module, could look like this

function MY_CUSTOM_MODULE_views_pre_render(&$view) {
  // $view is a reference to the view object

  // alter only the data of the view we want to change,
  // not every view on the website
  if($view->name == "MY_VIEW_NAME" && $view->current_display == "MY_CURRENT_DISPLAY") {
    // iterate over the list of entities, in this case over the list of groups
    foreach($view->result as $index => &$result) {
      // again, have $result as a reference
      // so changes are applied to the "original data", not just to a copy

      // change '#access' field deep in the field data structure
      $result->field_group_access[0]['rendered']['#access'] = true;
    }
  }
}


Views2 Handlers: Fatal Error Class 'views_handler_field' not found I am working on a module and want exposing some fields to Views and provide some custom filters. But I can't extend any Views classes without drawing a fatal error. My code looks something like this. It all works fine until I try to extend views_handler_field.

<?php
// $Id$
/**
 * @files
 *  Provide functionality for views.
 */
/**
 * Get some data and set some handlers.
 */
 function custom_views_data() {
      $data = array();
    $data['custom']['table']['group']  = t('custom');
    $data['custom']['table']['join'] = array(
      'node' => array(
        'left_field' => 'nid',
        'field' => 'nid',
      ),
    );
    // Has form
    $data['custom']['is_checked'] = array(
      'title' => t('Has contest form'),
      'help' => t('Filter based on presence of a contest form. Nodes with contest forms will equal 1.'),
      'field' => array(
        'handler' => 'views_handler_field',
        'click sortable' => FALSE,
      ),
      'filter' => array(
        'handler' => 'views_handler_filter_string',
      )
    );
    return $data;
 }

 // If you remove everything below here, things work as expected

 /**
  *
  * Define custom handlers.
  */
 function custom_views_handlers() {
      return array(
        'info' => array(
          'path' => drupal_get_path('module', 'custom')
        ),
        'handlers' => array(
          'custom_handler_is_checked_field' => array(
            'parent' => 'views_handler_field'
          )
        )
      );

 }

 /**
  * This class fails with Fatal error: Class 'views_handler_field' not found
  *
  */
class custom_handler_is_checked_field extends views_handler_field {}

Is your class code in the same file as your hook, aka the .module or .views.inc file? That doesn't work because views_handler_field is in a separate file and only loaded when required.

You need to move it in a separate file which as the same name as your class and the ending ".inc", inside the folder that you defined in 'path'. (in your case, your module directory, for large modules with many files, it's recommended to place them in a views directory)

Then, views will automatically include your class including the file that contains views_handler_field (because you defined the parent relationship in your hook) when required.


How do I get the term name in a custom submit handler? In Drupal 8/9, when you create a new term, the default status message is:

Created new term %term.

%term contains the term name, which is linked to the term page.
I want to override this and remove the link (I want to show the term name, but I do not want to link the term name to the term page).
I thought I could do this in a custom submit handler:
function MYMODULE_term_create_form_submit(array &$form, FormStateInterface &$form_state) {
  \Drupal::messenger()->deleteByType('status');
  \Drupal::messenger()->addMessage(t('The group @group-name has been added.', ['@group-name' => NULL]));
}

However, I don't know how to get the term's name from $form.  I searched the $form object with kint() and I could not find the form name.
Then I looked at core, which does this:
  public function save(array $form, FormStateInterface $form_state) {
    $term = $this->entity;

    $result = $term->save();

    $edit_link = $term->toLink($this->t('Edit'), 'edit-form')->toString();
    $view_link = $term->toLink()->toString();
    switch ($result) {
      case SAVED_NEW:
        $this->messenger()->addStatus($this->t('Created new term %term.', ['%term' => $view_link]));
        $this->logger('taxonomy')->notice('Created new term %term.', ['%term' => $term->getName(), 'link' => $edit_link]);
        break;

But, I don't have access to the term object in the submit handler.
What's the simplest way to do this without doing a quick-and-dirty patch to core?

In a submit handler you can find the form object in $form_state:
$term = $form_state->getFormObject()->getEntity();


Is it possible to determine what attachments (JS libraries, CSS, etc.) are required by a node form? I'm developing a solution which allows users to create content through a custom AJAX-driven UI. The first step in the process requires users to pick a content type from a dropdown list, which will then trigger the relevant node form to be loaded in to the page via AJAX. The HTML for the node form is being built correctly, but the issue I'm experiencing is that required JavaScript libraries are not included in the page, e.g. system libraries such as drupal.ajax and jquery.form, and libraries provided by contributed modules such as CKEditor and the media browser provided by the Media module.

Is there an elegant way of determining what libraries are required by node forms for a range of content types before the form is loaded? My intention would be to include all of the libraries using drupal_add_library, drupal_add_js and drupal_add_css in the page callback function for the UI.

Thanks in advance to anyone who has any ideas!

The most elegant way to do that is define attachments in hook_form_FORM_ID_alter. You can specify css files, js files or libraries:

$form['#attached']['library'][] = array('system', 'jquery.cookie');
$form['#attached']['js'][] = drupal_get_path('module', 'ajax_example') . '/ajax_example.js';
$form['#attached']['css'][] = drupal_get_path('module', 'ajax_example') . '/ajax_example.css';


Drush package handler - recommendations? After a day of cursing drush for refusing to update anything, I finally discovered that using --package-handler=wget instead of =git_drupalorg allowed everything to run smoothly. I suspect there were still problems with my git settings.

Why would I want to use git_drupalorg as the package handler? I see that most examples online use it, but perhaps people are defaulting to it on the basis that they're versioning with Git. Sure, I'm versioning my projects with Git too. But that versioning still happens, regardless of what technique is used to download core or modules. I just can't see what advantage there is in using git as the package handler.

But since everybody else is doing it... have I missed something?

(I don't ever contribute code to drupal.org. I can see why using git would be necessary for that. But then presumably contributors keep a totally separate installation for code development.)

Using the git_drupalorg package handler is best if you want to track the latest HEAD of the dev release.  If you just want to download stable releases, the wget package handler is preferable.


How to add additional query parameters to a views page url? I have a view with two displays as page. I need the URL of the pages as gallery?display=grid and gallery?display=slideshow and filter the views based on the additional parameter 'grid' or 'slideshow'.

Can anyone help me with this?

You can load different displays by using the views_get_view_result() function.

$grid_view = views_get_view_result('YOURVIEWNAME', 'grid');
$grid = $grid_view[0];

More documentation is found here and here


How to get Tb Mega Menu working in Chrome? I have a website and integrated Tb Mega Menu for the navigation. But the problem is my dropdown is not working in Google Chrome, though it is perfectly working in Internet Explore, Mozilla. My version of Google Chrome is 45.0.2454.85 m.
How to solve this issue? I did search for this, but found nothing suitable.

After so much time I found an answer. I Just increase the z-index for that li and the dropdown start working for me.


How do I migrate an image field with migrate 2 module on drupal 6 I have created my .module and .info and (one) .inc file.

I also have successfully used drush mi to import the data minus the images.

The images are in a related table in the database and are not being copied over when I run the migrate class. Here is my code:

    abstract class RoRMigration extends Migration {
     public function __construct() {
     parent::__construct();

     }
   }

    class RoRPagesMigration extends RoRMigration {
      public function __construct() {
      parent::__construct(MigrateGroup::getInstance('pages'));
      $this->description = t('Ruby on Rails Pages');

$this->map = new MigrateSQLMap($this->machineName,
  array(
    'page_id' => array(
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
      'description' => 'Page ID',
      'alias' => 'pid',
    )
  ),
  MigrateDestinationNode::getKeySchema()
);

$query = db_select('migrate_ror_pages', 'pid')
         ->fields('pid', array('page_id', 'title', 'content_subtitle', 'body_html', 'page_type',
          'redirect_url', 'published', 'meta_data', 'pretty_url'));

$source_fields = array(
 // TODO: Will add these other files later
 // 'banners' => t('Banners attached to this page; populated in prepareRow()'),
 // 'files' => t('Files attached to this page; populated in prepareRow()'),
  'images' => t('Images attached to this page; populated in prepareRow()'),
);

$this->source = new MigrateSourceSQL($query, $source_fields);
$this->destination = new MigrateDestinationNode('page_data');

// Mapped fields
$this->addFieldMapping('title', 'title');
$this->addFieldMapping('field_legacy_guid', 'page_id');
$this->addFieldMapping('field_legacy_content_subtitle', 'content_subtitle');
$this->addFieldMapping('field_legacy_html_body', 'body_html');
$this->addFieldMapping('field_legacy_page_type', 'page_type');
$this->addFieldMapping('field_legacy_redirect_url', 'redirect_url');
$this->addFieldMapping('field_legacy_published', 'published');
$this->addFieldMapping('body', 'meta_data');
$this->addFieldMapping('field_pathauto', 'pretty_url');

// We will get the image data from a related table in prepareRow()
$arguments = MigrateFileFieldHandler::arguments('file_copy', FILE_EXISTS_REPLACE);
$this->addFieldMapping('field_gallery_images', 'images')
     ->arguments($arguments);

// No unmapped source fields

// Unmapped destination fields
$this->addUnmigratedDestinations(array('status', 'promote',
  'revision', 'language', 'uid', 'revision_uid', 'created', 'changed', 'teaser', 'sticky', 'field_file_attached_file', 'field_legacy_link', 'field_legacy_byline', 'field_banner_image', 'path', 'pathauto_perform_alias'));
      }

      public function prepareRow($current_row) {

        $source_id = $current_row->page_id;

// This adds the images to the image_gallery field
$result = db_select('migrate_ror_pages_images', 'pic')
          ->fields('pic', array('filename_path', 'title'))
          ->condition('page_id', $source_id)
          ->execute();
$current_row->images = array();
foreach ($result as $row) {
  $image_data = array(
    'path' => $row->filename_path,
    'alt' => $row->title,
    'title' => $row->title,
    'description' => $row->title,
  );
  $current_row->images[] = drupal_to_js($image_data);
}

return TRUE;
    }
   }

So to be clear. There are two data tables migrate_ror_pages and migrate_ror_pages_images. The first table imports fine but the images do not import. The image table has a url to the image like this /sites/all/default/files/uploads/page_assets/images/filename.jpg and it has a title column, page_id, and image_id. There are more than one images per page.

Okay so I figured out what was wrong. I needed to put the site url in front of the path in my db.

  public function prepareRow($current_row) {

    $source_id = $current_row->page_id;

    // This adds the images to the image_gallery field
    $result = db_select('migrate_ror_pages_images', 'pic')
      ->fields('pic', array('filename_path', 'title'))
      ->condition('page_id', $source_id)
      ->execute();
    $current_row->images = array();
    foreach ($result as $row) {
      $image_data = array(
       'path' => $row->$GLOBALS['base_url'] . filename_path,
       'alt' => $row->title,
       'title' => $row->title,
       'description' => $row->title,
      );
      $current_row->images[] = drupal_to_js($image_data);
     }

The line that needed to be changed was the one regarding the path to the image. I was using a relative path /sites/default/.../filname.jpg and I needed to use a full path:

           'path' => $row->$GLOBALS['base_url'] . filename_path,

So if you are trying to import images/files you will need a full path to the image not a relitave one!

Hopes this helps someone.

//Craig


Unknown map column when migrating users from CSV file I'm trying to import the users from CSV file, but the import fails with the following error:

  Migration failed with source plugin exception: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'map.sourceid4' in 'where clause', in includes/database/database.inc:2171

Migrate class is:

<?php

/**
 * @file
 * Class for migrating users from a CSV file.
 */

/**
 * Class FooMigrateUsers.
 */
class FooMigrateUsers extends Migration {

  /**
   * Constructor.
   *
   * @inheritdoc
   */
  public function __construct($arguments) {
    parent::__construct($arguments);
    $this->description = t('Foo users from CSV file');

    // Create the migrate source.
    $import_path = drupal_get_path('module', 'foo_migrate') . '/import/users.csv';
    $options = array(
      'header_rows' => 1,
    );

    $this->source = new MigrateSourceCSV($import_path, array(), $options);
    $this->destination = new MigrateDestinationUser();

    $this->map = new MigrateSQLMap($this->machineName,
        array(
          'Title' => array(
            'type' => 'varchar',
            'length' => 15,
            'not null' => TRUE,
            'description' => 'Title',
          ),
          'Firstname' => array(
            'type' => 'varchar',
            'length' => 35,
            'not null' => TRUE,
            'description' => 'First name',
          ),
          'Lastname' => array(
            'type' => 'varchar',
            'length' => 35,
            'not null' => TRUE,
            'description' => 'Last name',
          ),
          'Primary email address' => array(
            'type' => 'varchar',
            'length' => 80,
            'not null' => TRUE,
            'description' => 'Primary email address',
          ),
        ),
        MigrateDestinationUser::getKeySchema()
        );

    // Mapped fields

    // We must have a unique username in the Drupal 'users' table.
    // dedupe() takes the Drupal table and column for determining uniqueness.
    $this->addFieldMapping('name', 'Primary email address')
         ->dedupe('users', 'name');
    $this->addFieldMapping('mail', 'Primary email address')
         ->dedupe('users', 'mail');

    //$this->addFieldMapping('pass', 'password');

    // Apply default role.
    $this->addFieldMapping('roles')
         ->defaultValue(DRUPAL_AUTHENTICATED_RID);

    $this->addFieldMapping('field_user_first_name',      'Firstname');
    $this->addFieldMapping('field_user_last_name',       'Lastname');

    $this->addUnmigratedSources(array('Title'));

    $this->addUnmigratedDestinations(array(
      'access',
      'created',
      'data',
      'is_new',
      'language',
      'login',
      'pass',
      'picture',
      'role_names',
      'signature',
      'signature_format',
      'theme',
      'timezone',
    ));

  }

  /**
   * Modifies the row to be imported.
   *
   * @inheritdoc
   */
  public function prepareRow($row) {
    return parent::prepareRow($row);
  }

}

The CSV data is like:

"Title","Firstname","Lastname","Primary email address"
"Mr","Foo","Bar","foo@example.com"
"Mrs","Bar","Foo","bar@example.com"

The 'Column not found' (map.sourceid4) error sounds like migration table related to source mapping is not complete.

You should identify the table (e.g. using drush command):

drush sqlq "SHOW TABLES LIKE 'migrate_map_%'"

Note: You can also execute above in SQL editor by using quoted part only.

and check the list of available columns for that table:

$ drush sqlq "DESC migrate_map_foomigrateusers"
sourceid1   varchar(128)    NO  PRI NULL
sourceid2   varchar(128)    NO  PRI NULL
sourceid3   varchar(128)    NO  PRI NULL
destid1 int(10) unsigned    YES     NULL
needs_update    tinyint(3) unsigned NO      0
rollback_action tinyint(3) unsigned NO      0
last_imported   int(10) unsigned    NO      0
hash    varchar(32) YES     NULL

The number of sourceidX column should match with number of columns in CSV file. If they won't, probably you've modified the CSV file and after each structure change you have to re-register your migration class (see: hook_migrate_api).

So please reregister any statically defined migration classes by (check list by drush ms):

drush migrate-deregister FooMigrateUsers
drush migrate-register FooMigrateUsers

In case of further problems, these drush commands can be handy as well:

drush migrate-mappings --all # To verify mapping.
drush migrate-fields-source --all # To list source field mapping.

When ready, try re-importing the data again:

drush mi FooMigrateUsers


custom views in taxonomy tags pages I have created a custom view for my Drupal 7 front page, and I have named it "Recent Products", but this view is only working for the front page is not working in taxonomies, tags, content preview pages.

How do I apply this view for every page, or set it as default for pages?

I think there is a misunderstanding: The Views module is used to create pages, or blocks. In both the cases, the created view shows nodes, users, taxonomy terms, modules, etc matching some criteria set for the view.

A view is not a template for altering the content of other pages. For that there is the Panels module. (Emphasis is mine.)

  The Panels module allows a site administrator to create customized layouts for multiple uses. At its core it is a drag and drop content manager that lets you visually design a layout and place content within that layout. Integration with other systems allows you to create nodes that use this, landing pages that use this, and even override system pages such as taxonomy and the node page so that you can customize the layout of your site with very fine grained permissions.


How to hook into access control of node/add menu handler? Looking at Drupal code, I noticed the following function.

function _node_add_access() {
  $types = node_type_get_types();
  foreach ($types as $type) {
    if (node_hook($type->type, 'form') && node_access('create', $type->type)) {
      return TRUE;
    }
  }
  if (user_access('administer content types')) {
    // There are no content types defined that the user has permission to create,
    // but the user does have the permission to administer the content types, so
    // grant them access to the page anyway.
    return TRUE;
  }
  return FALSE;
}

What is node_hook()? How can I implement this hook for additional access control?

node_hook() is not an hook; it's a helper function Drupal uses to verify a content-type hook exists. In the code you are showing, the function is verifying the module implementing the $type->type content type implements hook_form().

To alter the access control for a node, you have two options:

Implementing hook_node_access()
Implementing hook_node_grants() and hook_node_access_records()

Implementing hook_node_access() is easier, but that hook is not used in node listings (lists of nodes generated from a select query, such as the default home page at path 'node', an RSS feed, a recent content block, etc.).

Notice that, since _node_add_access() is an access callback, you could change the access callback used by node/add. I suggest not doing it because that would by-pass all the node access control implemented by Drupal.

Reference

Node access right


With a 'review' node type and a node reference to a 'product ' node type limit number of user reviews to one In a product node type with a review node type that has a reference field to it, how do I only permit one review per user per product node? Do I use the Rules module and if so how do I configure the rule? Do I make a custom query and then unset the Add Review button/link on the product node in a custom module or in template.php?

(edit) Take the example of product reviews on Amazon or muffler repair reviews on Yelp. The user who makes the review  gets one review per listing or item. After they create the review, they can edit it but can't make another one for that listing or item. Seems logical. Likewise the Fivestar rating widget only allows one vote per item so having several reviews for an item will not permit more than just one Fivestar rating.........

Unless somebody has a better solution, I'm going to test -- since the Fivestar widget makes the database query anyway -- if it has been set by the user on the node view. If true then I will disable the Node Reference URL widget button in the links area. If I need more security, I will create code or a Rue that tests on the Node Add page if the Fivestar widget has already been set to disable the Node Add page and redirect the user back to the product.

You might need to try a custom module for this.  Rules are too generic as you can only control a user's right to create a type of content.  If I was to write a module for this, it would go something along these lines:

• Use hook_form_alter to add an extra validation function to your Review node form
• Check if the user has submitted a review before in the db
• Throw an error if a record exists in the database

Something like the following code should work, but this is untested.

Edited to note that this is Drupal 6 code but if you use it as a template it shouldn't be too far away.

<?php

function MYMODULE_form_alter($form_id, &$form) {
    // If the form is a "review" node form
    if ($form_id == 'review_node_form') {
        // Add an extra validation function
        $form['#validate'][] = 'MYMODULE_user_node_limit';
    }
}

// Validation function
function MYMODULE_user_node_limit($node) {
    // Get our logged in user's details
    global $user;
    // Run a database query (something like this)
    $sql = "SELECT {node}.uid \n"
    . "FROM {content_type_review}, {node} "
    . "WHERE {content_type_page}.field_node_ref_nid = {node}.nid "
    . "AND {node}.nid = %d"
    . "AND {node}.uid = %d";
    $result = db_query($sql, $node->nid, $node->uid);
    if ($result === FALSE) {
        // Throw error
        drupal_set_message('You have already submitted a review of this item.', 'error');
    }
}
?>

Edited to answer additional comment by asker

Regarding the comment made by Adam S - you could use the code I have already posted in conjunction with the Drupal 7 equivalent of Drupal 6's hook_nodeapi. Here is a list of Drupal 7's node hooks for you to have a look at.  Also, have a look at Eric London's Drupal 6 example of a problem similar to yours of limiting a user's node writing privileges.  Apologies for not providing an exact Drupal 7 example but if you follow the basic premise of Eric London's link but modify it in conjunction with my code, you should be able to solve your problem.


Additional filter for (image)fields to filter node display I need to display nodes on multiple places. For some fields I have multi values. On every place I'd like to display other values of the field. I'd like to have maybe some checkboxes as filter.

For example:

An multi value image field. 3 places to display these image on the site. For every place a checkbox (area1, area2, area3). When checkbox 1 and 3 are checked, this image is displayed only in area1 and area3. When checkbox 2 and 3 are checked for an image, the image is displayed in area2 and area3.

Does anyone knows a solution for that?

I'm not sure if it quite meets 100% of your requirements, but you might want to take a look at the Display Suite module. It lets you customize multiple displays per node type, each of which can be configured to display different fields.


In view, $content is null when show: fields I'm trying to customize the row style template for one of my views. The settings are

Format: HTML List
Show: Fields

With these settings, $content is null in my .tpl.php file. I know about $fields, and I can see my values in there when I var_dump. However, the values are buried SO DEEP in there that I'm having trouble getting at them. I'm sure I must be doing something wrong.

How do I access my fields in a custom tpl for a view?

It is possible that you don't override the correct template. For the reference see here: Views template files.

There are several different approaches possible, depending of your requirements.

The usual way is to change the output of each field individually, using the field specific override. Access to the raw value and the already rendered content is straight forward using the provided variables. It's very difficult to break something here.
Another way is to use a row specific override. Following this approach it is your responsible to assure to output all fields in the result set for each row. In exchange this can be much more flexible regarding the created markup structure, because it's entirely up to you,

You could go even higher up the abstraction road, but the use cases for that are becoming incredibly scarce. So the odds are your simply in the wrong template.

Also, just in case you don't know that, there is an overview for the available and the used template files in the Views UI. In Drupal 7 and Views 3 it is in the outer right block the last link on the bottom:


Drupal Content Types Content types that are created recently are not showing up. They are displayed in content type list but not in "Add content" list and navigation menu. I tried few solutions like:

I checked in the database node_type table if the fields type and orig_type are same; they are same.
I configured the navigation block to access all content types, though it is not necessary.
I tried to do add the link directly in navigation menu, but the link is not getting added to the menu.
I cleared the cache several times and run the cron tasks too.
Its is not even permissions, I have given them already.
Can anyone help? I am stuck and I cannot start everything from scratch.

When you create a new content type, it should be visible in the "Content Type" page.

If they are not visible, then it could be a permission issue: You have to give permission for creating/modifying nodes using content types you added. The only exceptions are the first user created for a Drupal site (who always has all the permissions) and the users with the "administer content types" permission.


problem with check_markup() I have a content type called 'microblog', and a default input format for registered users is set to 'Filtered HTML', meanwhile i want to use 'Messaging plain text' format for creating a microblog content.

<?php
$content .= check_markup($node->title, $format = 'Messaging plain text', $check = TRUE);
?>

But it seems like drupal ignores $format, still when im posting microblog content it uses 'Filtered HTML' format.

PS i'm using http://drupal.org/project/microblog module.
Tried to change in microblog.module on 380 line to 'Messaging plain text' - still no effect...

You should do like this

$format = db_result(db_query("SELECT format FROM {filter_formats}
                              WHERE name = 'Messaging plain text';"));
$content .= check_markup($node->title, $format);

The problem is that you need to use the format id not the format name.


How do I add a custom textarea into the checkout screen? I want to add 'Notes' textarea for adding addtional message by customer while placing the order.

I have added additional textarea in 'Order types' page (/admin/commerce/config/order-types/default/edit/fields). It is displaying in order page but not in checkout page.

Example: Customer is placing an order for Toys and they want to add message saying 'Please deliver in 2 days..'

Edit: I have seen same question in Drupal 7. But there is no 'Commerce Fieldgroup Panes' module in Drupal 8.

You will need to write a custom checkout pane plugin, I'm afraid.

Docs here: https://docs.drupalcommerce.org/commerce2/developer-guide/checkout/create-custom-checkout-pane


How to retrieve sumbitted data in modal I want in add content have a link(or button) when user click on lt the popup (modal or any popuping method like dialog,modal,lightbox,colorbox ) will open, in that form I want have some field, like hierarchical select and long text fields, after user submit that form, the submitted values passed back to add content form,

appreciate any idea

I'd suggest an approach which is not a solid, but you can get an idea;

Create modal with Ctools (may be this and this links can
help you to create it);
On form submission store the submitted data as array into $_SESSION;
reload the page with ctools_ajax_command_reload();

example:

// This is must be in ctools modal callback. Read modal.html file in ctools/help directory
if (!empty($form_state['executed'])) {
  $commands = array();
  $commands[] = ctools_ajax_command_reload();
}

Alter the content add form;
add #default_value to the fields, e.g.: '#default_value' => isset($_SESSION['modal_data']['field_1_value']) ? $_SESSION['modal_data']['field_1_value'] : '';
at the end of the content add form just unset the $_SESSION data, e.g.: unset($_SESSION['modal_data']);


How do I display empty fields? I have redesigned the layout of the page using the display suite module. When I go to the node, I see empty fields are not there. I like to see the empty fields on the node. I have been looking for the settings and I could not find it. How can I display empty fields?

I never did it I have a small though...

Write a customer formatter (module /custom_formatters) for this field which outputs for the length of the field &nsbp;

Another option is maybe to add custom tokens which a writing blank spaces and set the initial value to this token.