Drupal Commons add automation using Workflow modules to solve the problem of Wiki/Article Publishing for End users I have a Drupal Commons Profile and I have setting up the following modules to my drupal commons site.

Workbench

Workbench Access
Workbench Moderator

Configure the Taxonomy and set it to "Section"

My Workflow

Content Creators
Content Publishers

Article Content Type:
Publishing Options: Disabled
Enabled Moderator Options to "Drafts"

Created two Roles

Content Creator ( Content Creators )
Channel Manager ( Content Publishers )

Set permissions to Each Role

First I logged in as Content Creator

My Workbench->Create Content->Article->Add New Article
Set Moderator: "Needs Review"

and Save article.

Issues:

After logged in as Publishers account.
Go to

My Workbench->Needs Review

But there is no any content will be appear.

But If i logged in as Administrator I will show the same there?

Can anyone let me know what was the issue I am facing.
any suggestion will be helpful.

your subject is quite different than the question you ask. If its just a permission issue then you need to check under roles and permission. Sometime we cannot give all rights required to for mod or data entry access, so best is to copy administrator role and remove all critical permission and assign only what you want to give (to specific piece of content).

Btw, workbench is only used for permissions and not for the work flow. Its a like creating a working space for certain set of people (work bench) with adequate permissions, that's it.

If your question is regarding your subject of how to create workflow, then look at maestro module https://drupal.org/project/maestro to create GUI based logical workflow with great level of approvals, check point and notification options.

I researched Maestro week back for my friend and worked for a short while.


Spammers on Drupal 6 site I think Im getting some spammers adding user accounts to my site. I've been checking the users section of my site daily and I'll see these strange email addresses. So I check on the reports and find that they are spammers. Has anyone encountered this problem? Im currently researching it to try and stop it.

The Spambot module is a great solution for protecting the registration form:

  Spambot protects the user registration form from spammers and spambots by verifying registration attempts against the Stop Forum Spam (www.stopforumspam.com) online database. It also adds some useful features to help deal with spam accounts.

I'd definitely recommend it


Issue while modifying and importing the manually content type data I have a scenario like this:

I am using Feeds Importer to import one content type data. I am using GUID field as the unique field. Also, I am exporting these all the nodes of this content type using Views into a .csv file.

My problem is that users can create nodes using the Feeds Importer and also manually in the Drupal admin console.

While I export the nodes of the content type, it contains all nodes (manually created nodes and Feeds imported nodes). There will be no GUID for the manually created nodes.

In this case, how can I resolve the issue of re-import of this data into the Drupal tool?

Is there a way to update the GUID field in the database whenever a new node of this type is created? This will resolve the issue.

Install Universally Unique IDentifier and use it as GUID.it is not required you create GUID field in most of time Nid is good choice  as GUID mapper.

Universally Unique IDentifier Description :

  This module provides an API for adding universally unique identifiers
  (UUID) to Drupal objects, most notably entities. Features in Drupal 7
  version Automatic UUID generation

  UUIDs will be generated for all core entities. An API is provided for
  other modules to enable support for custom entities. UUID API for
  entities, properties and fields

  With this unified API you can load entities with entity_uuid_load() so
  that all supported properties and fields are made with UUID
  references. You can also save entities formatted this way with
  entity_uuid_save() (depends on Entity API). Export entities to use as
  default/demo content

  The integration with Features module provides the ability to export
  UUID enabled entities with intact dependencies and references to other
  entities. This functionality depends on Deploy module 7.x-2.0-alpha1
  (soon to be released) and is probably the most robust way for
  installation profiles and distributions to provide demo content!


How can I access to created "View modes" in views and create a block of it? I created a "View modes" in Structure> Display-modes> View and I'm now trying to get access to it in views so i can be able to create a block of it.

By default in Drupal it's possible to create a block of teasers and full posts but I'm going to create a block of my own "View modes",

I cleared my cash several times but howsoever i try the "View modes" that's i created doesn't show in "Block display settings" dropdown menu and I can't create a block of it.

Just skip this part of creating a View. Don't create a block or page display yet (that's what I do) and work on a master view. When you go select rendered content as a field, you will have view modes you created as options. Show "Content" as a view mode.

See this for more:

https://www.amazeelabs.com/en/blog/views-field-rewriting-to-views-modes


Print selected fields from a referenced node Using entity reference, i have been able to link a node of type blog to another node of my custom content type, "challenge", by creating a field under blog of type entity reference. Great. Now, when the blog is published, some fields (not all) from the linked custom content type should also be displayed there. For ex, in my custom content type, there are some fields as title,body,image1,image2,sponsor, some flags using the flag module and other fields. I want that only some fields which i mentioned should be displayed on the blog (no flags etc to be displayed). SO what i do is under Manage Display for blog i select Rendered Entity for display. What this does is gets all the fields from the referenced/linked node. However i want some fields not all. Now what i do is write a custom node--blog.tpl.php. I then hide everything from content as:

<?php
   hide($content['title']);
   hide($content['field_blog_pic']);
   hide($content['field_challenge_name']);
   hide($content['field_challenge_pic']);
   hide($content['field_sponsor']);
   hide($content['field_sponsor_logo']);
   hide($content['field_sponsor_description']);
 ?>

Then i tried rendering the fields one by one. It is ok for the field of type blog but the moment i do a print_render($content['field_challenge_name']) then all fields from the referenced node (of my custom content type, challenge) get displayed. How can i just select a few fields for display of the referenced node.

If it helps, here's my node--blog.tpl.php:

     <?php
       print render($content['field_blog_pic']);
     ?>

     <?php
        print $title;
     ?>

     <?php
        print $comment;
     ?>

     <?php
        print $name;
     ?>

    <?php
    /** $user = user_load($user->uid);
      print theme_image_style(
                    array(

                        'path' => $user->picture->uri,
                        'attributes' => array(
                            'class' => 'in-blog-user'
                        )
                    )
                );
    */
    ?>

 <?php
   $user = user_load($uid);
   print theme('user_picture', array('account' =>$user));
 ?>

 <?php
  print $title;
 ?>

<?php
   hide($content['title']);
   hide($content['field_blog_pic']);
   hide($content['field_challenge_name']);
   hide($content['field_challenge_pic']);
   hide($content['field_sponsor']);
   hide($content['field_sponsor_logo']);
   hide($content['field_sponsor_description']);
   hide($content['field_categories']);
?>

 <?php
  print render($content);
 ?>

<?php /*

  <?php
     print render($content['field_challenge_name']);
  ?>

*/?>

All fields get displayed of the referenced node once i do the last few lines

      <?php
         print render($content['field_challenge_name']);
      ?>

    ?>

So after all that blabbering, all i want to ask is how to print some selected fields of a referenced node (here my custom type, "challenge") onto the referencing node (here, blog)...

Regards

I would use Display Suite for this problem. Using it, you can define an extra view mode for the referenced node type, with just the fields you want, then configure the display of the entity reference field to use that view mode. We are doing this in the current project I am working on, and it's just the ticket.


How to add a form_token to a login form For security purposes, I need to add a form_token to the login form. However, when (in hook_form_alter) I use the same code Drupal uses in form.inc for other forms, the validation fails because the token calculated during validation is different from the one calculated originally.

The code I'm using is:

if (!isset($form['#token'])) {
  $form['#token'] = $form_id;
  $form['form_token'] = array(
    '#id' => drupal_html_id('edit-' . $form_id . '-form-token'),
    '#type' => 'token',
    '#default_value' => drupal_get_token($form['#token']),
    // Form processing and validation requires this value, so ensure the
    // submitted form value appears literally, regardless of custom #tree
    // and #parents being set elsewhere.
    '#parents' => array('form_token'),
  );
}

I'm calling the form with drupal_render(drupal_get_form('user_login')). I'm aware that Drupal is not using the form_token on the login page because it is often cached, but I have disabled the cache for that page in hook_init with:

$GLOBALS['conf']['cache'] = FALSE

How can I add and validate a form_token in the login form? I'm using Drupal 7.

Some extra info as to why I need this. The request to secure login forms against CSRF came up during a security scan and although I do not agree with the explanation for the request (easier to setup a brute force attack, despite auto blocking logins in such cases), there is a good explanation on stackoverflow as to why this still can be a good idea: Do login forms need tokens against CSRF attacks?

I ended up (as suggested) adding a token to all unsecured forms with hook_form_alter.

Seemed efficient to use drupal_get_token() for this, but that did not work because the session ID (used by drupal_get_token() to generate a token) alters when an (anonymous) user logs in.

I therefore stored the first session id (when displaying the login page) in $_SESSION so I could retrieve it when validating. But putting something in $_SESSION apparently prevents Drupal from regenerating the session_id. And now that the session id is preserved during login, drupal_valid_token() also works as expected so I did not have to write a special token validation function.

This is the code I ended up with:

function MY_MODULE_form_alter(&$form, $form_state, $form_id) {
    // add a custom csrf token for forms that do not have one
    if ($!isset($form['#token'])) {
        $form['anon_token'] = array(
            '#type' => 'token',
            '#default_value' => drupal_get_token()
        );

        $form['#validate'][] = 'MY_MODULE_validate_anon_token';

        // store current session id
        // touching $_SESSION alone seems to preserve the session id after login
        $sess_id = session_id();
        if (isset($_SESSION))
            $_SESSION['anon_session_id'] = $sess_id;
        else
            $_SESSION = array('anon_session_id' => $sess_id);
    }
}

function MY_MODULE_validate_anon_token($form, &$form_state) {
    $token = '';
    if (isset($form_state['values']['anon_token']))
        $token = $form_state['values']['anon_token'];

    if (!drupal_valid_token($token)) {
        // not a valid token!
        $path = current_path();
        $query = drupal_get_query_parameters();
        $url = url($path, array('query' => $query));

        // Setting this error will cause the form to fail validation.
        form_set_error('form_token', t('The form has become outdated. Copy any unsaved work in the form below and then reload this page.', array('@link' => $url)));
    }
}


8 - Manually adding a user field will delete all programmatically added user fields In my module i programmatically add user fields for the website owner instead of instructing them to do so. Here's an example of the code i used which runs in mymodule.install:

function openid_connect_entity_base_field_info(EntityTypeInterface $entity_type) {

if ($entity_type->id() === 'user') {
    $fields['field_birthdate'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Birthdate'))
      ->setDescription(t('Add a description'))
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setDisplayOptions('form', array(
        'type' => 'string_text_field',
        'weight' => 30,
        'default_value' => 0,
      ))
      ->setDisplayConfigurable('form', TRUE);
  }

return fields;
}

but if you add a field manually all the programmatically added fields will be deleted as shown:

programmatically added fields before adding one manually

Adding a field manually

And boom all the programmatically fields are gone!

If this is a bug in the drupal 8 framework where do i report this?

You just need to move the hook implementation into the .module file.

It works on install in the .install file because that file is included in the request, and when Drupal looks for hook implementations, it can find it.

Wen you're not installing, e.g. when adding fields through the UI, the .install file is not included so the hook won't be found, and Drupal will consolidate the info it has by removing those fields.


Go to page section after redirect I wanted to provide feature where non-logged in users can click on "Rate" button, which will lead them to login and after login they come back to the page. Upto this, it is working fine.

But I want user's to go to particular section of page, div with id = "id1".

How can I achieve this?

-- Many thanks for your time.

This is what I have tried:

$destination = drupal_get_destination();

$options = array( 'query' => $destination,'fragment'=>'div_id');

print l('Review', 'content/login', $options);

This works for me...

$destination = drupal_get_destination();
$destination['destination'] .= '#div_id';
$options = array( 'query' => $destination);
print l('Review', 'content/login', $options);


How to get nodes with term programmatically I have Vocabulary and Custom Content Type which has field Term reference.

How can I get all nodes of particular term in my module?

Something like this? This doesn't work.

$field = field_info_field('field_game');
$results = new EntityFieldQuery;
$results->fieldCondition($field, 'field_game_tid', '5')
  ->execute();

$nids = array();
foreach($results as $result) {
  $nids[] = $result->nid;
}

$nodes = node_load_multiple($nids);

You want to specify that you searching for nodes first (and optionally by your content type), and then filter by term:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'YOUR_CONTENT_TYPE_HERE')
->fieldCondition('field_game', 'tid', 5);

$result = $query->execute();
$nids = array_keys($result['node']);
$nodes = entity_load('node', $nids);

Here's a good example of an entity query like this (and more field conditions)


Trying to get IMCE with Filefield Sources working (no Upload button in popup) I've got a clean install of D6.22, CCK, Filefield, ImageField, Filefield Sources and IMCE. No other modules.

When i go to http://mysite.com/imce it all works perfectly (see screenshot).

But when i try to implement an image field with IMCE as a filefield source, i can click the "browse" link and the IMCE popup comes up, but the only button i get at the top of the popup is "Insert file". No upload, no delete, no resize etc. Here's the screenshot.

I see from the popup's page info that its URL is...
http://mysite.com/filefield/imce/page/field_pics?app=pics|url@edit-field-pics-0-imce-path
(the image field's human name and machine_name are both "pics").
I'm logged in as user-1, and the IMCE user-1 profile is looking good.

Also, there are no javascript errors, and if inspect the popup with Firebug, the upload button is there, but hidden. If I unhide it and click the button, I get the alert "You can not perform this operation". So it seems to be a permissions problem rather than a javascript problem.

I'm sure i've missed something so simple nobody's bothered to mention it in any of the docs. Can someone enlighten me?!

Ah! Like, Filefield Sources no longer lets IMCE do anything except browse your files and select one of them (for security reasons i think). That's what the situation seems to be, though i can't find anywhere that says that explicitly.

Luckily there's a patch which reinstates the missing functionality...

http://drupal.org/node/877452#comment-4499144

The maintainer of Filefield Sources links to that patch from the module's project page, so it's a recommended patch.

All functioning now :) Can i have my Sunday back now please?

++Thanks to ufku for providing the patch.


bootstrap sub theme rendering garland I copied the database and source code from my local to another server.
On my local I have a bootstrap sub theme set as default which works fine. On the other server (which has the exact same db settings and code) the theme being rendered is Garland despite being disabled and the admin section under appearance stating that my sub-theme is the active one.

When I checked the site after updating the server it had the correct css but when I reloaded the page it reverted back to garland but without any changes to the admin settings.

What are some good steps to take in terms of debugging this.

I deleted the garland theme and re-added it. After this everything worked properly. I don't know why this worked!


Can I change the Display Settings by modifying the database? I am using Drupal 8.5.6 and need to make the authoring information hidden for each content type. In other words, there should be no 'authored by admin on (date)' on any page. The fix should be simple (How do I hide the authoring information?) but similarly to https://stackoverflow.com/questions/51771776/drupal-8-display-settings-tab-missing-from-all-content-types, I do not have the display settings tab. I can get it back by uninstalling the Manage Display module (I tested on a seperate site), but there is a module dependent on 'Manage Display', which if I uninstall, content that shows up on the main page is lost.

Is there a way to replicate checking the 'Display author and date information' box from the database alone? Or is there a way to change this setting without uninstalling the Manage Display Module?

Export the config and change in node.type.[content-type].yml:

display_submitted: false

and import the config again or edit the live config directly with Drush, for example of the content type Article:

drush cedit node.type.article


What may cause "An illegal choice has been detected. Please contact the site administrator"? When a user goes to create content, usually for a forum the following error is received.

  An illegal choice has been detected. Please contact the site
  administrator.

The forum topic can still be created however.
This doesn't happen if the user is administrator.

The following errors can be seen in error report

Type form
Date Wednesday, May 1, 2013 - 12:24
User 222_test
Location
Referrer    /node/add/forum
Message Illegal choice 423 in term_node_tid_depth_1 element.
Severity error
Hostname
Operations

Type form
Date Wednesday, May 1, 2013 - 12:24
User 222_test
Location /node/add
Referrer    /node/add/forum
Message Illegal choice 427 in term_node_tid_depth element.
Severity error
Hostname
Operations

I would say that this means that the user has selected term 423 for term_node_tid_depth_1 and 427 for term_node_tid_depth, but those values are not actually options in that field.

Usually the way this happens if you have custom code that sets the field value to an invalid value, or if it changes the field and removes some of the possible allowed values.

You say it doesn't happen when you are the admin, so I would guess that the admin has access to all the options in the field but other users are just seeing a subset of the field values, but somehow are still setting the field to one of the values they aren't allowed to see.

Do you have any custom code or are using any unusual field or forum related modules?


Create a View from custom database I love the features the view provides in Drupal. Sortable tables, Filters, as well as ability to use external modules like views bulk export.
My problem is that I want to display a separate database (Call this X), using views. What would be the best way to go about it?

To get around this problem in Drupal 6, I created a content type with all fields that were in Database X, then I created view for that content type by frontend. After that I used hook_pre_render_view() to push data from X to the view. Right now I want to achieve similar results in Drupal 8. I could use this same approach but it doesn't feel very Drupally. I was wondering if there is a better way to achieve this.

You can connect a external database inorderto let Drupal Know about it:

$databases['external']['default'] = array(
  'database' => 'custom_database',
  'username' => 'root',
  'password' => '',
  'prefix' => '',
  'host' => php_sapi_name() == 'cli' ? '127.0.0.1' : 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

Then you can connect to that database:

/*
* Switch to external db
*/
\Drupal\Core\Database\Database::setActiveConnection('custom_database');

/*
* Get connection
*/
$db = \Drupal\Core\Database\Database::getConnection();

Then do you stuff and don't footgrt to switch again to the standard database:

/*
* Switch back
*/
\Drupal\Core\Database\Database::setActiveConnection();

You can store your external database info into a content type programatically and the show in views.


How do I set my custom input type as default? I strongly need to use my custom type as default. How do I set it as default?

In Drupal 7, the default input format is the one the users have the permission to use, and that appears first in the list of the input formats reported in admin/config/content/formats.

In my case, Textile is the default input format that is selected for the administrator role, but if the currently logged-in user doesn't have the permission to use that input format, then the default input format will be "Filtered HTML." "Plain text" is the input format that all the roles can access; in the case none of the other input formats is accessible to the user, "Plain text" is the input format that will be used.

In Drupal 6, the default input format is the one selected as default in admin/settings/filters.


How do I define a Route with multiple different paths? Does Drupal's routing system support a regular expression or other means for multiple route paths? I have a route that I would like to be able to hit from two different endpoints, /api/v1/foo and /api/v1/foo_bar. One route is newer, the other I want to keep for backwards compatibility reasons.

In my module's my_module.routing.yml file, I have defined:

foo:
  path: 'api/v1/foo'
  defaults: { _controller: '\Drupal\my_module\Controller\MyController::doItAction' }
  methods:  [GET]
  requirements:
    _access: 'TRUE'

foo_bar:
  path: 'api/v1/foo_bar'
  defaults: { _controller: '\Drupal\my_module\Controller\MyController::doItAction' }
  methods:  [GET]
  requirements:
    _access: 'TRUE'

This works, but as you can see everything after the route name and path property is copy/pasted. It's not exactly adhering to the DRY principle. Now this is a simple case, but imagine if I had a much more involved route with complex requirements and parameters. There would be a very high chance of making a typo or pasting mistake in one.

Is it possible to define the path as a regular expression or something similar so I don't have to repeat all the route properties?

cool:
  path: 'api/v1/{dynamic}'
  defaults: { _controller: '\Drupal\my_module\Controller\MyController::doItAction' }
  methods:  [GET]
  requirements:
    _access: 'TRUE'

Then in your controller

public function doItAction($dynamic) {

  if($dynamic == 'foo' || $dynamic == 'foo_bar') {
    // your code
  }

}


How to provide custom template declared inside my theme .theme file as variable inside page twig template In my theme, I implemented HOOK_theme to declare custom twig template.
How can I provide/preprocess this template as variable ready to to output inside my page.twig.html template ?

Presume you have something like:

HOOK_theme($existing, $type, $theme, $path) {
  return [
    // mycustomtheme.html.twig
    'mycustomtheme' => [
      'variables' => [
        'var1' => NULL,
        'var2' => NULL,
        'var3' => NULL,
      ],
    ],
  ];
}

You can preprocess the page.html.twig theme and add your theme output as a variable:

function HOOK_preprocess_page(&$variables) {
  $var1 = 'foo';
  $var2 = 'bar';
  $var3 = 'baz';
  $variables['content']['customcontent'] = [
    '#theme' => 'mycustomtheme',
    '#var1' => $var1,
    '#var2' => $var2,
    '#var3' => $var3,
  ];
}

And then you should be able to print it on page.html.twig:

{{ content.customcontent }}


How can menu tabs be relocated to another region? I want to move menu tabs to occur in the main menu region instead of immediately above the content.  I cannot identify a block that contains them.  Is there a module, template location or a hook for controlling their display?

"I cannot identify a block that contains them." There is not a block that contains these. In Drupal 7, these tabs are a variable called $tabs found in /modules/system/page.tpl.php.

You could suppress these tabs by overriding page.tpl.php in your theme.

To put them in another region, you could:

Implement hook_preprocess_page(&$variables, $hook) in your theme's template.php or in a custom module.
Copy the contents of the $variables['tabs'] array key into another region.


Set the title for a node view panel I am trying to use panel in Drupal 8 node view template. I have enable Node view panel and added a new variant for Basic page view. But I couldn't mention in panel page to take the title as current node title. Where I can mention it in panel configuration?

Drupal 8

Even I have created the panel variant in Drupal 7. Here title is taking by default node title.

Drupal 7

FYI: Page Manager is in beta, but that doesn't affect the solution; see below.

You should first check if the node context is available in your Variant. Here is an example screenshot for that:

If that is the case, then you can simply use the following token in the page title field:

  [node:title]

should look like this:

Good luck!


Url aliases/global redirect not being used in Custom Blocks This one's weird.  Drupal 7.

I have a complex front page - lots of Views, also lots of custom blocks using code I wrote from scratch - functions that essentially query the database directly and output different lists of content.

For some reason, these custom lists aren't using the generated url aliases.  They just link to node/#####.  Further, Global Redirect isn't working for them either.  What gives?

To see in action: http://www.ainonline.com.

You'll see most of the top stuff has the generated aliases.  The ones in the middle towards the bottom, under the individual channels, use the system urls.  Any ideas?

Found the answer.  Sort of surprising since I don't think it's uncommon to run Drupal from a subdirectory (im my case, "drupal") and hide the fact through .htaccess rewrites.  Anyhow, doing exactly that breaks Global Redirect.

The fix is unfortunately hacking the module until it's addressed.  See here:
http://drupal.org/node/976214


Multiplied db_results when multiple IN I am stuck since yesterday on a problem that is making me crazy, I feel like I am missing something.
Here is the context:
I am products (a node). In each products, I have tags (taxonomy terms), in a term reference field with an unlimited values possible.

I am simply trying to query my items, using a tag filter. But as soon as I select multiple tags, if the multiple as those tags, results is multiply by the number of corresponding tags.

The query is pretty big so I am simplifying it here to achieve the same result.

Node structure:

Title ------- | Quantity | Tags Tid
Product 1 --- | -- 1 --- | 12, 15
Product 2 --- | -- 4 --- | 13

Tables looks like this:

Node:

Title ------- | Nid
Product 1 --- | 320
Product 2 --- | 321

Quantity:

quantity_value | entity_id
1 ------------ | 320
4 ------------ | 321

Tags:

tid | entity_id
12  | 320
13  | 321
15  | 320

I am using db_query for my query:

So let's say that I want to filter on product that has Tags tids equal to 12 and 15 (product 1)

$query = db_query("
  SELECT n.title, SUM(q.quantity_value)
  FROM {node} n
  JOIN {quantity} q
  ON q.entity_id = n.nid
  LEFT JOIN {tags} t
  ON t.entity_id = n.nid
  WHERE t.tid IN (12, 15)
  GROUP BY n.title
  HAVING COUNT(DISTINCT t.tid) = count(12,15)
");
$results = $query->fetchAll();

That query returns me 1 row, with product 1, but quantity = 2, instead of 1. I have tried sub querying the "IN" and multiple other stuff, but nothing has worked. The only solution I have now is to divide SUM(q.quantity_value) by COUNT(n.title), it would work, but I think there is better way to do it :)

Thanks for your help!

Ed

Hum... Classic "I am sure I tried that before and it wasn't working"... I spent an entire day looking for the solution, and find it 5 minutes after posting here :)

$query = db_query("
  SELECT n.title, SUM(q.quantity_value)
  FROM {node} n
  JOIN {quantity} q
  ON q.entity_id = n.nid
  WHERE EXISTS (SELECT *
    FROM {tags} t
    WHERE t.entity_id = n.nid
    AND t.tid IN (12, 15))
    HAVING COUNT(DISTINCT t.tid) = count(12,15)
  GROUP BY n.title
");
$results = $query->fetchAll();

Subquery was the way to go (if anyone has something better to suggest, I would love to hear it).

Thanks,

Ed


Group items in Views by value in Field Collection I have a content type (content type X) containing a Field Collection field.
This Field Collection field consists of a Node Reference (content type Y) field and a text field.

I would like to create a view where I group items based on the nodes selected in the field collection field.

An example:

Node 1:

Field collection:

Node ABC : text here
Node BCA : text here

Node 2:

Field collection:

Node BCA : text here
Node CDE : text here

The view showing these items would look like the following:

ABC

Node 1

BCA

Node 1
Node 2

CDE

Node 2

How would I be able to create a view like this?
I'm sure I need to use relations, but honestly I have no idea where to start.

Thanks for any help in advance!

Very nice question!
I give you every detail step by step, including the structure of content types.
First install Field Collection Views module. This will add a default View in Views menu. Its name is field_collection_view. Clone this view (recommended) or edit the existing one.
 Content Type X
This is the Manage Fields of this content type

It contains a Title and a Field Collection field that I called xxx. This is the xxx

It only contains an Entity reference to y, I called it field_reference_xxx (you can also include other fields, for our purpose it is unnecessary).
Content Type y
It only has Title field and nothing else.
I inserted the exact content you included in the question.
Node1 (x) to abd and bca
Node2 (x) to bca and cde
field_collection_view View
This is the main work to do. The default View of field collection is in /admin/structure/views/view/field_collection_view path. Open it.
First you need to add two Relationships :

Entity Reference: Referenced Entity
A bridge to the Content entity that is referenced via field_reference_xxx

Make sure to select referenced  not referencing
and the second one:

Field collection item: Entity with the xxx (field_field_collection)
Relate each Content using xxx.

I supposed the Contextual Filter for selecting is Title of content type y, right? so let's do it. add Title as contextual filter and make it to use (Content entity referenced from field_reference_xxx) Content: Title relationships.
So far so good. Now go to Fields section. select Title as a field and make it to use (field_field_collection) relationships. I mean this

AND NOW OUR WORK IS DONE!
In the aggregate This should be your configuration

For testing I give you the following screenshots to make sure it works
Without any value

With bca

With abc

and cde

Good Luck!


Node listing on taxonomy term pages I've created two taxonomy vocabularies e.g. "One" and "Two" and I've added 5 terms by these vocabularies.

Then I created two taxonomy category template files, but I have one big problem.

Example: term named "Apples" from vocabulary "One" list all nodes that have this term.

I'm trying to get url and node name, trimmed body text and pager so this term page it shows 10 nodes and there is a pager at the bottom.

I created view block, but it's huge job to create blocks for each terms etc..

So how I can list all nodes on these term pages?

You are not supposed to create view block for each term, your view can take dynamic argument for taxonomy and will return results accordingly, All you need is to have contextual filter setup for your views.


Drupal hash salt / private key is changing? I've created a token that I store in database, here is how I create my token :

$token = drupal_hmac_base64($pid . " " . $order_id . " " . $solde, drupal_get_private_key() . drupal_get_hash_salt());

And then when a user go to my url that looks like that :

https://mycustomwebsite.com/order_id/token

With the token and another value : order_id, I get the line in my database with the order_id and then I create a new token :

$new_token = drupal_hmac_base64($pid . " " . $order->order_id . " " . $solde, drupal_get_private_key() . drupal_get_hash_salt());

I compare these two tokens just for a verification to grant the access or not.

This works fine but couple days after when I try to go on a link the access doesn't work anymore. When I look at the new_token generated for verification it's not the same !
But the value used to make this token (pid, order_id and solde) are the same, so here is why I ask my question.

Does the drupal_get_hash_salt() or drupal_get_private_key() can return different values in the time ?

drupal_get_hash_salt() is either:

a manually-entered value stored in your settings.php
...or (by default) a hash of your serialized-DB config

drupal_get_private_key() is either:

a stored variable called drupal_private_key if it's set
...or (by default) randomly generated bytes (that are saved to drupal_private_key after generation)

So, either one can change their value if:

You changed your DB config (if $drupal_hash_salt isn't manually set in settings.php).
You've lost/removed drupal_private_key from the variable DB table.


Hiding regions for a node page without creating a unique twig file for that node? In Drupal 7 I could hide regions as reactions to certain conditions with Context; Here is a pseudocode to explain what I actually did with this module:

  If $node = 1;

  Than programmatically hide $region = sidebar;

In Drupal 8 for some reason, at least in this era, this functionality has been removed from the module. You can no longer hide regions as a reaction to whatever condition.

Hiding regions is still possible with CSS but it should be noted that programmatically hiding regions is better than CSS hiding as it is more swift and sound, as well as more elegant.

What I've tried instead:

Given the fact Context 8 doesn't include that functionality, I tried to use CSS to hide the region in the given node; I knew from Drupal 7 that if you are inside an node and go to the DOM tree, you can see a unique node class that will serve you in such a particular CSS action (hiding a region in a particular node).

In my Drupal 8 site I went to the DOM but didn't quite find such a class (as appears in Drupal 7 sites).

Therefore I tried using what worked for me in Drupal 7 wondering if from any case it just no longer appear in the DOM. I went to my CSS file and added:

.page-node-364 .region-sidebar-first {display: none !important}

It didn't work, nor similar tryings such as:

#node-364 .region-sidebar-first {display: none !important}
.node-364 .region-sidebar-first {display: none !important}
.364 .region-sidebar-first {display: none !important}

And so forth...

Other actions on that node class variations (neglecting region-sidebar-first) also didn't work even with !important declarations on the CSS and what I tried seemed just to be invalid.

I flushed all caches after each try.

Why I'm confused:

What I did saw at DOM and used as a class didn't cause any effect (.364 as mentioned above):

My question:

Due that Context isn't the solution this time, and that seemingly, no usable id or class appears in DOM, I thus ask professional themers here if it is even possible to hide regions for a node in Drupal 8, solely through the CSS, without creating a unique twig file to that particular node.

4k4 suggestion to use the preprocess_page Drupal-function can be done like this:

Preprocess functions go in your themes themeName.theme file, you may need to create this file if your theme does not have one - be sure to clear the Drupal cache after adding or changing code in this file.

function theme-name_preprocess_page(&$variables) {
  // Set the node ID if we're on a node page.
  $nid = isset($variables['node']) ? $variables['node']->id() : '';

  // Unset a region for one node ID.
  if ($nid == '7') {
    unset($variables['page']['sidebar_second']);
  }

  // Unset a region for multiple node ID's.
  if (in_array($nid, ['1','2','3'])) {
    unset($variables['page']['sidebar_first']);
  }
}

If you would rather use CSS (not a bad technique at all), you can add path classes to body also from theme-name.theme, but this time via the preprocess_html function:

use Drupal\Component\Utility\Html;

function theme-name_preprocess_html(&$variables) {
  // Add path classes to body.
  $path = \Drupal::request()->getPathInfo();
  $path_args = explode('/', $path);
  if (count($path_args) >= 3) {
    $variables['attributes']['class'][] = 'path-' . Html::cleanCssIdentifier(ltrim($path, '/'));
  }
}


Creating "view" of "user blogs" specific to a user On a user "my account" page, I want to create a view block which lists the blogs created by that user only. Is there a way to accomplish this ?

There are solution for it by using Contextual Filter in views. Follow this -

Create a new content view and limit it to the content type you want.
Uncheck "Create a page" and check "Create a block." Select the format you want.Click "Continue & edit."
Add a contextual filter for "Content: Author uid.". Do this --

Under "When the filter value is not available," select "Provide a
default value," and select "User ID from URL" from the dropdown.
Because blocks don't understand contextual filters very well, the view
won't work properly without this default value, and all posts of the
given content type will show on all user pages (not just the user's
own posts).
Under "When the filter value is available or a default is provided,"
check "Specify validation criteria" and select "Basic validation" as
the validator. Select "Hide view" from the dropdown.

Save your view.
Assuming that you created a block display, the block will now be available on the Blocks page. Go there and open it.
Set your block to display on all user pages (/user/*) in the correct region. Save the block.
Your block should now appear on all user pages, showing the content written by each user.

Let me know the result if it works fine :)


Why, while developing a module, do I get an error for not specifying a handler when one exists? Receiving the error "entity type did not specify a access handler", even though the entity type definitely does specify an access handler, like so:

/**
 * @ConfigEntityType(
 *   handlers = {
 *     "access" = "Drupal\give\GiveFormAccessControlHandler",
 *   },
 * )
 */

And the file src/GiveFormAccessControlHandler.php is in place and ready to handle access.

Why won't Drupal 8 see it?

Drupal 8 made the decision to be fast by default and use the APC Classloader if it is available.  It is faster, but it doesn't necessarily catch changes as you make them.  To not have to restart your web server during development, you can set your local environment to not try to use a better-for-production class loader.

For instance, in local.settings.php add:

$settings['class_loader_auto_detect'] = FALSE;

As documented in settings.php:

  If the APC extension is not detected, either because APC is missing or
  because auto-detection has been disabled, auto-loading falls back to
  Composer's ClassLoader, which is good for development as it does not
  break when code is moved in the file system.

In the issue where this change was made, Berdir warned that it would stymie developers.  More background information at what to do when developing a Drupal 8 module and a class file just isn't being loaded even though it is definitely there.


Is it possible to have a specific page.tpl.php for mobile devices? Background is, that the "desktop-version" of the website will have some external advertisements added via javascript-tags. Due to the nature of these adverts, they don't scale down with the rest of the responsive elements. I could just hide them via CSS and Media Queries, but then they would load anyway and slow down loading times.

If these advertisements are in a block, you can put some intelligence in that block, eg:

if USER_AGENT == MOBILE DEVICE
   return // eg, nothing
else
   return the AD

This way, the ad is never delivered on the mobile device.  The USER AGENT can be gleaned from $_SERVER['HTTP_USER_AGENT'], eg:

if (strpos($_SERVER['HTTP_USER_AGENT'],'iPhone')!==FALSE) {
   // I'm an iPhone
}


How to add image field to module install file How to add image field to database in module install file? I found on api documentation, that type is image, so tried the following code:

function profile_bg_schema() {

$schema = array();

$schema['profile_bg'] = array(
  'description' => 'The table containing backgrounds',
  'fields' => array(
    'bid' => array(
      'description' => 'The primary identifier for the background.',
      'type' => 'serial',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
    'image' => array(
      'description' => 'The background image.',
      'type' => 'image',
      'not null' => TRUE,
      'default' => '',
    ),
    'class' => array(
      'description' => 'The class added to div.',
      'type' => 'varchar',
      'length' => 255,
      'not null' => TRUE,
      'default' => '',
    ),
  ),
  'primary key' => array('bid'),
);

$schema['profile_bg_unlock'] = array(
  'description' => 'User - background - active table',
  'fields' => array(
    'uid' => array(
      'description' => 'User ID.',
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
     'bid' => array(
      'description' => 'Background ID.',
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
    ),
    'status' => array(
      'description' => 'The primary identifier for the background.',
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
      'default' => '0',
    ),
  ),
);

return $schema;

}

First I was getting an error about image field, now module becomes ON, but nothing changes in database.

---- EDIT ----
Error below. It looks like Drupal do not know what type of field should create in database.

   Notice: Undefined index: image:normal w DatabaseSchema_mysql->processField() (linia 205 z C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\drupal\includes\database\mysql\schema.inc).
    PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DEFAULT NULL COMMENT 'Background Img.', `class` VARCHAR unsigned NOT NULL DEFAU' at line 3: CREATE TABLE {profile_bg} ( `bid` INT unsigned NOT NULL COMMENT 'bg ID.', `image` DEFAULT NULL COMMENT 'Background Img.', `class` VARCHAR unsigned NOT NULL DEFAULT '' COMMENT 'css class for the background.', PRIMARY KEY (`bid`) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8 COMMENT 'background table'; Array ( ) w db_create_table() (linia 2720 z C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\drupal\includes\database\database.inc).

You are reading the wrong documentation. Please read Data Types instead. There is no image type for database field.

The available data type are:

serial
int
float
numeric
varchar
char
text
blob

Since Drupal manage file (including image files) in file_managed table with key fid. What you need is to create a int column for storing the value of foreign key fid. The column definition should be:

'image_fid' => array(
  'description' => 'The {file_managed}.fid being referenced in this field.',
  'type' => 'int',
  'not null' => FALSE,
  'unsigned' => TRUE,
),


SORT CRITERIA by GROUP BY datepart in Views In views I have my items being sorted by date and then relevancy .  Although unless the items are posted at exactly the same time this means that the relevancy score is made redundant.

I can’t seem to add a date boost to the relevancy but have figured if I could Sort the date in blocks of time ( i.e. a day ) this would give me the results that I’m looking for.  Then items to be sorted by the day they are posted; and then by relevancy.

I understand that in SQL I can use ‘ GROUP BY datepart’ to do this.  Has anyone done anything like this in Views.

I couldn't find any way to do this using the options in the View UI. One way to accomplish it, however, might be to add an additional field to your content type that stores only the day/month/year for the date (set the default to 'now' so that you don't have to manually enter the date, and set the field to 'hidden' on the display options), and then you could use that field to group by in the view.


Is there a way to migrate only nodes? I don't want to make a full migration. I want to migrate only and solely Nodes (preferably with their Metatag metadata as well). Not Views, Not Panels, not Contexts, not URL redirects - Only Nodes...

I ask this after encountering some troubles in full D7>>D8 upgrade and when using the Drupal Upgrade module (I even opened a thread regarding it here in DA). Therefore, I am looking for ways to make only a partial migration, or to make migration in parts.

Is it possible regarding to nodes?

You don't need to do a full migration. You can initialize the Upgrade process by connecting to the old site and it will create migrations. Then you can, instead of executing them automatically, run just some of them with the UI provided by the upgrade_tools project ( I think?).

However, migrations have dependencies. To be able to run the node migration, by default you have to run a few others, e.g. users, text formats and also the fields.

You can try to change that by editing the created migrations either with drush cedit or export/import. I believe someone is also working on an UI for it.

You can also customize any mapping and how fields are migrated. The default behavior is that every field and configuration is migrated 1:1 but  to be honest, I can't imagine that's what most sites will want to do. Instead, I imagine they build a new D8 site and then import the content.

See the migration documentation. There are also plenty of blog posts available already around that topic but it's not a trivial thing to do.

https://drupalize.me/blog/201511/simple-drupal-7-drupal-8-migration
https://www.advomatic.com/blog/transforming-data-in-a-drupal-8-migration-step-by-step

Alternatively, you can try to export/import your content, as mentioned in the Comments, Feeds is not quite ready yet, but you could use a views export and import by writing some custom code.


How to create a simple Drupal module that updates a custom node field I have a custom node type "product" which has a custom Decimal type field "field_price".

I would like to create a simple module in Drupal 8 to set this value to 10.75 every time I create or update a node.

edit

I have now restructured the module as follows. These are the files / folder structure I have (excluding the .info.yml) :

Module folder:
/modules/updateprices

Routing.yml:
/modules/updateprices/update_prices.routing.yml

Routing.yml code:
update_prices:
    path: /updateprices
    defaults:
        _controller: 'Drupal\updateprices\Controller\UpdatePricesController::update_prices_node_presave'
    requirements:
        _permission: 'access content'

Controller code:
/modules/updateprices/src/Controller/UpdatePricesController.php

<?php
namespace Drupal\updateprices\Controller;
use Drupal\Core\Entity\EntityInterface;

class UpdatePricesController  {
        function update_prices_node_presave(EntityInterface $entity) {

          $entity_type = 'node';
          $bundles = ['product'];

          $fld_price = 'field_price';
          if ($entity->getEntityTypeId() != $entity_type || !in_array($entity->bundle(), $bundles)) {
            return;
          }
             $entity->{$fld_price}->setValue(10.75);
        }
}

I am now getting an error:

  ReflectionException: Class
  Drupal\updateprices\Controller\UpdatePricesController does not
  exist in ReflectionMethod->__construct() (line 123 of
  /home/website.com/core/lib/Drupal/Core/Entity/EntityResolverManager.php).

Hooks, in a module, only work inside the .module file.

You don't need a controller nor a routing file here, these are used for creating pages.

/modules/updateprices/updateprices.module

<?php

use Drupal\Core\Entity\EntityInterface;

function update_prices_node_presave(EntityInterface $entity) {

  $entity_type = 'node';
  $bundles = ['product'];

  $fld_price = 'field_price';
  if ($entity->getEntityTypeId() != $entity_type || !in_array($entity->bundle(), $bundles)) {
    return;
  }
  $entity->{$fld_price}->setValue(10.75);

}


form_set_error: How to set for an array Drupal 6 Array
(
    [items] => Array
        (
            [0] => Array
                (
                    [nid] => 164
                    [module] => uc_product
                    [remove] => Remove
                    [title] => Strokes1
                    [data] => a:4:{s:10:"attributes";a:0:{}s:9:"shippable";s:1:"0";s:12:"restrict_qty";s:1:"0";s:6:"module";s:10:"uc_product";}
                    [qty] => 2
                    [description] =>
                    [cart_item_id] => 200
                )

            [1] => Array
                (
                    [nid] => 165
                    [module] => uc_product
                    [remove] => Remove
                    [title] => Strokes2
                    [data] => a:4:{s:10:"attributes";a:0:{}s:9:"shippable";s:1:"0";s:12:"restrict_qty";s:1:"0";s:6:"module";s:10:"uc_product";}
                    [qty] => 1
                    [description] =>
                    [cart_item_id] => 203
                )

            [2] => Array
                (
                    [nid] => 166
                    [module] => uc_product
                    [remove] => Remove
                    [title] => Strokes3
                    [data] => a:4:{s:10:"attributes";a:0:{}s:9:"shippable";s:1:"0";s:12:"restrict_qty";s:1:"0";s:6:"module";s:10:"uc_product";}
                    [qty] => 1
                    [description] =>
                    [cart_item_id] => 204
                )

        )

    [update] => Update cart
    [checkout] => Checkout
    [form_build_id] => form-5c5819d5418df14f08153f1ce15d6acc
    [form_token] => 2341b9068b8ffb7454d267b22e572d7d
    [form_id] => uc_cart_view_form
)

I'm using form_set_error to display the error messages if there is no product.

My Issue is:

For example, I am having 3 products in the checkout page.

When I clicks submit I need to validate that all the products are available.

Here, let us consider if the second product is not available I am showing the error message "Product Stroke 2 is not available".

But all the check boxes in the cart is highlighted

Because I had set form_set_error to items element.

How can I set form_set_error for every individual element.

What I have given to display error message:

form_set_error('items', 'Not available');

Kindly guide me how to resolve the issue. I am using ubercart module with drupal 6.

There is a comment on the API page for form_set_error which explains how to set a form error on a subelement of a form item.

From the comment:

form_set_error('field_name][i][value', t('Your message'));


How can I set the value of a taxonomy term reference to multiple terms using PHP? This question describes how to set the value of a term reference field using PHP.  But what do I do if I want to set the value of a term reference field in the user profile to multiple terms?

I am trying to set the value to term IDs 27 and 28.  Here is my code so far:

$user->field_yourfield_name[LANGUAGE_NONE][0]['tid'] = 27;
user_save($user);

Assuming the field is set up to accept multiple records...

$user->field_yourfield_name[LANGUAGE_NONE][0]['tid'] = 27;
$user->field_yourfield_name[LANGUAGE_NONE][1]['tid'] = 28;
// etc

Or you can just keep appending to the array (without knowing the next available index) like this:

$user->field_yourfield_name[LANGUAGE_NONE][]['tid'] = 27;
$user->field_yourfield_name[LANGUAGE_NONE][]['tid'] = 28;


How can I slideDown with #states? I have a form using "#states" (in the Relation module), and it works, but it kind of jumps around. A nice slideDown would be so much better.

How can I do that instead of just making it visible?

I assume you're using the visible state?

The code that is responsible for doing this is in states.js:

$(document).bind('state:visible', function(e) {
    if (e.trigger) {
      $(e.target).closest('.form-item, .form-submit, .form-wrapper')[e.value ? 'show' : 'hide']();
    }
  });

As you can see, it calls show/hide without any configurable parameters, which means that it can't be easily changed.

However, the comment above that block is interesting:

/**
 * Global state change handlers. These are bound to "document" to cover all
 * elements whose state changes. Events sent to elements within the page
 * bubble up to these handlers. We use this system so that themes and modules
 * can override these state change handlers for particular parts of a page.
 */

If I understand this correctly, you can override the event handler for your specific page element, e.g. the form or even single form elements, by adding something like this:

$('form.your-form-class').bind('state:visible', function(e) {
  if (e.trigger) {
    $(e.target).closest('.form-item, .form-submit, .form-wrapper')[e.value ? 'slideDown' : 'slideUp']();
  }
});

I guess you will need to return FALSE to prevent that the event bubbles up further in the DOM tree.


OG menu default links are not adding up I am using og_menu 7.x-3.x-dev I am trying to create some default links to the og menu, but links are not adding.With a new group node its creating the og menu but the default links are not coming.Do I need to apply any patch? Thanks in advance. On the og menu settings page I have checked the "Automatically create a OG Menu for new Organic Group" checkbox and in the default links section I have tried adding absolute url and internal drupal path but no success.Am I missing some settings.

I figure out later the link I was adding were actually the nodes I was creating programmatically as a new group is created and I was creating the path alias programmatically as well, when i check the db table menu_links I found there was no router for these node menu links,so to make them work I am putting the default links as external urls for example http://yoursite/node/test, I believe there must be a better way to get this done,good for now.


Insert row into a view I have a view which fetches nodes from content type A, arranges them in a grid and uses a displaysuite buildmode to render them...nothing fancy so far. Now I want to insert a specific node of content type B at a specific position in the grid...like this:

+----------+----------+
|          |          |
|  type A  |  type A  |
|          |          |
+----------+----------+
|          |          |
|  type B  |  type A  |
|          |          |
+----------+----------+
|  type A  |  type A  |
.          .          .

I'm not sure where to start. I was hoping there would be some hook, preprocess function or whatever where I get an array of node objects to insert my special node into which then gets rendered...

I found the function I was looking for. You can insert nodes in the results array just after the query has been executed.

This goes in the module:

function modulename_views_post_execute(&$view) {
  // wait for the right view
  if($view->name == "name_of_the_view") {
    // create the object you want to insert in the result
    $temp = new stdClass;
    // creation date of that node
    $temp->node_created = 1314807643;
    // nodeID
    $temp->nid = 13;

    $new_result_array = array();
    $i = 0;
    foreach($view->result as $single_result) {
      if($i == 2) {
        // insert the extra node at 3rd position
        $new_result_array[] = $temp;
        $new_result_array[] = $single_result;
      } else {
        $new_result_array[] = $single_result;
      }
      $i++;
    }
    // replace the old result array
    $view->result = $new_result_array;
  }
}


Migrating passwords from WordPress I am using the Feed module in Drupal to import the list of my users from WordPress and I have faced a big problem: The password field mapping in the Feed module says "unencrypted password", and there is no way of decrypting phpass WordPress passwords into a CSV file (it is not even safe). What should I do?

Instead of trying to decrypt users passwords, and then re-encrypt them to be stored in drupal. Why dont you:

import the users all over into drupal
get all users to reset there own passwords (through the normal email method) when they next try to login


Entity Reference Autocomplete module: hook_entity_info definition? I have tested the Entity Reference Autocomplete module by defining a form field of type entityreference (via hook_form) on the user entity - and it works as advertised.

When I try it on my own entity an AJAX error is thrown.

My form element definition:

$form['name'] = array(
  '#title' => t('Ground'),
  '#type' => 'entityreference',
  '#era_entity_type' => 'ground',
  '#size' => 32,
);

I can't imagine the problem is my entity's base table. So, the only thing I can think of, which may be the source of the error, is my hook_entity_info definition:

/**
 * Implements hook_entity_info().
 */
function scorebook_entity_info() {
  $return = array(
    'ground' => array(
      'label' => t('Ground'),
      'controller class' => 'EntityAPIController',
      'base table' => 'scorebook_ground',
      'entity keys' => array('id' => 'grid'),
    ),
  );
  return $return;
}

It contains the minimum keys. Do I need to add some other keys to my definition? If anyone knows of a working example of this module working with a custom entity that may help too. Thanks.

UPDATE:

Here is the correct hook_entity_info definition for anyone who doesn't want to read everything below. You need to define an access callback function, also, to return either TRUE/FALSE accordingly.

'ground' => array(
  'label' => t('Ground'),
  'controller class' => 'EntityAPIController',
  'base table' => 'scorebook_ground',
  'entity keys' => array(
    'id' => 'grid',
    'label' => 'name',
  ),
  'access callback' => 'scorebook_access',
),

I'm the module maintainer. Thanks for using the module, hope you're finding it useful. You need to add a 'label' key to your entity definition, like:

'entity keys' => array(
  'id' => 'grid',
  'label' => 'table-column-that-contains-the-human-name-of-entity',
),

With that, and after flushing caches, etc, your form should work fine. The reason is that entityreference_autocomplete assumes that (as a best practice), every entity would have, apart of the ID, which will be normally just a number, some friendly way to identify it through a label. Therefore, you need that on your custom entity.

However, I get that not everyone might want / need that 'label' key or a column for the label in their schema, for whatever reason, and I've added support to the module to work without that. That bit is on the dev version on the module, and will be rolled out in the next stable version. So it's up to you, to define a column for the 'label' key in your schema, or download the dev version, or wait a  couple days for the stable release that supports entities without the 'label' key.

Cheers!


Embedding a view in user edit form How can I embed a view inside a user edit form depending on that user's role. I have used the Context module but it does not have the right conditions.

At the moment is uses the (user page -> User account form) condition. I cannot use the User role condition because it is for the currently logged in user.

You can use hook_form_alter and views_embed_view to alter the form and add the markup for a view.


ctools_modal_render() in a condition I have the following code in my custom.module (using it in hook_init()):

if ($js) {
  // Required includes for ctools to work:
  ctools_include('modal');
  ctools_include('ajax');
}

if (user_is_logged_in()) {
  $title = 'hello';
  $output = 'more hellos';
  ctools_modal_render($title, $output);
} else {
  return NULL;
}

Problem is if even i'm not logged it shows to me a modal windows with infinite loading text. How to unset ctools_modal_render() if i am not logged in?

You can use below code to redirect anonymous user to user login page.

if ($js) {
  // Required includes for ctools to work:
  ctools_include('modal');
  ctools_include('ajax');
}

if (user_is_logged_in()) {
  $title = 'hello';
  $output = 'more hellos';
  ctools_modal_render($title, $output);
} else {

  ctools_ajax_command_redirect('user/login');
  ctools_modal_command_dismiss();

}

Or, If you do not want to display popup to anonymous user, then you need to check user is anonymous or not before redering the ctools popup link.

<?php if (user_is_logged_in()): ?>
Link 1
<?php else: ?>
Login
<?php endif; ?>


How to set webform message below the submit button? I need to render the HTML of the errors messages below the submit button for styling purpose. I find out about Inline Form Errors; however, this will display an error message after the field and not after the submit button.

Any idea how can achieve this?

Try form alter method you can add text like following:

 $form['some_text'] = array(
      '#markup' => '
Some text
'
    );

Hope it will help!!


How to display a block in twig (D8) I read the other similar questions, but it didn't work.

I created a block in a region and I want to display that same block on my custom page (inside the twig).

I'm using this code to load the block:

$block = \Drupal::entityTypeManager()->getStorage('block')->load('block_id');
$block_content =  \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);

and I'm trying to build it like this:

$build['page'] = array(
      '#type' => 'inline_template',
      '#template' => $template,
      '#form' => $block_content,
);
return $build;

My twig file is like this:

{{ form }}

But nothing is displayed...
What am I doing wrong?

Thanks in advance.

To make the form variable available in the Twig template you need to supply a context like follows.

$build['page'] = [
  '#type' => 'inline_template',
  '#template' => $template,
  '#context' => ['form' => $block_content],
];

Generally, I would recommend using custom #theme hook instead of an inline template.

Another way to render block within a template is using Twig Tweak module.

{{ drupal_entity('block', 'block_id') }}


"Drupal root not found. Pass --root or a @siteAlias in order to see Drupal-specific commands" I have multiple sites inside the same htdocs directory. In one, I removed all the folders except vendor under Web. Now drush will not work (it worked before I moved the folders). But now, it cannot find the database, which is correctly defined in web/sites/default/settings.php
/srv/www/htdocs/jar/drupal # ./drush status
 PHP binary    : /usr/bin/php
 PHP config    : /srv/www/php.ini
 PHP OS        : Linux
 Drush script  : /srv/www/htdocs/jar/drupal/vendor/drush/drush/drush
 Drush version : 10.3.6
 Drush temp    : /tmp
 Drush configs : /srv/www/htdocs/jar/drupal/vendor/drush/drush/drush.yml
 Drupal root   : /srv/www/htdocs/jar/drupal

I am running Drupal 9.0.8 and drush 10.3.6 (in /srv/www/htdocs/jar/drupal). I have removed drush using composer (2.0.3) and reinstalled it (recreating vendor in the process).
/srv/www/htdocs/jar/drupal # ./drush -vvv cr
 [preflight] Config paths: /srv/www/htdocs/jar/drupal/vendor/drush/drush/drush.yml
 [preflight] Alias paths: /srv/www/htdocs/jar/drupal/drush/sites,/srv/www/htdocs/jar/drush/sites
 [preflight] Commandfile search paths: /srv/www/htdocs/jar/drupal/vendor/drush/drush/src
 [debug] Starting bootstrap to site [0.04 sec, 8.17 MB]

In BootstrapHook.php line 32:
  [Exception]
  Bootstrap failed. Run your command with -vvv for more information.
Exception trace:
  at /srv/www/htdocs/jar/drupal/vendor/drush/drush/src/Boot/BootstrapHook.php:32
 Drush\Boot\BootstrapHook->initialize() at /srv/www/htdocs/jar/drupal/vendor/consolidation/annotated-command/src/Hooks/Dispatchers/InitializeHookDispatcher.php:44
 Consolidation\AnnotatedCommand\Hooks\Dispatchers\InitializeHookDispatcher->doInitializeHook() at /srv/www/htdocs/jar/drupal/vendor/consolidation/annotated-command/src/Hooks/Dispatchers/InitializeHookDispatcher.php:36
 Consolidation\AnnotatedCommand\Hooks\Dispatchers\InitializeHookDispatcher->callInitializeHook() at /srv/www/htdocs/jar/drupal/vendor/consolidation/annotated-command/src/Hooks/Dispatchers/InitializeHookDispatcher.php:29
 Consolidation\AnnotatedCommand\Hooks\Dispatchers\InitializeHookDispatcher->initialize() at /srv/www/htdocs/jar/drupal/vendor/consolidation/annotated-command/src/CommandProcessor.php:145
 Consolidation\AnnotatedCommand\CommandProcessor->initializeHook() at /srv/www/htdocs/jar/drupal/vendor/consolidation/annotated-command/src/AnnotatedCommand.php:296
 Consolidation\AnnotatedCommand\AnnotatedCommand->initialize() at /srv/www/htdocs/jar/drupal/vendor/symfony/console/Command/Command.php:221
 Symfony\Component\Console\Command\Command->run() at /srv/www/htdocs/jar/drupal/vendor/symfony/console/Application.php:1018
 Symfony\Component\Console\Application->doRunCommand() at /srv/www/htdocs/jar/drupal/vendor/symfony/console/Application.php:271
 Symfony\Component\Console\Application->doRun() at /srv/www/htdocs/jar/drupal/vendor/symfony/console/Application.php:147
 Symfony\Component\Console\Application->run() at /srv/www/htdocs/jar/drupal/vendor/drush/drush/src/Runtime/Runtime.php:118
 Drush\Runtime\Runtime->doRun() at /srv/www/htdocs/jar/drupal/vendor/drush/drush/src/Runtime/Runtime.php:49
 Drush\Runtime\Runtime->run() at /srv/www/htdocs/jar/drupal/vendor/drush/drush/drush.php:72
 require() at /srv/www/htdocs/jar/drupal/vendor/drush/drush/drush:4

I looked at all the above suggestions, but am stuck. Drush works perfectly on my other 5 sites...

A missing composer.json file was the solution for me.


`Routing` folder not present inside `Drupal\Core\` I am trying to port a module from D7 to D8.

Since hook_help() uses routes instead of paths in D8, so the line use Drupal\Core\Routing\RouteMatchInterface; is added at the beginning of the code as mentioned on this page.

But the thing is that no folder named routing exists inside my Drupal\Core\.

Questions.

Am I supposed to add that folder myself?
How will I configure
    RouteMatchInterface file.

That is the namespace. It's actual location in the file system is /core/lib/Drupal/Core/Routing. The autoloader knows where to look via the namespace.


How to add extra css in style.css file? I want to add extra css for my images (I just want to set float:left to them).

I've checked where I need to add my CSS i.e.<div class="field field-name-field-gallery field-type-image field-label-above">.

So should I directly add this class name in style.css file or should it go somewhere else?

Yes, if style.css is a CSS file that's loaded into your page (either by a module or, more likely, your theme) then that's probably a good place for your custom styles.

If you'd rather have your own file for custom styles though, you can just create a file (e.g. custom.css) in your theme folder, and add a line like this to the theme's .info file:

stylesheets[all][] = custom.css

Once you clear Drupal's caches you should see the new stylesheet included in all pages using that theme.


Views output does not match actual output I have a view that I finally got to work in the view preview. Then I go to the link that should give me the same result at the preview and I get the no results behaviour. I double-checked that the view is saved and I cleared the cache.

When I visit the url in the preview area, I do not get the result in the preview. Any ideas of what I did wrong?

I found the answer. Honestly, I was being a derp and a noob. Maybe I just needed time to think about it before posting a question. I will answer it here in case anyone else runs into the same issue.

Make sure you do not have any other views using the same url pattern!

This is a view I have been trying to make work for a while because I needed to reference two different vocabularies that were attached to the content type: location and department. It proved to be slightly more complicated than a typical view because of the two vocabularies and because of Drupal 8 which I am still getting used to. I forgot to delete or disable the previous view I was trying to figure it out in. When I deleted the old view that didn't work (but used the same url pattern), everything was fine.


exposed filter result : how to check the results is lesser than 20 or greater than 20...? i have created the content type named candidate_profile, included fields like Current_Salary_Range and  i have created a view named display_candidate and also i am using better exposed filter for current_salary_range field the filtered the result print in view throw the Header->Global:Result summary.hence how should i proceed to check the results is lesser than 20 or greater than 20...?

using the below code to check the result is greater than or lesser than 20

global $pager_total_items;
  print $pager_total_items[0] ;

if($pager_total_items[0]>20)
  {
    print 'Result is greater than 20';
  }
  else
  {
    print 'Result is lesser than 20';
  }

In this code put into your theme folder like mytheme/templates/page.tpl.php file.

but this is working only that particular theme because of i write that code into mytheme page.tpl.php file thats why...


Check activity of authors during period I would like to have some sort of management system in the control panel where the management people can view the activity of the authors during a certain period.

So: A person with a certain role (management) must have a management tab in his administration menu where he can see the names of all authors + their amount of articles they have created during a certain period, where the manager can choose the start and enddate of this period.

Example:

Manager chooses:

1 september 2015 - 30 september 2015

and then he gets an overview of all authors and their amount of articles made that month.

Is there a module by any chance that already has this?

Well, to those who might wonder the same as me: apparently there is no module yet that does this, which surprises me, as it seemed such a basic request to me.

So you have to do it yourself.

For those who need it, I hereby give you my own solution, but ofcourse other possibilities are available.

I made this with a combination of views & total control module.

Total Control gives you a nice dashboard which you can fill with views. For the view itself, you just have to use the aggregate function and a relationship.

Relationship: 'Content: Author'
Use AJAX: Yes (this is to make sure filters can be exposed in blocks)
Use Aggregation: Yes
Make a table with following fields and filters:

Field: '(author) User: Name'
Field: 'Content: Nid' (Aggregation: Count (Distinct))
Filter: 'Content: Post date' => Exposed

extra fields are possible, like I have also added the date of the last article that person made in this specific period, which could also be handy for activity monitoring. To do this, use the field 'Content: Post date' and add the aggregation setting MAX to it.

Hope this helps others in case they are looking for something similar that is easy to maintain, without having to invent things that already exist.


Deduping Views by forcing Views to add a simple GROUP BY to a query In D8, I need a way to "dedupe" a view with a relationship. This involves a "Course" content type, and a "Sessions" entity (actually, a Commerce Product) that points back to the Course.

I've tried to create views that are based off the content type and related to the Session entity, and visa versa.  In both cases, what I really want to do is to get a list of courses searched by both the attributes of the Course (let's say, type of course) and of the session (location).

Since Course :: Session is 1 :: N, we're getting N rows for each Course. This is not what we want. Using the Advanced settings has proved useless so far. Query Setting "Distinct" does not dudupe. The Field Format Setting "Grouping field" does not appear to trigger a GROUP BY in the query.  And using Aggregation creates a monster GROUP BY that appears to pull in just about all the fields in the tables, with no way to remove the useless fields from the GROUP BY.

Here's what I'd like to do: use a simple GROUP BY (say, the title of the Course), and compare the entity ID of the sessions with the minimum entity_id of that group of sessions; if it's not equal, I want to exclude the row either in the WHERE clause or in a HAVING clause if it will work. I'm trying to modify the query via the views hook

function my_module_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'course_listing') {
    $title_alias = 'alias_to_content_table.title';
    $query->addGroupBy($title_alias);
  }
}

The problem here is that while the code is definitely called, the call to addGroupBy() is ignored when the query is actually rendered out. Views thinks I didn't mean it :-)

What exactly do I need to clobber Views with to get it to add a GROUP BY statement?  If I can get it to do that, I can insert a MIN field into the SELECT statement (see http://tech-tamer.com/drupal-7-using-sql-expressions-in-views-3/ for someone's clever idea of how to do that in D7; it appears to work fine in D8, but will generate a bad query w/o the correct GROUP BY).

It turns out that the solution is similar to what I tried: you do need to use hook_views_query_alter.  But playing with GROUP BY is useless unless you can guarantee that you will not be using ORDER BY at all (i.e., you will do no sorting beyond your GROUP BY key).  GROUP BY will contain not only the variable you want to group by; it will also contain every variable you use in ORDER BY.  This appears to be required by the current SQL standard.

The way to do this is this is build your view around the "parent" type ("Course" in my example), and do any filtering you need to do in hook_views_query_alter, using a correlated subquery.  This will look something like this:

function my_module_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {

  if ($view->id() == 'course_listing') {
    $where_clause = <<<WHERE
    (
      SELECT COUNT(*)
      FROM {node__field_session_course} link_to_course
      WHERE node_field_data.nid = link_to_course.entity_id
    ) > 0
WHERE;

    $query->addWhereExpression(0, $where_clause);
  }
}

where node_field_data is the base table for Course.

Since there is no left joins or inner joins with the Session table, there are no duplicates, making the deduping problem go away.


Building a View or Panel(?) from an existing node and customize path and breadcrumb I have this requirement I don't know how to approach.
The site's taxonomy is used in a hierachical way.

I have a Conference content type and the breadcrumbs and url's follow this pattern:

home/conferences/conference-type/continent/conf-title where conference-type and continent are taxonomy terms

A Conference has an image gallery contained in an Image field, which is not visible on the Conference page itself but to a dedicated page located to    home/resources/gallery/conference-type/continent/conference-name

My question is how do I build this page dynamically from the conference node's content ?

I could use a view or a panel and pass the nid contextual filter, but then:

How do I build the path/breadcrumb from the nid passed as argument?
How do I make sure the view is invoked on this specific path?

The base url of the view would be home/resources/gallery/%/%/% this would ensure that the view is invoked only when all three arguments are present.

and Rather than sending one argument to the view you would be seinding three arguments.

Conference Type - The taxonomy term
Continent - The Taxonomy term
conference-name

Since your content would have all three condition to be true you would get the required url. Other wise you can set it to show a page not found or may do some other things as you want.


Exclude more then one date I'm new to Drupal. I'm trying to make a work calendar.

I need to make weekly events in the calendar. And that's working real well but now I want to exclude dates from an event.

Is there a way to select more than one date at time?

I think there are 2 possible approaches, as further explained below (I'm assuming you're using Drupal version 7, not 6).

Use a boolean field to exclude from the calendar

For the content types that you want to include in your calendar, add a boolean field like "Exclude from Calendar" (Y/N). When creating your view, filter out the nodes that have a value of "Y" for this field.

Use 'Views Contextual Filters OR'

Consider module Views Contextual Filters OR (which only has a dev version today). Excerpt from its project page:

  ... provides a views plugin which modify query to support OR conditions for contextual filters.

With that, you might be able to specify the various dates to be excluded, with something like date1 OR date2 OR ... (if you only have a few dates to be excluded o course).

Does this help?


List all node titles to better iterate on a list of names I have a content type called Country and I have to verify what countries already exists in db and save the missing ones, comparing to a variable with all countries ($country_list). I am having trouble accessing countries names of my nodes, that are specified as the content type title.
  $country_list = ['Mexico', 'Tanzania', 'Brazil', 'Camaron'];
  $nodes = node_load_multiple(array(), array('type' => 'country_profile'));
  $nodes_name = node_title_list($nodes);

  foreach ($country_list as $country_name) {
    if (!in_array($nodes_name, $nodes)) {
      // should create new node
    } else {
      // shouldn't do anything
    }
  }

The problem is, when i get the node_title_list() it doesn't return the 'raw title' (see output below)
Output:
    Array
(
    [#theme] => item_list__node
    [#items] => Array
        (
            [0] => Tanzania
            [1] => Mexico
        )

    [#title] => 1
)

How can i do that, so that the output of this list is
Array
        (
            [0] => "Tanzania"
            [1] => "Mexico"
        )

If you just need to create the nodes that don't have a specific title (which I guess it's just a country name), you don't need to use node_title_list(), whose purpose is rendering a list of node titles as links. Just load the nodes and check which titles aren't already used.
$country_list = ['Mexico', 'Tanzania', 'Brazil', 'Camaron'];

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'country_profile')
  // Remove the following line if you don't need to get only published nodes.
  ->propertyCondition('status', NODE_PUBLISHED)
  // Keep the following line, so Drupal won't check if the currently logged-in user has access to the nodes and the fields.
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');
$result = $query->execute();
if (isset($result['node'])) {
  $country_list = array_flip($country_list);
  $nodes = entity_load('node', array_keys($result['node']));
  foreach ($nodes as $node) {
    unset($country_list[$node->title]);
  }
  $country_list = array_flip($country_list);
}

if (!empty($country_list)) {
  // There are nodes that need to be created; their titles are in $country_list.
}

Even better, load those nodes whose title is equal to one of the country names you already have.
$country_list = ['Mexico', 'Tanzania', 'Brazil', 'Camaron'];

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'country_profile')
  // Remove the following line if you don't need to get only published nodes.
  ->propertyCondition('status', NODE_PUBLISHED)
  ->propertyCondition('title', $country_list)
  // Keep the following line, so Drupal won't check if the currently logged-in user has access to the nodes and the fields.
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT');
$result = $query->execute();
if (isset($result['node'])) {
  $country_list = array_flip($country_list);
  $nodes = entity_load('node', array_keys($result['node']));
  foreach ($nodes as $node) {
    unset($country_list[$node->title]);
  }
  $country_list = array_flip($country_list);
}

if (!empty($country_list)) {
  // There are nodes that need to be created; their titles are in $country_list.
}


Paid node checkout plus membership plans for a Drupal site I need a solution to these problems for Drupal 7:

I need to create a website where people can post their classified ads. But the twist is that I don't want the ads to be published until the user has paid for it.

Also I need to create a membership plans per role (E.g. Gold Plan, Silver Plan, etc. for monthly subscription)

Now I have tried a few things like:

I tried using lm_paypal for this purpose. But the issue with lm_paypal is that it does not publish the node after the payment has been made.
The admin has to manually check the paypal IPN and publish the content if the node has been paid for. I do not know module development so I am not able to make these small tweaks.
I tried using ubercart too but the standard issue rises again. The uc node checkout module is still in the dev version for drupal 7 and it works like hell. So many errors :(

So can anybody please come up with an alternate solution where I can achieve both the "Pay to publish" and "Membership plan" functionality on my Drupal 7 site?

Being a great fan of Drupal Commerce, I will suggest you to use it in your instance for this need.

You can use Commerce Node Checkout module for your pay to publish requirement.

For membership requirement, you can set product for each membership type & set rules for it. Create rules on event completing checkout process & put some condition like - product SKU match to membership product SKU, current user type etc. & then add usertype to the user.

You will get many payment related modules with Commerce, so you don't have to worry about any ecommerce feature.


How to set access arguments visible to all i have a simple module which show user to set email frequency but it's content can be seen by only to logged admin users , i want to change it to all the users,in drupal how can i do that

function emailf_menu() {
  $items = array();
  $items['emailfrequency'] = array(
    'title' => 'Manage email Frequency',
    'page callback' => 'emailf_page',
    'access arguments' => array('view content')
  );
  return $items;
}

function emailf_menu() {
  $items = array();
  $items['emailfrequency'] = array(
    'title' => 'Manage email Frequency',
    'page callback' => 'emailf_page',
    'access arguments' => TRUE
  );
  return $items;
}

'acces arguments' => TRUE will allow access to all users, including anonymous


Why is my property being rendered when I don't call render? I have a string property, and HTML is getting rendered instead of a string, even though I don't call render where the property is being accessed.

Twig template:

{{ attach_library('mymodule/video') }}

{% if content.video_url|render %}
  <video>
    <source src="{{ content.video_url }}" type="video/mp4">
  </video>
{% endif %}

As you can see, I'm specifying src="{{ content.video_url }}", NOT src="{{ content.video_url|render }}". Still, the rendered HTML is:

<video>
  <source src="
video.mp4</video>
" type="video/mp4">

Why is drupal rendering HTML instead of a string?

content.video_url contains a build array of the field which Twig renders automatically, including the HTML markup of the field template.

To print the raw string value use the entity object which stores the field, node in node.html.twig

{{ node.video_url.value }}

or paragraph in paragraph.html.twig:

{{ paragraph.video_url.value }}


Odd $_SESSION contents I have a page in Drupal from which I want to be able to read the $_SESSION data to determine the userid and their assigned role. As an exploration I attempted to print to the page the contents of $_SESSION so that I could see what was being stored and what the keys were to retrieve these values.

When I attempt to print to the page using echo print_r($_SESSION);, instead of a set of reasonable session data, I instead get only this:

Array ( [batches] => Array ( [1] => 1 ) )

I had a bit of a Google around to see if I was doing something wrong, and I came across the documentation for session.inc, which says:

  These functions should not be called directly. Session data should instead be accessed via the $_SESSION superglobal.

So it seems that, while Drupal wants me to use $_SESSION to retrieve the session data, I can't do this because my $_SESSION data has only this odd pair of nested one-element arrays that store only the number 1.

I also came across some reports that not having the uid 0 in your users table can cause similar issues, so I have checked the users table and I do indeed have user 0.

Any ideas what is going wrong here?

Thanks.

The $_SESSION variable contains values set by Drupal; in your case, $_SESSION['batches'] is the value set by the Batch API. Drupal, although, doesn't use the session to store the user ID; that value is stored in the $user global variable, as cilefen correctly said in his comment.

global $user;
$uid = $user->uid;
$roles = $user->roles;

Keep in mind that the $user global variable doesn't contain a fully-loaded user object; to get that, you need to use the following code.

$account = user_uid_optional_load();

$account will contain every field associated with the user entity, and any property attached to the user object from third-party modules.


search_form_alter NOT BLOCK I was looking the insertion point to change some stuff in the search form. I manage to change the search block, but I can't find a way to do the same with the form I see in site.com/search/node I was 100% sure the hook should be function SearchformMod_search_form_alter(&$form, &$form_state, $form_id) { } But it seems like I'm wrong. If I try to use Theme developer I don't get any .tpl suggestion either. Any Idea ?

The hook you want is hook_form_FORM_ID_alter():

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MYMODULE_form_search_form_alter(&$form, &$form_state, $form_id) {
  // Code here
}

Alternatively you could use hook_form_alter():

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_form') {
    // Code here
  }
}


only selected view modes per node? The view mode per node option in DS Extras is great. But I want to give my editors only the 2 view modes they need, I don't want to burden them with the complete list of some 20 view modes I use all over the site. Is it possible to configure this?

Thanks for any help
Kind greetings
Frank

This functionality appears to already be in the current release of Display Suite.  See here for details: https://www.drupal.org/node/1673626


problem about view module in drupal 7 I have created a view for a content type called "events," and in the view there are 2 contextual filters (by category and years).

what I want to do is to be able to view the result in 3 conditions:

only the year:  http://example.com/events/2010
only the category ID:  http://example.com/events/4
year and category ID together:  http://example.com/events/2010/4

Now the problem is that in the second case, as the argument is considered a year.

How can I set the view to be able to use a URL as in the second case?

As @googletorp commented, the argument in the url have to keep a certain order if not Views won't know which kind it is. The recommended method for this is allowing a "wildcard" by providing an exception, in views you can configure this in the contextual filter options:

Then you simply put all instead of the year when not it's not available:
2- the category id alone : http://mydomain.com/events/all/4


How to highlight new added links on front page with cookies? My front page contains say 3 different views and each view has 10 rows. My requirement is Links which were not published to the frontpage the last time the user loaded it should be highlighted. I am using common template file for field shown on front page. (that is title file with anchor tag having link to some URL) Example in image :

I am having no idea how I can achieve this, I tried searching lot but I have idea that this can be possible with cookies.

Please suggest that will be very helpful !!

Thanks :)

UPDATE :

I have set nid values in cookie with below logic :

function custom_views_pre_render(&$view) {

  //frontpage highlight

  if (current_path() == "frontpage") {
    if (!empty($view->result)) {
      $nids = array();
      foreach ($view->result as $res) {
        $nids[] = $res->nid;
      }
      if(!isset($_COOKIE['FrontPage'])) {
        setcookie("FrontPage[$view->name]", implode(',', $nids), time() + (3600 * 24 * 5), '/');
      }
    }
}

Now I need to compare values of each row nid with in this array.

You could do this in a limited way where you store each item's nid and updated date in a cookie. The cookie would get updated each time the user loads the front page by JavaScript that reads the nid and date from the DOM.

Before the cookie is updated it is used to set a highlight class on any items that aren't set in the cookie.

In order for the cookie to not grow too large the items could be pruned by date if the front page only shows most recent.

For an demo take a look at https://jsfiddle.net/rnc2eLxr/2/

I've included the code below.

JS libraries:

https://code.jquery.com/jquery-2.2.4.min.js
https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js

HTML:

Google

Reddit

Javascript:

// Get cookie value.
var linksString = $.cookie('frontLinks'),
  links = [];
if (linksString != undefined) {
  links = JSON.parse(linksString);
}

// Highlight any links not found in cookie.
$('li a').each(function(i, v) {
  var $link = $(v),
    tuple = {
      "date": $link.data('date'),
      "nid": $link.data('nid'),
    },
    match = findByNid(links, tuple.nid, true);
  if (!match) {
    $link.addClass('highlight');
    links.push(tuple)
  }
});

// Find array object by nid property.
function findByNid(inArr, nid, exists) {
  for (i = 0; i < inArr.length; i++) {
    if (inArr[i].nid == nid) {
      return (exists === true) ? true : inArr[i];
    }
  }
}

// Store links in cookie.
$.cookie('frontLinks', JSON.stringify(links))

CSS:

li a.highlight {
  border: red 1px solid;
}


Can't show custom user field on nodes This is a follow up question to: How do I show user attributes on articles?

I still can't get the "Twitter URL" field to show up on articles, and got tired of reading through the Fields API docs; I figured I couldd ask if anyone can look at my template files, and tell me why the twitter URL is not output, as I know it is being set.

This is the node preprocess function from node.tpl.php:

function blogbuzz_preprocess_node(&$vars, &$variables) {
  if ($vars['view_mode'] != 'full' && $vars['id'] == 1) {
    $vars['classes_array'][] = 'node-first';
  }

  if ($vars['view_mode'] == 'full' && node_is_page($vars['node'])) {
    $vars['classes_array'][] = 'node-full';

  }
  // Even though there's a user object in $variables['user'], we need to
  // load a new copy because the preloaded one doesn't have have field data
  $user = user_load($variables['uid']);

  // Retrieve the data and its value for the Twitter URL field
  // Replace field_twitter_url with the short name of the field
  // found at admin/config/people/accounts/fields
  $items = field_get_items('user', $user, 'field_twitter_url');
  $field = field_view_value('user', $user, 'field_twitter_url', $items[0]);

  // Get the rendered output of the field for use in the submitted line
  $twitter_url = drupal_render($field);

  // If you wanted to get more fields, repeat the last three lines, replacing
  // field_twitter_url with the names of the other fields.
  $variables['twitter_url'] = $twitter_url;
}

And here is  the template.tpl where I use $twitter_url:

<div class="<?php print $classes; ?>">

    <?php print render($title_prefix); ?>
    <?php if (!$page): ?>
      <h2<?php print $title_attributes; ?>><a href="<?php print $node_url; ?>"><?php print $title; ?>

    <?php endif; ?>
    <?php print render($title_suffix); ?>

      <?php if ($display_submitted): ?>
        <?php print t('Published by '); ?><?php print $name.t(' on ').$date; ?>
         <?php print t('Twitter '); ?><?php print $twitter_url; ?>
      <?php endif; ?>

      <?php if (!empty($content['field_tags'])): ?>
        <?php print ' in '.render($content['field_tags']);  ?>
      <?php endif; ?>

    <?php
      hide($content['comments']);
      hide($content['links']);
      hide($content['field_tags']);
      print render($content);
    ?>

    <?php if ($content['links']): ?>

        <?php if (!$page): ?>

<?php print l(t('Read more'), 'node/' . $nid, array('attributes' => array('class' => t('node-readmore-link')))); ?>

        <?php endif; ?>
        <?php print render($content['links']); ?>

    <?php endif; ?>

    <?php print render($content['comments']); ?>

You are trying to render the twitter_url twice. First in then preprocess function and then again in the template.

If that's not the problem, start debugging. Install devel.module if you haven't already and add dpm($variable) statements on the relevant places, e.g. dpm($twitter_url) in the preprocess function.


Associating comments with special pages/module output I have what one could consider an "irregularity" in a Drupal module. I have this unique case (mostly due to vendor inconsistencies and ever-changing requirements) where when a user requests a certain item (in this case, something from an inventory database), a hook_menu() call routes them to a callback that polls the inventory API (a REST service), and we pass that REST data to the user through a theme call in Drupal. Attempts to actually display the data directly to the browser are mostly unsuccessful due to CORS issues, and nobody is answering the phone at the vendor.

I've been informed there are some additional requirements that require our newly minted psuedo-content to host a "Comments" section, which if my knowledge of the CMS is clear, only associates with items the system is storing, e.g Entities and Nodes. Before I ask about a definitive solution, I should ask, if there is any way to convince the CMS otherwise, and track a comments record for this faux-content, or if my only option is to save this data as a node (even if its just a single field), and then 301 Redirect to it once saved. Any thoughts? I know this is a rather abstract question with an equally abstract solution, but time constraints make longer-term solutions unobtainable for now.

Well, I think you pretty much have the answer.

Handling comments without the help of the Node API would probably be a lot of work.

But if you don't need all the extra features the Node layer brings, you can try to apply the same method on an entity. The Reply module takes care of attaching comments to your entity type.

Again, it's more work than simply using a node to store each item comments section. Just use your callback function to load or create a node with a field storing the item ID (if it doesn't exist yet on the database).

You can then use drupal_goto('node/' . $nid, array(), 301) to redirect the user to the comments page.


How to hide Authoring information,Revision information,Publishing options tabs in create/edit node for any content type I am trying to hide Authoring information, Revision information, Publishing options tabs in create/edit node for any content type. I tried different modules with no luck. Please give me suggestions how to achieve this. Thanks a lot

I usually do this with a custom module and drupal's Form API and setting #access = FALSE for form elements I want to hide (and test it with 3rd party modules to assure it doesnt break anything).

Recently, I've been made aware of Override Node Options which does exactly this for Drupal 7/6.