I cant use $account in a block I'm using drupal 6, I wanted to give feed back on a simple quiz (that is answered during user registration - to be a profile field).  I made a template for the profile page:
user-profile.tpl.php

And the code (at the bottom of the page) works fine, but it doesn't work when I try the same code in the template(for the specific block I want):
block-block-10.tpl.php

I added this function to template.php, to (TRY) make $account avaialble to block-10

function blockaccess() {
// access globals
global $account;
global $node;
}

What do I need to change?

the code in block-block-10.tpl.php:

    <?php
    blockaccess();
    dsm($node);
    dsm($block);
    dsm($account);
  $correct_ans = "3) I'm from Spain.";
  $quiz_ans = $account->profile_quizoffer_ans;
  print $quiz_ans;
  print "--------------------------------------------
";
  print '
チラシの裏のクイズ:

Q: Where are you from?	Result
';
  if ($quiz_ans == $correct_ans) {
    print '

';
    print $quiz_ans;
    print '

CORRECT

You passed the quiz!
';

  }
  else {
    print '

';
    print $account->profile_quizoffer_ans;
    print '
INCORRECT

You didn'."'".'t pass the quiz!

The correct answer was:	';
    print $correct_ans;
    print "
"  ;

  };
  print "
"; ?>

Try global $user; rather than global $account;.


Title's will not show translated version (multilingual site) in View list I am working on a multilingual drupal website (webshop with commerce_kickstart-7.x-2.37, drupal 7.43).

My articles are perfectly translated, even the titles. So when I go to the page of the article and change the language it shows the translated content including title.

I then made a new view. With that view i created a page to have all the titles of the articles in a list. The thing is though that those titles will not translate when i change the site language while it does perfectly change on the article itself!

Any help? Is it because I do not have internationalization views? I don't get why it is translating on the article itself but not on the overview page.

I've found it myself.

when using fields, instead of adding content:title as a field, use entity translation:title. This will show the same field as your title but the translated version.


Explicit/Implicit Relationships In this presentation, slide 13 says (emphasis mine):

  The relationships between Entities- the ways entities can interact either
  each other - define our Drupal application

  nodes can have comments
  users create nodes
  taxonomy terms are attached to nodes

  these relationships are implicit - perhaps they should be explicit?

What does the last sentence mean?  In Drupal, what makes entity relationships implicit rather than explicit?

Only the original author knows what he meant by this, as the distinction between implicit and explicit does not have any special technical meaning within the context of Drupal that differs from the normal distinction made in plain English.  Nonetheless, here are my thoughts.

The relationships are implicit because there is nothing in the database to define them and give them meaning.

For example, take nodes and users.  The {node} table has a uid column.  What does this mean?

It is implied in Drupal that this is the author.  But, it could really be anything: author, owner, sponsor, etc.

In some database designs, tables will never have relationships (ie, foreign keys) to other data
tables directly (I forget which normal form this is).

To do this in Drupal, you would alter the {node} and delete the uid column.  Then
make a {node_x_users} table that looked something like

CREATE TABLE  `node_x_users` (
  `xid` int(10) unsigned NOT NULL default '0',
  `nid` int(10) unsigned NOT NULL default '0',
  `uid` int(10) unsigned NOT NULL default '0',
  `rid` int(10) unsigned NOT NULL default '0',
  PRIMARY KEY  (`xid`),
  KEY `nid` (`nid`),
  KEY `uid` (`uid`),
  KEY `rid` (`rid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

The actual relationships, via (foreign keys to other tables) would be stored in this table and not in {node} or {users}.  You would also make a table like

CREATE TABLE  `relationship_labels` (
  `rid` int(10) unsigned NOT NULL default '0' COMMENT,
  `type` varchar(128) NOT NULL default '',
  PRIMARY KEY  (`rid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

This would store a text version of what the relation type is so you could explicitly define them.

So, when you make a node, you insert the node into {node}, get the $nid (which is the PK of the table), then insert the relationship into the cross table, {node_x_users} along with the $uid and the key representing the type of relationship.  When you render a node, you also JOIN on the {relationship_labels} to get the "Authored by", "Edited by", etc text.

In the code you end up with more JOINs (but they are all on simple, indexed types), but you also gain some other advantages, the biggest benefit is a very flexible data model.

Personally, I see this as one of the biggest problems with the current Drupal architecture.

An example of a system that does relationships like this is CollectiveAccess.


Access fields of node content type from event "rules_entity_insert:comment" In Rules 8, I know how to make custom fields of a content type accessible in an event "After updating a content item (rules_entity_update:node)", that is:

Condition: Entity is of bundle
Entity: node
Type: node
Bundle: my_content_type

So that I can use something like {{node.my_custom_field.value}}.

But, when I'm in an event "After saving a new comment (rules_entity_insert:comment)", the above solution does not work. How should I do to access custom fields of the node the comment is attached to?

Couldn't find an answer using Rules, and ended up adding some code:

function my-module_comment_insert(Drupal\Core\Entity\EntityInterface $entity)
{
   // Get NID and load Node
   $nid = $entity->get('entity_id')->target_id;
   $node = \Drupal\node\Entity\Node::load($nid);
}

From there I can use $node->get('field_something'). Of course if it's an entity reference field (as per my case), there's some work to do.


Drush-error when using field-create Trying to make a field with Drush, i get the following error

First, the version

root@homer:/usr/share/nginx/html/8/sites/default# drush version
 Drush Version   :  8.0.1

Try to make a field 'voorvoegsel' (dutch) with field-create in Content-type contact

root@homer:/usr/share/nginx/html/8/sites/default# drush field-create contact voorvoegsel,text
PHP Fatal error:  Call to undefined function field_info_field() in phar:///usr/local/bin/drush/commands/core/field.drush.inc on line 175
Drush command terminated abnormally due to an unrecoverable error.                                                                                [error]
Error: Call to undefined function field_info_field() in phar:///usr/local/bin/drush/commands/core/field.drush.inc, line 175

Googling gives me no clue, so i post this here. Can't find a (good) solution.

Drush doesn't support field commands for Drupal 8 yet. The error message is caused by the fact that Drupal 8 no longer has a function field_info_field() - see Drupal change record at https://www.drupal.org/node/2260037

Drush issue at https://github.com/drush-ops/drush/issues/230


JQuery Accordion closes unintended when ajax-link from inside gets response I'm working on a page where a user can click on ajaxified links inside a JQuery-Accordion-Widget.

Currently every time a link is clicked and the response is loaded, the accordion gets closed and it is not possible to click it anymore - but no JS-error is raised.

Did i miss something i have to call i.e. to change the focus ?

Thanks for your help,
piezo.

You can probably use one of the jQuery Accordion API functions to manually control the state of the accordion

e.g:

// getter
var active = $( ".selector" ).accordion( "option", "active" );
// setter
$( ".selector" ).accordion( "option", "active", 2 );

more info here


Problem with SSL certificate I just enable SSL certificate for my domain.
I added that in my .htaccess file:

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^domainname\.com*
RewriteRule ^(.*)$ https://www.domainname.com/$1 [L,R=301]

And:

# HSTS.
<IfModule mod_headers.c>
  Header always set Strict-Transport-Security "max-age=15768000; includeSubDomains; preload"
</IfModule>

# Cookie secure.
<IfModule mod_headers.c>
  Header set Set-Cookie HttpOnly;Secure
</IfModule>

And I changed the line in my settings.php file:

$base_url = 'https://www.domainename.com';

And :

$conf['https'] = FALSE;

All my https site displays well with the little green padlock, but the following errors appear in the dashboard drupal :

The Piwik module displays the following error:

  Message d'erreur The validation of
  "https://analytics.s1biose.com/piwik.php" failed with error "Error opening socket ssl://analytics.s1biose.com:443"
  (HTTP code 0).

There are some known issues with Drupal 7.x in some server configurations particularly around PHP 5.6 and OpenSSL 0.9x due to changes in how PHP verifies SSL certificates. Acquia has some notes about the cause and options (including a core patch to try to address some instances of the problem but read the whole article before considering that option).

On shared hosting you'll likely want to try the Alternative HTTP Client module to see if it resolves the notice.


How do I put a logo into a block? I have tried to put this code in custom block with input formated to PHP code:

$settings = theme_get_settings('my theme');
if (!$settings[toogle_logo] = 0) {
  print '<img src="' . base_path() . $settings['logo_path'] . '" alt="my logo" />';
}

It doesn't work in Drupal 7.

theme_get_settings() was removed in Drupal 7. Instead, use theme_get_setting(). This works:

<?php

if (theme_get_setting('toggle_logo')) {
  $image = array(
    'path' => theme_get_setting('logo'),
    'alt' => 'my logo',
  );
  print theme('image', $image);
}

?>

theme_get_setting() will get the current theme's setting, but if you want an arbitrary theme's setting, you can use the optional second parameter as described in the API docs. I used theme_image() to make it less fragile.

But if you can avoid the use of the PHP filter, you really should: consider creating a small custom module that creates a block with the code instead.


Taxonomy term: "The requested page "xx" could not be found." In a taxonomy vocabulary, I have terms such as: groups/arts (parent level.)

The URL alias of the term is set as groups/arts (Organic Groups.)

But when I want to access the page www.example.com/groups/arts, I get a "The requested page "/groups/arts" could not be found" error message. This is true regardless of pathauto being enabled or not.

If instead of writing the url I click on the view tab of the taxonomy term edit page (which should bring me to the page) I am sent instead to the root directory (www.example.com)

This issue started after I began using the default view provided for taxonomy. I used the view for for a different vocabulary that works well (the terms have their own pages that show.) However, if I disable the view then I get the same no page found result.

Is it possible that the taxonomy view messed up? Or can one not use it twice on the same site for different vocabularies?

Any pointer on those issues greatly appreciated. Thanks. :)

Any idea on how to fix this? Is it a .htaccess file issue? If I knew where to start looking that would already be a big help. Thank you. :)

I will answer my own question on this one:

On a site that has several vocabularies, enabling the selection of one of those vocabularies in the contextual filer of the default taxonomy view, removes the paths assigned to the terms of other vocabularies (those that have nothing to do with the view.) Those paths then default to the root directory and the term pages can no longer be found (or used in another view, etc.)

Un-selecting the vocabulary returns functionality to the term paths of other vocabularies but also allows the existing view to be displayed on all vocabulary term pages (this appears to be functioning as designed however.)

It appears to be a bug in the taxonomy module for which there is no fix. :(


How to perform a page redirect after submitting node with conditions? I have a select list which contains A and B. If users choose A, then (after submitting the node) the users are redirect to URL A; if users select, they are redirected to URL B. I'm using Rules and adding conditions to try this but no avail.

Maybe I'm wrong in choosing the conditions because I'm so confused right now and there's no documentation for this.

I've considered to use the Conditional Rules module, but since this project not covered by Drupal, I'm hesitating to use it.

Solution for option A:

Below is a sample of a rule (in Rules export format) that should allow you to specify a Rules Condition related to a specific value selected via a selection list (and when a new node is created):

{ "rules_new_node_with_special_optionlist_value_a" : {
    "LABEL" : "New node with special optionlist value A",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "data_is" : { "data" : [ "node:field-optionlist" ], "value" : "A" } }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "A new node got created with option list value = Advanced" } }
    ]
  }
}

Some more details to further explain the above above sample:

The Rules event I'm using is "After saving new content" (replace this event by whatever fits your case).
In my case I have a selection list field with machine name field_optionlist.
This field actually has 2 possible values, like so:

A (=Advanced).
B (=Basic).

As a sample, I decided to use as condition "The selected value must be Advanced".
If that value is selected, then (as Rules Action), a message is shown like A new node got created with option list value = Advanced. Feel free to change that to whatever Rules action, this is how I often "unit test" new rules I write. In your case you want to make it a redirect to your URL A.

The "clue" to make this rule work is the condition Entity has field. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')".

Note that I've not added a Rules Condition here about selected content types, that's probably an extra condition you might want to add also. But if the selection list field is only used for the content types you're interested in, then the Entity has field condition should be sufficient already.

Solution for option B:

Clone the rule you created for option A into a similar rule, this time to check for the value of "B", and to perform a Rules Action to redirect to your URL B.

With those 2 rules in place, your disered logic is implemented, and you don't need the "Conditional Rules" module either.


Is there a git repository for Drupal releases only? Having cloned drupal from the git repository using

git clone --branch 7.x http://git.drupal.org/project/drupal.git

I noticed that I'm actually running 7.9-dev when what I want to be running is the most recent stable. Is there a git repository or branch that I can pull from to run the most recent stable release? I've seen references to git.drupal.org/project-stable/drupal.git around the net, but that doesn't seem to be a valid repository anymore.

Drupal releases are marked with a corresponding "tag" within the repository. When you clone a git repository, you get all the tags and branches along with it. Running the following command from within the repository will checkout the version 7.8 tag:

git checkout 7.8

To list the available tags, type git tag. To list all available branches, type git branch -a.


Issues with Zen subtheme I am running a Zen subtheme for another drupal instance and it all worked fine. However, when I copied the folders across to my new Drupal instance, all I see is

The name of the site and

User menu :

My account
Log out

There is no Add content link... or the administration menu along the top... also no styles are applied... I am pretty sure I changed all the site specific instances in the code (.info file etc)... What am I doing wrong?

Ok, so I can navigate through the admin menu by changing the url path... admin/appearance

I have cleared the cache, but the styles for the zen sub theme are still not being picked up and I cannot see the Add Content link on the front page.

I've tried changing the theme to Bartik, and it looks fine. The styles are being picked up and everything.

So why is it not working for the Zen subtheme?

In the logs, I am seeing this message:

  Notice: Undefined property: stdClass::$prefix in system_theme_settings() (line 547 of /home/mysite/public_html/modules/system/system.admin.inc).

Does this explain the wsod problem?

You need to copy over The Zen theme as well, A sub-theme requires both the sub theme and its parent theme in order for it to work


How to get the URL of an entity being created at hook_entity_insert() stage? I'm trying to send an email "someone added content" with the URL to the entity as the message body.

function MYMODULE_entity_insert(EntityInterface $entity) {
  if ($entity->getEntityTypeId() === 'node') {
    switch ($entity->bundle()) {
      case 'contact':
        MYMODULE_mail_notify_admin($entity);
    }
  }
}

function MYMODULE_mail_notify_admin($entity) {
  $mailManager = \Drupal::service('plugin.manager.mail');
  $module = 'MYMODULE';
  $key = 'contact';
  $to = 'secret@secret.com';
  # $to = \Drupal::currentUser()->getEmail();
  $params['message'] = $entity->toUrl()->getUri();
  $params['title'] = $entity->label;
  $langcode = \Drupal::currentUser()->getPreferredLangcode();
  $send = true;

The problem is that $entity->toUrl()->getUri() gives an error, "This URL has a Drupal route, so the canonical form is not a URI".

How do I get the URL from a URL object?  Is this a problem because the entity hasn't been created yet, and the route hasn't been assigned?

The URL object is there, you're just calling it wrong.

The code for this is a little complicated:

  $path = $entity->toUrl('canonical', ['absolute' => TRUE])->toString();
  $params['message'] = $path;

For more info, see this issue.


How can I programatically change the content of a block and keep Full HTML formatting I need to programmatically change the content of a ui configured block. I've partially figured out how to do this, ie:

$ids = \Drupal::entityQuery('block_content')
  ->condition('type', 'custom_block_type')
  ->condition('info', 'Specific block title')
  ->execute();

$my_block = BlockContent::load(array_values($ids)[0]);
$my_block->set('body','
'.$my_processed_string.'
');
$my_block->save();

This does change the content, but when I do this the block loses the Full HTML block format, and the new content in printed out verbatim as html encoded content (ie, the user literally sees '
My altered value
' on the screen). If I go through the ui and change the Text Format field manually to Full HTML, it renders correctly, but that doesn't really accomplish what I need to do.

How can I change the content programatically, without losing the html formatting?

The body field has at least two properties, value and format. To replace the complete field content, you have to use an array:

$my_block->set('body', [[
  'value' => '
' . $my_processed_string . '
',
  'format' => 'full_html',
]]);

Normally you don't need to do this. Set only the value property:

$my_block->body->value = '
' . $my_processed_string . '
';

So that you don't overwrite properties you don't want to change.


My drupal 7 messed up after installing a module and I just get an error, how do I debug it and trace the source of that error? If I have a module that I installed and its causing a conflict with another module, how do I trace it down to see which is causing the conflict? Let's say the error message doesnt' give any useful information in finding the culprit module. How would one go about find the module causing the issue?

You can use the debugging methods mentioned in the comments, especially ddebug_backtrace.

Another, more manual option, is, to disable other enabled modules one by one, until the error goes away. Once you know the culprit, search the issue queue of that module (and the new module) and/or use the debug statement (or drupal_debug from the devel module) to narrow down the problem.

Some pointers on how to debug:
https://drupal.stackexchange.com/questions/545/how-do-i-debug-drupal
How do I debug my Feeds import not importing a field

And then of course, you should look at the web-server logs (apache, etc).
Another way to debug issues like that, when you get the white screen of death, is, to execute a drush command on the command line - like cc or something like that. Often, the error message gets printed to STDOUT.


Migrate: Duplicate entries in url_alias after update migrations I have term and node migrations from wprdpress to drupal 8 (with pathauto module enabled). I set the url alias in the migration templates like:

process:
  path/alias: source_path
  path/pathauto:
    plugin: default_value
    default_value: 0

Setting the path that way works fine on importing content with drush mi term. But when I update the terms with drush mi term --update a new (the same) path gets inserted into the url_alias table. For example the term with tid 1 gets imported once and updated 2 times there will be the following aliases in url_alias table:

select * from url_alias where source = '/taxonomy/term/1';
+------+------------------+---------------+----------+
| pid  | source           | alias         | langcode |
+------+------------------+---------------+----------+
| 1514 | /taxonomy/term/1 | /term-1-alias | de       |
| 2731 | /taxonomy/term/1 | /term-1-alias | de       |
| 3632 | /taxonomy/term/1 | /term-1-alias | de       |
+------+------------------+---------------+----------+

BTW: I have pathauto module enabled, but uninstalling it results in the same behavior.

Looks like a bug in the core path module: https://www.drupal.org/node/2350135


How allow moderators to give a rebuke to user I'd like to allow moderators to give a rebuke for users. If user has e.g. 3 rebukes, the account of user should be removed or blocked - automatically or moderator should be inform about it.

You can use Flag module for that. You can set flag for users or posts created by users or something else as per your requirement.

Use rules to set rule on flagging & their counter value. There is very nice tutorial series on flag here by Johan Falk. You can see his rules tutorials to have better understanding about setting rules based on flagging.


View of users with the same 'entity reference' field vale I'm running a D7 site where every user profile has a 'entity reference' field referencing to their manager.

All I want to do is to create a list of the users sharing the same manager in context to logged-in user.

Can anyone please help

You need two entity references and a contextual filter to accomplish this.

The contextual filter does not use either of the relationships. Just select provide default value, User ID from logged in user.

The first relationship will get you the manager of the currently logged in user: User entity referenced from field_manager

The second relationship will get you the users that have that manager reference: User referencing User from field_manager. Set this relationship to use the other relationship. That's the first dropdown after you create the relationship.

Then you can simply add the User name field to your view and set it to use the second relationship (User referencing User from field_manager).

Any questions let me know. I have this running on a stripped down local install of Drupal 7.


Drupal.behaviors Once() won't execute I have created a custom block that shows some parking information for the user (using json) and this worked fine for most pages, but when I visit any created nodes (pages like /node/1,/node/2) the jquery get executed twice (so the information is added twice to the parkings-div in the block). After some searching, I thought using "once" would solve my problem but after adding this it doesn't execute at all.

(function ($) {
    "use strict";

Drupal.behaviors.Parkings = {
    attach: function (context, settings) {
        $('#parkings',context).once('parkingsbehavior', function () {
            getAndShowResults();
        });

        function getAndShowResults() {
            var root_url = getRootUrl();
            $.get(root_url + "parkings", {})
                    .done(function (data) {
                        var i;
                        for (i = 0; i < data.length; i++) {
                            var p = $(document.createElement("p"));
                            var p_text = data[i].description + ', free: ' + data[i].parkingStatus.availableCapacity;
                            p.append(p_text);
                            p.appendTo("#parkings");
                        }
                    });
        }

        function getRootUrl() {
            return window.location.origin ? window.location.origin + '/' : window.location.protocol + '/' + window.location.host + '/';
        }
}};

}(jQuery));

This is my routing file:

parkings.content:
      path: '/parkings'
      defaults:
        _controller: '\Drupal\parkings\Controller\ParkingsController::content'
        _title: 'Parkings Gent'
      requirements:
       _permission: 'access content'

and I've added these dependencies:

    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

Am I misunderstanding how once() works or am I just using it wrong?

(I'm using Drupal 8 v1.8)

jQuery Once has changed with jQuery 2.x, see the Drupal changelog for info.

I ran into the same issue and that fixed it for me:

Essentially now you are going to want to do:

...once('mybehavior').each(function()...


How can I block an abusive person who endlessly tries to register more accounts? I have a free site with open registration; anyone can register and I am not able to change that.  However, accounts must be approved by an administrator after completing a profile, so I have access to a variety of info to identify duplicate users (date of birth, "self introduction" comment, email address, photos, reported location in profile, geolocated IP, IP address, etc.)

Recently the site has become subject to the attacks of a single user who is extremely abusive and seems to have unlimited time to register multiple accounts.  These accounts can be blocked relatively easily, but it's a lot of work for the administrator (me) and I'm afraid I will miss one among the legitimate accounts (this user registers about 6 accounts per day).

I have already:

banned the user's known IP addresses
blocked registration from known domains that are used for "disposable" email addresses
added a special view to help me identify accounts based on known patterns of access from the user

Is there anything I can do with cookies, etc. to make it even more difficult for this user to register?

This is a Drupal 7 site.

EDIT: In my case, this is a human user, not a bot.  But the bot answers are useful for those who are being specifically targeted by spammers.

Instead of trying to prevent the user from registering, which is a game for trolls and hackers alike, make the site annoying for him. Make him want to leave, as opposed to making him want to win the trolling game.

What I've done in the past, not specific to Drupal, is to let the user register. I then sabotaged his specific account:

I sprinkled if ($someuser) { sleep(rand($base, $base*2)) } in the code, where $base would increase daily. I made sure that he had lots of timeouts.
I would drop N% of his posts, where N started above 50% and only increased from there. If the post had certain keywords, it would be dropped immediately.
I would randomly drop CSS rules so the page would display poorly. Again, the severity would increase in time.

This required more effort on my part, but as per Sun Tzu's advice I was conditioning the user to hate my site. I wanted him to feel not that he was annoying us, but rather that he should be annoyed by the delays and apparent bugs. It took less than a week for him to give up on us.

EDIT: In the comments, user rooby mentions the Misery module which is based on the same concept:

Delay: Create a random-length delay, giving the appearance of a slow connection. (by default this happens 40% of the time)
White screen: Present the user with a white-screen. (by default this happens 10% of the time)
Wrong page: Redirect to a random URL in a predefined list. (by default this happens 0% of the time)
Random node: Redirect to a random node accessible by the user. (by default this happens 10% of the time)
403 Access Denied: Present the user with an "Access Denied" error. (by default this happens 10% of the time)
404 Not Found: Present the user with a "Not Found" error. (by default this happens 10% of the time)
Forms don't submit: Redirect back to the form during validation to prevent submission. (by default this happens 60% of the time) Note: Occasionally certain forms validate based on which button was pressed, this won't work in those cases.
Crash IE6: If the user is using Internet Explorer 6, this will crash their browser. (by default this happens 0% of the time)
Spam: Replace node content with a set word. (by default this happens 10% of the time)
Logout: Log the user out. (by default this happens 10% of the time)


How to disable user and e-mail input auto-fill? I'm trying figure out, how I can disable auto-fill or change markup of 'user' and 'e-mail' input forms, when a user is logged in.

This auto-fill feature is breaking my design, because the 'user' and 'e-mail' markup are just a text inside a div and I can't apply a correct style on it.

Something in the core stores user login and drupal use this information in every form submit, in other lines, I can't let user change 'user' and 'e-mail' inputs. BUT, I found how to change markup and correct my design. Follow...

In 'mytemplate'\templates\form\form-element.html.twig I changed:

...[omitted]...

78.   {{children}}

...[omitted]...

for:

{% if logged_in and element['#type'] == 'item' %}
  <input type="text" name="{{name}}" value="{{element['#value']}}" disabled>
{% else %}
  {{ children }}
{% endif %}

And my form now looks like this:


How do I attach a file to a file field when saving (update/insert) a node? After creating programmatically a PDF file with TCPDF, I am trying to attach it to my field "file_fichier", here is what my code looks like

/**
 * Implements hook_node_presave().
 */
function hook_node_presave($node) {

  if($node->type=='profil'){

    $uri = 'public://profiles/fichier';
    $filename = $node->title.' - PDF - '.$node->language.'.pdf';
    $file_path = $uri . '/' . $filename;

    // Output PDF with TCPDF
    $pdf->Output($file_path, 'F');

    $file = new stdClass;
    $file->uid = $node->uid;
    $file->filename = pathinfo($file_path, PATHINFO_BASENAME);
    $file->uri = $file_path;
    $file->filemime = file_get_mimetype($file_path);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);

    dpm($file);

    // Now attach file to the file field.
    $node->field_fichier[$node->language][] = (array) $file;

  }

}

The PDF file is well saved to public://profiles/fichier/file_name.pdf as expected, and it's also recorded to the 'file_managed' table.

But the problem is that it's not attached to the field field_fichier, and nothing seems to happen to the field_data_field_fichier table

I think that you don't have the fid.

/**
 * Implements hook_node_presave().
 */
function hook_node_presave($node) {

  if($node->type=='profil'){

    $uri = 'public://profiles/fichier';
    $filename = $node->title.' - PDF - '.$node->language.'.pdf';
    $file_path = $uri . '/' . $filename;

    // Output PDF with TCPDF
    $pdf->Output($file_path, 'F');

    $file_temp = file_get_contents($file_path);

    // Saves a file to the specified destination and creates a database entry.
    $file_temp = file_save_data($file_temp, $file_path, FILE_EXISTS_RENAME);

   $node->field_fichier = array(
     'und' => array(
       0 => array(
        'fid' => $file_temp->fid,
        'filename' => $file_temp->filename,
        'filemime' => $file_temp->filemime,
        'uid' => $node->uid;,
        'uri' => $file_temp->uri,
        'status' => 1,
        'display' => 1
    )
  )
);


What does "Argument #1 is not an array in _form_set_class()" mean? In Drupal 7, I'm getting this error and want to fix it:

  Warning: array_merge() [function.array-merge]: Argument #1 is not an array in _form_set_class() (line 4021 of {my site}/includes/form.inc).
  Warning: array_merge() [function.array-merge]: Argument #1 is not an array in _form_set_class() (line 4021 of {my site}/includes/form.inc).
  Warning: implode() [function.implode]: Invalid arguments passed in theme_radios() (line 2746 of {my site}/includes/form.inc).

What does this mean, and what should I do about it?

For me it happened; when I used

$form['field']['#attributes'] = array('class' => 'myclass');

While it should be

$form['field']['#attributes'] = array('class' => array('myclass'));


The Solr server could not be reached. Further data is therefore unavailable I have installed a solr 5.2.1 in my windows 7 and I have created a solr core through SOLR Admin UI. It works fine. When, I trying to connect to solr by help of search_api_solr module in drupal 7.38 on my local host, The following error is coming.

"The Solr server could not be reached. Further data is therefore unavailable". What I have missed out, Anyone can Please help. Refer the below images.

Maybe your path for solr is wrong. If you setup solr by drupal instructions then your solr path must be:
/solr/drupal


How to edit the People (users admin view) to include filter by user name? I want my admins to be able to search through the admin users view by the user name. I have a site with a lot of users and periodically the admins want to be able to check on various user fields. Is there a way to do this?

You can take a look at the Administration Views Module:

  Replaces administrative overview/listing pages with actual views for
  superior usability.

  Features

  Filter all administrative views via AJAX.
  Perform any kind of bulk/mass operations on items in administrative views.
  Filter content by title, node type, author, published status, and/or vocabulary.
  Filter comments by title, author, node title, or published status.
  Filter users by name, ban/blocked status, or user roles.

  *Note: If you are upgrading from an older version of Administration views and the default views have been overridden (saved in the
  database) you could encounter issues or not see any new changes unless
  you revert these views, so the default in-code views are used. This
  can be done in the views UI listing or using drush (drush cter
  views_view --module=admin_views)

By default it has a specific users view, but since it is a view, you can modify it.


Develop a module that adds a new content type with custom fields How do I start to develop a Drupal 7 module that adds a new content type with some custom fields, so it generates all the output I want?

Although its possible to do programatically, your easiest bet would be to use features.

This is how you would do it:

Manually create your content type
Manually add fields
Create a new feature and export the content type (and its fields)
Done!

Now if you install this feature is a fresh Drupal installation that content type and fields will be automatically added.


How to redirect user page to front page for specific roles I want to redirect every users page to front page? like if user page url is /user/97 then it redirect to front page if user is not administrator. I want user page inaccessible to other users but only administrators.

How can I achieve this?

I tried doing like this:

<?php

namespace Drupal\myisu_ubit\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
// use Drupal\user\Entity\User;

 /**
   * Listens to the dynamic route events.
   */
 class RouteSubscriber extends RouteSubscriberBase {

 /**
  * {@inheritdoc}
  */
 protected function alterRoutes(RouteCollection $collection) {
   // Change the route associated with the user profile page (/user, /user/{uid}).
   if ($route = $collection->get('user.page')) {
      $route->setPath('/');
   }
 }

}

module.services.yml:

services:
  user_profile.route_subscriber:
     class: Drupal\module\Routing\RouteSubscriber
     tags:
        - { name: event_subscriber }

What am I doing wrong here?

Solved using EventSubscriber like this:

services:
  my_module.event_subscriber:
    class: Drupal\my_module\EventSubscriber\MyModuleSubscriber
    tags:
       - {name: event_subscriber}

And MyModuleSubscriber:

namespace Drupal\my_module\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\views\Views;
use Drupal\views\ViewExecutable;
use Drupal\user\Entity\User;
use Drupal\Core\Url;

class MyModuleSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public function checkForRedirection(GetResponseEvent $event) {
    $request = \Drupal::request();
    $requestUrl = $request->server->get('REQUEST_URI', NULL);
    $userID = \Drupal::currentUser()->id();
    $user = User::load($userID);
    $uid = $user->get('uid')->value;
    $roles = $user->getRoles();
    $userPage = "/user/" . $userID;
    if (
      $userID !== '1' &&
      !in_array('administrator', $roles) &&
      $requestUrl == $userPage
    ) {
        $path =  \Drupal::service('path.alias_manager')->getAliasByPath('/');
      $event->setResponse(new RedirectResponse($path, 301));
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkForRedirection');
    return $events;
  }

}

I don't know if it is the correct way to do this but it solves my problem.


Compromised D7 Sites due to SQL Injection Security Bug "Drupal Core - Highly Critical - Public Service announcement - PSA-2014-003" I have few websites running Drupal 7 and i upgraded them all on 16th October 2014.

Since 3 days we are monitoring the websites and we haven't seen any problem or evidence of our system being compromised.

I am wondering if there is anyway to identify if a Drupal 7 sites has been compromised?

It will be really helpful if we all post our views, any evidence of system being compromised and any action that could be helpful to make sure we are secure.

Someone recently came out with a module that should help in this, assuming you have installed drush.  It is called Drupalgeddon

Here is an example of its use:

$ drush -y @sites drupalgeddon-test
You are about to execute 'drupalgeddon-test' non-interactively (--yes forced) on all of the following targets:
sites.abcd-d6.example.org       >> Site is not Drupal 7.                     [ok]
sites.abcde.example.org         >> Site did not test positive. Good luck!    [ok]
sites.abcdef.example.org        >> Site did not test positive. Good luck!    [ok]
sites.abcdefg.example.org       >> Site did not test positive. Good luck!    [ok]

Also note:

Drupalgeddon cannot guarantee a website has not been compromised.


Looking for exposed filter for private file name We have a view for a type of node that includes a Private File.

We cannot see a way to add an exposed filter, such as "Contains any word", and have it filter based on the file's name.

Are we missing something obvious?

Here's how to set that up:

Make sure you are not displaying teaser/full nodes. This works only for fields.
Under Relationships add your file field. You should select Content: [field name] (field_field_name:fid).
Create new Filter Criteria and choose File: Name.
Choose appropriate operator and optionally expose it to the visitors.

Hope this helps.


How can I dynamically add URL or taxonomy to body class Am creating my own theme and have successfully added the URL into the node class in node.html.twig with {% set classes = [ 'url' ~ url|clean_class, ] %} but I need to be able to style each page individually as a whole, not just at the node level - how do I add the URL or the taxonomy of the node to the page or body classes?

The answer provided by mradcliffe was what I needed. One improvement that will yield a css-friendly class name is to use the Twig |clean_class filter. Here is the code:

In MY_THEME.theme

<?php
function MY_THEME_preprocess_html(&$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $variables['current_path'] = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
}
?>

In html.html.twig:

{%
  set body_classes = [
    logged_in ? 'user-logged-in',
    not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
    node_type ? 'page-node-type-' ~ node_type|clean_class,
    db_offline ? 'db-offline',
    current_path ? 'context' ~ current_path|clean_class,
  ]
%}
<body{{ attributes.addClass(body_classes) }}>

Don't forget to clear your cache!


multiple views on same page Say I am writing a page template to show the daily special menu of a restaurant. Each menu item is a content and has a field to store which day of a week it goes on special. The page will have 7 tabs(Mon, Tue, Wed etc) to display the query of that day.

I wonder how to achieve this in drupal 8?

A simply solution is to use 7 regions for each day and put a view block in each of them.

More flexible is a solution in page preprocess putting the view block in variables:

foreach ( $days as $day ) {
  $variables['view_block_' . $day] = views_embed_view('menu_view', 'block_' . $day);
}

And use the variables in a similar twig loop.

Think about holidays or other special cases, in code you can realize all these things. If it gets more complicated, use contextual filters and arguments as third parameter of views_embed_view().


Add an attribute to $variables from a Controller I need to add an attribute to the body tag from a controller. Adding a body tag with hook_preprocess_HOOK() is not a problem.

/**
 * Implements hook_preprocess_HOOK().
 */
function MY_MODULE_preprocess_html(&$variables) {
  if (\Drupal::routeMatch()->getRouteName() == 'my.route') {
    $variables['attributes']['class'][] = 'my-class';
  }
}

However, I only want to add the attribute when the node object, which is already in the controller, meets a second condition which is:

if ((\Drupal::routeMatch()->getRouteName() == 'my.route') && ($this->moderationInformation->hasPendingRevision($node))) {}

I don't have $variables in the controller so how can this be done?

Rendered output from a controller or other page elements like blocks or menus don't have direct access to the variables of a page/html preprocess hook. You can however attach metadata to the render array which then bubbles up to the page level when rendered, for example html_head or css libraries. In your case one possible way would be to attach a placeholder to the render array of the controller, which then replaces a placeholder class in the body tag. But I still would prefer to get the node via the route parameter, see the linked topic in the first comment.

A code example how to replace a body tag class from a controller. First add a placeholder class in the preprocess hook:

/**
 * Implements hook_preprocess_HOOK() for html.html.twig.
 */
function mymodule_preprocess_html(&$variables) {
  $variables['attributes']['class'][] = 'body-placeholder-class';
}

And then attach a placeholder to the build array to replace this class from the controller:

$build['#attached'] = [
  'placeholders' => [
    'body-placeholder-class' => [
      '#markup' => 'class-replaced-by-controller',
    ],
  ],
];
return $build;


What parts go under source code version control? I am wondering what the best practices are for putting Drupal code under version control. I'll be mostly using core and standard Drupal modules. I'll be developing a custom theme, and one or two custom modules.

As far as I see it, I have 3 options:

Put the entire Drupal folder under version control. Developers can directly check out the folder in the Apache htdocs folder and go from there.
Check in only my custom code (modules + themes). Developers checkout the code in the appropriate folders.
Set up something like Docker.

There are different ways to approach this, depending on what you need. The easiest approach is the one you described in #1 (Put the entire Drupal folder under version control).

That allows you to easily checkout the full working copy of the codebase with just Git. The downside is that you are storing a lot of code in your Git repo which already exists in other Git repos (ie: Drupal core, contrib modules, etc).

With Drupal 8, the community is generally moving towards using Composer for managing dependencies and building the Drupal codebase. Then, you only need a composer.json file (which points to specific versions of Drupal core and contrib projects), and your custom code in the Git repository. More information: https://www.drupal.org/docs/develop/using-composer/using-composer-with-drupal

Another option is to create an installation profile, and use Drush Make. This method is deprecated in favor of Composer in Drupal 8, but still works nicely for Drupal 7 projects. This is better suited to common code/configuration that you might use to set up lots of similar sites, rather than one highly-customized and specific site.

Regarding Docker - that's sort of a separate decision. You'll still need to choose one of the above options, and then build the codebase accordingly inside the Docker container (or mount it in a volume).


Unable to override ctools selection plugin class from my module I am trying to add a custom ctools selection plugin for entity reference field as explained Here but it is never bing called but it is calling the parent class (EntityReference_SelectionHandler_Generic). Following is my code.

1) Implements hook_ctools_plugin_directory

function mymodule_ctools_plugin_directory($module, $plugin) {

   if ($module == 'entityreference') {
    dsm($plugin);
    return 'plugins/' . $plugin;
  }
 }

Than I created "plugins/selection" folder in my module directory following is the code I have in this file respectively-

1) Base.inc

$plugin = array(
'title' => t('Simple (with optional filter by bundle)'),
'class' => 'myClass',
'weight' => -100,
);

2) myClass.class.php

class myClass extends EntityReference_SelectionHandler_Generic{
public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
watchdog('getInstance', "print something for test ");
return new ExampleSelectionHandler($field, $instance, $entity_type,  $entity);

}
public function buildEntityFieldQuery($match = NULL, $match_operator =CONTAINS'){
}
}

But Myclass is never getting called instate it is calling the
 parent class(I have added a watchdog in that class).

same problem, two days wasted according to http://lookalive.co.uk/blog/drupal-entity-reference-how-make-custom-entity-reference-selection-handler and all it's copies.

entityreference_get_selection_handler() code dpm() showed that "*.inc" should be named 'base.inc' as in your case.

After renaming in my case *class.php started to execute.

So all i can advice to you - check if module has higher weight than 'entityreference' module, see here https://www.drupal.org/node/110238

And add the first line to '*class.php' (for inheritance)

require_once drupal_get_path('module', 'entityreference') . '/plugins/selection/EntityReference_SelectionHandler_Generic.class.php';

If this helped to you - pleace vote [+] this answer (i need more scores, tks)


List of replacement tokens? Where can I find a list of the available tokens, so I can write things like {{ node.title }} in my templates?

The documentation says the best way to find a list of them is to use this: https://www.drupal.org/docs/8/modules/d8-rules-essentials/data-selection

Can anyone provide something more useful?

Those are variables, not tokens. They're arbitrary, and can/will change depending on what template you're in, what modules/themes you have installed, and how you have them configured.

The easiest way to see what variables you have available in context is to use the dump() method:

{{ dump() }}

See Discovering and Inspecting Variables in Twig Templates for full details.


Solr Search - Adding taxonomy to Search results I'm using the 'Solr Search' module ( not Apache solr search ) .

What I need to do is return results that have a taxonomy term relationship.

In my search indexes 'fields'  I have the taxonomy I want 'Keywords'  selected. The type for this is 'Taxonomy term'  .  I have also added 'Keywords » Name' through 'Add Related Fields'  .  This is type 'Fulltext'  and after reindexing and saving this field appears in views/search/page / search ‘full text’ / Searched fields.

However when I search for a keyword through the exposed filter the results are not being returned. They can however been seen in Facets.

Any idea what I might be missing.

I rebuilt the view and this time it worked fine.


RESTws POST List (text) field type Error I'm using RESTws and POSTing a JSON object to "/node". Everything works fine until I include a List text field (checkbox type). The field in question is:

...
"field_days_closed_v": ["Monday", "Tuesday"],
...

When I post I get this error:

  Recoverable fatal error: Argument 2 passed to RestWSBaseFormat::getResourceReferenceValue()
      must be of the type array, string given, called in .../restws/restws.formats.inc on line 278 and defined in RestWSBaseFormat->getResourceReferenceValue() line 311

My JSON is:

{
  "body": {
    "format": "filtered_html",
    "summary": "",
    "value": "test"
  },
  "field_opening_times_t": {
    "format": "filtered_html",
    "value": "Daily"
  },
  "field_price_category": "",
  "field_price_text_t": {
    "format": "filtered_html",
    "value": "
Free entry
"
  },
  "title": "Mark test test test",
  "type": "primary_article"
}

The field is a List(text) and the widget type is Check boxes/radio buttons. Values are:

Monday|Monday
Tuesday|Tuesday
Wednesday|Wednesday
Thursday|Thursday
Friday|Friday
Saturday|Saturday
Sunday|Sunday

Am I right in thinking it is just an array that should be POSTed?

Any ideas?

The JSON format for list (text) for checkbox type would looks like follows

{"title":"My Day","type":"page","field_days_closed_v":{"und":["sunday", "monday"]}}

I've tested this, and working fine.

Here field_days_closed_v is the machine name of the  List text field (checkbox type). similarly sunday, monday are the values of checkbox type so change them accordingly.

Hope this helps. :)


Multiple image field in block form I wanna add in a block configuration form an image field that can take several images, just like in a node form, with all the drag'n drop stuff, etc.
Any advices or solutions?

The solution is an image field configured in a custom block type.

Block forms are configuration and don't support image fields. Custom block types are content and they support the same field types as nodes.

If you can't do what you want with a custom block type, you can create your own block plugin which uses a block content entity.

For background information see these questions Adding custom block problems and  Blocks: Old vs. "Custom" and Config vs. Fields.


how to setup rule events for before/after video is played? How can I set up a rule events for actions to occur before and after videos are played in a node?

Thank you for any tips/ help you can give!

When video start/end it should call js function which trigger ajax call for path you create on drupal (using hook_menu) the callback of that menu item should call the rule you want using rules invoke function
    rules_invoke_component('rule_name', $arg);

So the case is how to trigger the ajax call on start/end

if you are using youtube, check this page, you can trigger js function to start the ajax

https://developers.google.com/youtube/iframe_api_reference

if you have another player you should look to the api


The content access permissions need to be rebuilt. Rebuild permissions? My Drpal website asks

"The content access permissions need to be rebuilt. Rebuild permissions"

what is this means?

Can I go for Reubuild Permission?

Will it cause any problem for current modules?

I cannot give you a full answer. Your answer is specific to your website.

  "The content access permissions need to be rebuilt. Rebuild permissions"
  what is this means?

From some Drupal 6 documentation:

  Rebuild Permissions If the site is experiencing problems with permissions to content, you may have to rebuild the permissions cache.
  Possible causes for permission problems are disabling modules or
  configuration changes to permissions. Rebuilding will remove all
  privileges to posts, and replace them with permissions based on the
  current modules and settings.

  Rebuilding may take some time if there is a lot of content or complex
  permission settings. After rebuilding has completed, posts will
  automatically use the new permissions.

You then asked:

  Can I go for Reubuild Permission?

Sure. This process can take a long time though for a site with many nodes and content.

  Will it cause any problem for current modules?

Depending on your situation and the new modules you've installed that are changing how content permission is being assigned rebuilding permissions may or not affect your users. You must first verify what modules are affecting the content permissions and be sure you've assigned appropriate permissions to specific roles that may be using them. It is your responsibility as site owner to be aware of module dependencies.


How do I make my service dependent on another module existing? I want to provide a service in my module, but only if another module (say the core File module) is enabled. I don't want to require this module, it should be optional.

Something like this:

services:
  helper.file:
    class: Drupal\helper\File
    arguments: ['@entity_type.manager']
    requirements: ['file']

Is there a way to do this without needing to declare it as a dynamic service? If not, is there an example on how to declare a dynamic service, because https://www.drupal.org/node/2026959 is woefully lacking:

  Finally, it is also possible to define the register() method to register services dynamically, however this should be very rare.

Yep, you need a ServiceProvider that only registers the service if the module exists in the container.modules parameter

See https://github.com/md-systems/file_entity/blob/8.x-2.x/src/FileEntityServiceProvider.php#L25 for an example


How do I enable a custom JS file in my Drupal site? In my Drupal themes' folder I've created a file named "custom-js.js".

I created this file to use 2 jQuery manipulations on a small text block that appears in all pages of the site.

My question is, how do I enable this JS file? How do I "link it" with Drupal, so that it's actually being used in my site?

There are several ways to add JS files to Drupal, depending on the requirements.

If the JS is related to your theme and used on every page, perhaps easiest to add the file to your theme's .info file

create the JS file in mytheme/custom-js.js and configure it for the theme in mytheme.info

scripts[] = js/custom-js.js
Flush all caches to register the new JS file.

More info: https://www.drupal.org/node/756722


How to hi-lighten with red border when multi check box fails validation. I've been searching around for days but can't find the solution.. I know this is a core bug and have found two solutions on http://drupal.org but both of them don't work for multi check box validation on my site (It works for single check box and multi radio buttons though).

These are what I have found:

Required radios/checkboxes are not validated (D6)

move checkboxes error class to parent div, so that checkboxes can be given a red border like other fields

My problem is that it's not outputting the error classes only for multi check box even after using those methods above.
Any idea how to fix this?

Have you tried this module: Checkbox Validate ?

  Corrects bugs in Drupal core:

  Checkboxes set as required not displaying required symbol (install this module to display)
  Checkboxes set as required behave as optional (install this module to make behave
  as required field)

  This is the related D6 issue: #259292: Required radios/checkboxes are not validated (D6).


"Promote to front page" to other than front page Is it possible to push node summaries (teaser text) onto pages other than the "Front Page"?
I see the option "Promoted to front page" but is there a workaround for promoting them to  sub-pages as well?

"Promoted to front page" can be used as a views filter. So you could create views based on that (so it displays node teasers that have a certain taxonomy and are "Promoted to front page").

Another simple way to mimic "Promoted to front page" is to add a taxonomy select field to your content types, and then the taxonomy pages would display the specified content.

Does this answer your question?


Bootstrap and require a method from a separate module I have a script that runs outside of my module, which bootstraps Drupal.

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;
use Drupal\smart_ip\SmartIp;

chdir('../..');

$autoloader = require_once 'autoload.php';

$request = Request::createFromGlobals();
$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();

$ip = $request->getClientIP();

$location = SmartIp::query($ip);

My problem is that using the Smart IP query method (SmartIp::query($ip)) throws an error:

TypeError: Argument 1 passed to Drupal\Core\Session\SessionConfiguration::getOptions() must be an instance of Symfony\Component\HttpFoundation\Request, null given, called in /var/www/drupalvm/sitelog/core/lib/Drupal/Core/Session/SessionManager.php on line 111 in Drupal\Core\Session\SessionConfiguration->getOptions() (line 40 of /var/www/drupalvm/sitelog/core/lib/Drupal/Core/Session/SessionConfiguration.php)
#0 /var/www/drupalvm/sitelog/core/lib/Drupal/Core/Session/SessionManager.php(111): Drupal\Core\Session\SessionConfiguration->getOptions(NULL)
#1 /var/www/drupalvm/sitelog/vendor/symfony/http-foundation/Session/Storage/NativeSessionStorage.php(278): Drupal\Core\Session\SessionManager->start()
#2 /var/www/drupalvm/sitelog/vendor/symfony/http-foundation/Session/Session.php(87): Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage->getBag('attributes')
#3 /var/www/drupalvm/sitelog/modules/smart_ip/src/SmartIp.php(100): Symfony\Component\HttpFoundation\Session\Session->get('smart_ip')
#4 /var/www/drupalvm/sitelog/modules/smart_ip/src/SmartIpLocation.php(167): Drupal\smart_ip\SmartIp::getSession('smart_ip')
#5 /var/www/drupalvm/sitelog/modules/smart_ip/src/SmartIpLocation.php(133): Drupal\smart_ip\SmartIpLocation->getData(false)
#6 /var/www/drupalvm/sitelog/core/lib/Drupal/Component/DependencyInjection/Container.php(264): Drupal\smart_ip\SmartIpLocation->__construct()
#7 /var/www/drupalvm/sitelog/core/lib/Drupal/Component/DependencyInjection/Container.php(177): Drupal\Component\DependencyInjection\Container->createService(Array, 'smart_ip.smart_...')
#8 /var/www/drupalvm/sitelog/core/lib/Drupal/Component/DependencyInjection/Container.php(494): Drupal\Component\DependencyInjection\Container->get('smart_ip.smart_...', 1)
#9 /var/www/drupalvm/sitelog/core/lib/Drupal/Component/DependencyInjection/Container.php(236): Drupal\Component\DependencyInjection\Container->resolveServicesAndParameters(Array)
#10 /var/www/drupalvm/sitelog/core/lib/Drupal/Component/DependencyInjection/Container.php(177): Drupal\Component\DependencyInjection\Container->createService(Array, 'smart_ip.get_lo...')
#11 /var/www/drupalvm/sitelog/core/lib/Drupal.php(158): Drupal\Component\DependencyInjection\Container->get('smart_ip.get_lo...')
#12 /var/www/drupalvm/sitelog/modules/smart_ip/src/SmartIp.php(36): Drupal::service('smart_ip.get_lo...')
#13 /var/www/drupalvm/sitelog/modules/sitelog/sitelog.php(23): Drupal\smart_ip\SmartIp::query('192.168.88.1')
#14 {main}.

I hoped that by putting use Drupal\smart_ip\SmartIp;, at the top of my script, I would have access to the module's methods, but I don't.

I don't understand what is required to make the Smart IP query function available to my script?

For this case you have to add one additional step to your bootstrap code.

Put $kernel->preHandle($request); right below the $kernel->boot();


User 1 becomes anonymous on node/add, access denied messages I had been developing a Drupal site locally and put it up online recently without much problems. Our server runs in PHP Safe Mode, but I've already got most of the website working nicely. The only weird thing that is happening now is that I, as the User 1/Admin with all permissions configured correctly and accordingly, have been unable to add any new nodes. I can manipulate views, add content types, change the appearance, use deltas and contexts, administer users, and do pretty much everything except add new content. I have been working around this by using Devel to generate some nodes, but this is clearly a flawed work flow. Oddly enough, I can view the list of current content and edit any node I please. I just get "Access Denied" when I got to http://www.example.com/node/add. For all content types. And they do show up in the administer menu, so I don't think it has anything to do with the content suddenly being unavailable.

Looking at the action/error log, I find that those "Access Denied" errors are happening to "Anonymous," even though I have clearly logged in. I have tried flushing all the caches, rebuilding permissions, and still no luck. I also tried making another admin account, and that user runs into the same problem. Does anyone know what this might be and how I can fix it? It's kind of important to be able to add content.

EDIT:  This is on Drupal 7.14

Those who come and find this question unsolved can use the solution at d.o which is

  Solved it!! It had to do with the .htaccess file! I needed to comment
  the following with regard to SSL Certificates.

# SSL Certificates
#  RewriteCond %{HTTPS} !=on
#  RewriteRule (user|admin) https://%{SERVER_NAME}%{REQUEST_URI} [L,R]
#  RewriteCond %{HTTPS} !=off
#  RewriteRule (node/*/edit|node/add/*) http://%{SERVER_NAME}%{REQUEST_URI} [L,R]

  I am not entirely clear on why it suddenly worked, but obviously it
  has something to do with these rewrite rules.


Colapse even rows of table I have a table in my site that I build in my own module with theme table. I want to be able to have a sort of link in each even row (the ones with the color buttons) that allows me to collapse those rows. In fact, when loading the page, those rows should be already collapsed and only visible if the user wants.

Is this even possible using theme table? Is there any alternative I should use to do it?

Thanks

Maybe ctools_collpasbile is a solution? http://timonweb.com/posts/painless-collapsible-divs-in-drupal/#

I just can't apply it to my table.


How to make a numeric textField in Drupal WebForm? Can anyone suggest how to make a numeric only textfield in WebForm for a mobile number field?

You can use the Webform validation module to create such validation.


Drupal 6 - Grouping Modules together I have been creating a lot of code in the past few months for my Drupal 6 website and have since created about 20 modules of code that all pretty much go together.

I know we can group modules together in a folder, but am wondering what impact this will have if I do this on already deployed modules.

Is it possible for me to simply create a new folder in the sites/all/modules folder and move all my modules in this new folder? Will Drupal handle this properly?

Grouping modules is allowed in Drupal, when the modules are not already modules. Because, the modules are registered in System table by the location of the module. So, Changing the folder structure will result in fatal errors.

If you would like to change the folder structure then you need to disable the modules and uninstall them. After that, you can re-enable them after changing the folder structure by grouping them.

Note: Make sure you won't lose any data when you un-install the custom modules. Take a backup of database and source code before doing any changes for safe side.


why do I receive wrong Notice: Undefined index? There is a view and content type both called activities and this is views-view-fields--activities--block.tpl.php

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

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

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

this block is displayed in the front--page.tpl.php and it works right.
There is another block of this view and that block is displayed in the node page. this block only contains 10 title. the problem is drupal reports this warning in the node page:

Notice: Undefined index: field_activities_image in include() (line 2 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_summary in include() (line 5 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_image in include() (line 2 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_summary in include() (line 5 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_image in include() (line 2 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_summary in include() (line 5 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_image in include() (line 2 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_summary in include() (line 5 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_image in include() (line 2 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_summary in include() (line 5 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_image in include() (line 2 of ...views-view-fields--activities--block.tpl.php)
Notice: Undefined index: field_activities_summary in include() (line 5 of ...views-view-fields--activities--block.tpl.php)

The ID of the block that is displayed in the node page is block_1 but it tries to use views-view-fields--activities--block.tpl.php. how can I solve this warning?

I think that the name views-view-fields--activities--block.tpl.php is a suggestion for all blocks of the view activities - to get better specified template name check template information in that view. ('Information' link under Other -> Theme in the view builder) I think that the template name should be something like views-view-fields--activities--[block_id].tpl.php.

Change the block machine name if necessary.

Also, its a good practice to utilise this in templates to prevent such warnings:

<?php if (!empty($fields['field_activities_image'])):?>

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

<?php endif; ?>


Disable Product Display upon purchase of the Product or it's variations I have a site of products wherein each Product Display has 2 Variations (Products).

I would like it so when a single variation is purchased the Product Display get's unpublished (regardless of a variation still being available for purchase).

I've been trying to do this with Rules with little success, has anyone come across this before or know of a solid solution?

The Disable product when it was purchased issue on d.o. deals exactly with this problem.


Location of core theme functions? Where can i find the core theme function code (D7)? I would like to use the table theme function as a template for a new theme function I'm writing.

Arnold

Check out the API Docs on Drupal.org.  There you will be able to find the description on how to use the functions as well as the actual code of the function.  For your use, here is theme_table().  The actual function is in "includes/theme.inc, line 1631" as stated in the theme_table() documentation page.


How to count the number of post by author in D7? I am using the following code in drupal 6 but now this code does not work with Drupal 7.

<?php
$uid=$node->uid;
$results=db_query("select COUNT(nid) AS count from node where uid=$uid");

while ($res = db_fetch_object($results)) {
print "
" . $node->name . " has submitted " . $res->count . "          source code / articles.
";
}
?>

My primary problem is on how to query the number of post like the sql statement above as:

db_query("select COUNT(nid) AS count from node where uid=$uid");

Anyone know the equivalent to this on D7?

BTW, I want to use the code in display suite module.

The result of db_query() should now be iterated over directly, db_fetch_object() isn't part of Drupal 7.

You could also make use of the fetchField() method to get the result of your COUNT query:

$uid = $node->uid;
$args = array(':uid' => $uid);
$count = db_query('SELECT COUNT(nid) FROM {node} WHERE uid = :uid', $args)->fetchField();

print "
$node->name has submitted $count source code / articles.
";

The above example uses the preferred method of passing arguments to a database query, it's safer than including them directly in the query string.

If you did want to loop over the results (for a query with more than one row/field) you'd do it like this:

$result = db_query('SELECT * FROM {node}');
foreach ($result as $row) {
  $nid = $row->nid;
}


structure_sync not working I am trying to use structure_sync within my Drupal 8.4.4 project to export the block content of custom blocks as a configuration (see also the discussion "Custom blocks cannot be properly exported and imported").

Installation via composer went fine and the module also reports everything goes fine when trying the export-blocks function for example:

$ drush export-blocks
Exporting blocks...
Exported "Copyright"                                          [ok]
Exported "Social Links"                                       [ok]
Exported "Flyout"                                             [ok]
Successfully exported blocks                                  [ok]
The custom blocks have been successfully exported.            [status]

However, no configuration files were actually created in the sync_dir (or elsewhere).

Is there some other undocumented pre-requisite?

It is not well explained in the documentation, but structure_sync works by generating a new configuration item with all the exported content. It does not generate new files by itself.

Later, when you export the configuration, the new config item appears.


What is the correct way to update my cached block when a node of a given type is saved or updated? I have a custom module with a block plugin:

SliderBlock.php

class SliderBlock extends BlockBase {
  public function build() {
    $build = [];
    $build['#theme'] = 'slider_block';

    return $build;
  }
}

I want to render a list of nodes of type 'slides' in the block (it will eventually be a custom slider feature)

mymodule.module

function mymodule_theme() {
  return [
    'slides_block' => [
      'variables' => [
        'slides' => get_slides(),
      ],
    ],
  ];
}

function get_slides() {
  // Load all slides nodes.
  $nids = \Drupal::entityQuery('node')
    ->condition('type','slides')
    ->condition('status','1') // Only published slides nodes.
    ->execute();
  $nodes =  \Drupal\node\Entity\Node::loadMultiple($nids);

  return $nodes;
}

and I loop over each in the template to get the markup I need:

slider-block.html.twig

{# markup for slider here #}
{% for slide in slides %}
  <p>{{ slide.label }}</p>
{% endfor %}

The above template shows me the title field for each Slides node, which is what I expect. The problem is that if I un-publish a Slides node, the markup is not updated unless I clear caches.

Alright, this sounds like a cache issue, so I dove into a google search mission and discovered a series of ways to disable caching for the block. None of which seem to work, for anonymous users or otherwise:

// Unsuccessful:
public function getCacheMaxAge() {
  return 0;
}

// Unsuccessful:
$build['#cache'] = [
  'max-age' => 0,
];

I looked at cache contexts, as far as I could tell, there was no 'node' based cache context. If I understood them correctly, cache tags wouldn't help, since I don't know the ids of any given node of type 'Slides'.

I 'only want to' disable caching for this block. This block will be rendered only on a specific page, so I could disable caching on that page using the modules route yml file (am I right?), but it feels wrong to disable that whole page for the sake of one block.

What is the right way to solve this, and what's the methodology in reaching that conclusion?

Note: I could use views to collect the nodes, but to customise the view markup is more  challenging.

As @Clive commented you need a node list cache tag.

Put the slides and the cache tag when you invoke the template in the build array (not in a hook_theme(), this hook is only called when you install the module):

class SliderBlock extends BlockBase {
  public function build() {
    $build = [
     '#theme' => 'slider_block',
     '#slides' => getSlides(),
     '#cache' => ['tags' => ['node_list']],
    ];
    return $build;
  }
}

Put a TODO annotation in your code to change the list tag to a content type specific node_list:slides, once you have updated to Drupal 8.9.x. See this change record: Added an ENTITY_TYPE_list:BUNDLE cache tag.


How to repair "Mismatched entity and/or field definition" when "drush entity-updates" fails? I'm developing a site in Drupal 8 in Acquia Dev Desktop 2 on Windows 10. After updating to 8.5.0-beta1 I noticed this error on my status page (although it may have been there earlier in 8.4.4):

ENTITY/FIELD DEFINITIONS
Mismatched entity and/or field definitions
The following changes were detected in the entity type and field definitions.
Custom menu link
The menu_link_content.field_most_common_name field needs to be updated.

It's possible this error came from the Menu Item Extras module, which I had installed a couple of months ago, but since deleted.

Following popular advice, I ran drush entity-updates. That did not cure the problem. The output (typed manually) from my CMD window is below:

menu_link_content entity type :
  The menu_link_content.field_most_common_name field needs to be updated.
Do you wish to run all pending updates? (y/n): y
Drupal\Core\Entity\EntityStorageException: Exception thrown while
performing a schema update. SQLSTATE[42522]: column not found: 1054 unknown
column   [error]
'field_most_common_name_argument' in 'where clause': SELECT 1 AS expression
FROM
{menu_link_content__field_most_common_name} t
WHERE (field_most_common_name_target_id IS NOT NULL) OR
(field_most_common_name_display_id IS NOT NULL) OR
(field_most_common_name_argument IS NOT NULL) OR
(field_most_common_name_title IS NOT NULL) OR
(field_most_common_name_data IS NOT NULL)
LIMIT 1 OFFSET 0; Array
(
)
 in Drupal\Core\Entity\Sql\SqlContentEntityStorage->wrapSchemaException()
(line 1535 of C:\Users\Nick\Sites\devdesktop\drupal\core\lib\Drupal
\Core\Entity\Sql\SqlContentEntityStorage.php).
Failed: Drupal\core\EntityStorageException: !message in
Drupal\Core\Entity\Sql\SqlContentEntityStorage-&gt;wrapSchemaException()
(line 1535 of
C:\Users\Nick\Sites\devdesktop\drupal\core\lib\Drupal\Core\Entity
\Sql\SqlContentEntityStorage.php).   [error]
Cache rebuild complete.   [ok]
Finished performing updates.   [ok]

Based on the 2nd answer here and this reference, I have made a custom module called "Database Fix" with the following content in the database_fix.module file. I am not a coder, so there is plenty of guesswork involved here:

<?php

/**
 * Fix database by updating menu_link_content.field_most_common_name field
 *
 */
function database_fix_update_8501() {
    $manager = \Drupal::entityDefinitionUpdateManager();
    if ($field = $manager->getFieldStorageDefinition('field_most_common_name', 'menu_link_content')) {
      $manager->updateFieldStorageDefinition($field);
    }
}

I enabled the module, refreshed pages and ran update.php, but it didn't work.

Although this question is quite old and no longer relevant for Drupal 8 as drush no longer has entity-updates, I believe people would still be landing on this page with Pending Entity Updates messages in the Status Report. I ran into the same scenario and wanted to address that issue.

The message is shown when the definition of the entity in the database is different from the definition of the entity in the file because of deleting or adding a field in the entity. That is something that is going to happen a lot when you are developing the module and the entity definition keeps evolving.

Uninstalling and installing the module will solve the problem because you are recreating the entity again.

I ran into this same problem and thought I should get to the bottom of this as it was not possible to keep uninstalling and installing the module.

Drush used to have entity-updates as a feature that would allow entity definitions to be updated on the fly. However this was removed from Drupal core in 8.7.0 (Support for entity updates removed from core)

The work around is to install Devel Entity Updates module and run the dentup alternative

If you are using composer

composer require --dev drupal/devel_entity_updates

drush en devel_entity_updates

drush dentup

That should address this problem. The devel entity updates module is to be used in develpment environments only and in higher environments you are expected to push changes to your entities through hook_updates


How to change Node's authored on date? What is the proper way to address and modify a node's authored on date? I created a slew of new nodes via a CSV import via the Feeds module. These nodes now have the date of 2013-07-11 as the authored on date as that's when I did the import. But each node refers to a previous date and I need the authored on date to reflect that.
I have a content type I've created that has a separate Date field where I choose the date. I'd like to eliminate that and just use the authored on date instead.
I'm trying to use VBO to run a custom PHP snippet to make this change but the examples I've found so far do not work.
$object->created = $object->field_date[0]['value'];
node_save($object);

This snippet when run through VBO returns errors:

Notice: Undefined variable: object in eval() (line 1 of /home/chriscor/public_html  /hi_tracker/sites/all/modules/contrib/views_bulk_operations/actions/script.action.inc(20) : eval()'d code).
Notice: Trying to get property of non-object in eval() (line 1 of /home/chriscor/public_html/hi_tracker/sites/all/modules/contrib/views_bulk_operations/actions/script.action.inc(20) : eval()'d code).
EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7693 of /home/chriscor/public_html/hi_tracker/includes/common.inc).

Any idea what I'm missing?

It looks like the $object variable doesn't exist, or isn't in scope. Check the arguments your function receives for the proper node object.


How can I import/rewrite settings/content types/blocks/etc from live with the newly developed features on dev? I have a site that's already up and running. On my local dev environment I occasionally develop new features for that site.

I have certain configs(blocks, settings, etc) that I need to add to the live site. However, I can't seem to figure out a way to import them without deleting the current blocks/settings/etc that already exist on the live site.

Is there some way that I could import them on the live site without deleting them beforehand?

IMHO, using git for that works quite well.

You have a production branch and a development branch (and possibly many feature branches). Locally, you are on the develop branch, you make your changes there, export and commit your changes there

Before you do a deployment, you switch to production branch, do a config export ,sync it down, commit it, merge develop into production, do a local config import to make sure that things are consistent and then deploy.

A useful presentation for this is https://de.slideshare.net/nuvoleweb/advanced-configuration-management-with-config-split-et-al, for example slide 39, although that focuses more on working with multiple developers, but the process with production is similar.


How to change a fields text_format for admin users, and show a plain_text for anonymous users? When a node with body text format as plain_text is posted by anonymous user , how do I change it to full_html when being edited by admin or authenticated user?

Is there anyway I can edit body fields text_format on the go? like through preprocessing or form hooks?

I also have cases where some of the nodes when edited by admin comes with "enable/disable richtext", and for some nodes, it does not show up.

I'm afraid what I assume you are trying to accomplish just isn't available to you because Drupal saves the text entered in a field unfiltered/as is; it then filters it when it is actually displayed or rendered.

So, if you enter for example:

Hello world <some html tag>blah blah blah</end some html tag>

in a text field, that exact content will be saved.

Then, when the entity is displayed, Drupal will look at the text format and if it's plain_text, it will output

Hello world blah blah blah

but if the text format is full html it will output (with minor exceptions)

Hello world <some html tag>blah blah blah</end some html tag>

but once again, in both instances whatever the user inputs will be stored in the database.

Of course, you could create a field that toggles some sort of "display the body with full html after an admin has verified its contents" that would be looked at and if set, display the entity with that field using full html, but until set, would just display it in plain text.


Make t() function translate string on template file? I created a custom page, with my custom module.

Hook_Menu

$items['registered-products/%'] = array(
    'title' => t('Hello World'), // TRANSLATES FINE
    'page callback' => 'mymodule_product_page',
    'page arguments' => array(1),
    'access arguments' => array('access content'),
    'file' => 'includes/mymodule.product_page.inc',
);

Template File

I created a template file (.tpl.php) for my custom page, in here I have:

<?php print t('hello world'); ?> <!-- DOES NOT TRANSLATE -->

RESULT

The t() translates in hook_menu, but on the template file it does not.

What do I have to do so the t() works to on template file?

The problem should be solved as soon as the strings are identical.
In the provided code, hello world is not equal to Hello World.

  Matching strings for translation is case sensitive.


Drupal 7.53 pathauto pattern field do not transliterate I created a new field in on a content type I have on my application (Drupal 7.53), then in /admin/config/search/path/patterns I have set a pattern to this type of content as the following:

[node:field-nw-sitemap:0:url:path]/[node:field_titulo_url].

I expected to have a result like:

mysite/subpath/new-content
it works fine on development environment, but in homolog, witch is online, the return to the url is
mysite/subpath/New%20Content.
Has anyone been here before? Help please. Thanks.

I have tested several times and looked all over the internet, in one test I was able to reproduce the problem in dev environment. The problem was that the filed name contained the keyword "url", the problem persisted with the word "path", once I changed the field machine name to field_caminho everything worked fine.


batch importing node data -- via database? I'm looking to migrate an existing site to Drupal. I have a a content type on the new Drupal site that will eventually hold some 1500 nodes. Of course, I don't want to enter each one in the form on the admin side; I'd like to input them programmatically, from a script.

What I'm wondering is if I can do plain old SQL INSERTS into the node and related tables, and have my nodes ready to use. Assuming I do the inserts correctly, will the nodes just be there when I fire up Drupal? Or will I need to touch some other parts of the site?

Or is there another way, like a module for batch importing?

This is for Drupal 7.

There are two routes you can take.

One uses the Migrate module usually in conjunction with Table Wizard.  This gives you a web front end for doing an import with field mapping, and other nicities.  EDIT: just saw that TW doesn't have a D7 version.

The other is a custom import script.  The script does the Drupal bootstrap process, queries the remote database, creates a $node and then does a node_save.  This is a little more complex, but not that hard.

I have been doing the later on new projects, and is easy to adapt to XML, CSV, or other data sources.


Design concern with custom tpl.php I have a custom tpl.php for my custom content type. As part of its content it also needs to show a (dynamic) value. The dynamic content is actually scraped from another website of ours.

My concern is, whether to have scraper logic inside tpl.php. My understanding is that the intention of tpl.php is to handle the view part.

What are the disadvantages of having my tpl.php to contain the logic of scraping(not just scraping. Basically anything apart from rendering)?

It's bad practice from a general development point of view (look up "separation of concerns")
It can break caching, or render it useless/pointless.
One bit of code should do one thing, and do it in a such a way that is testable.

In my opinion, your logic for scraping should be in its own class, a class that does nothing but scrape. Then your preprocess function should make use of that class, and prepare the variables for the template.

You don't have to do any of this, of course, it's up to you what best practices you want to follow. If you're new to development, take it from me that modularising your code now will probably save you a lot of time when you come back to in 2 years and something doesn't work.


How to get a list of all the selected values for a field programmatically? How can I get a list of all the selected values for a field?

For example I have a field called countries, and I want to get all countries selected for a certain node.

I need to have this list, because I want the region to be automatically selected in another field (regions), according to the chosen country.

Ex: I choose France in the countries, then automatically the European region is selected in regions

For now I can only copy the selected values in the "countries" field, in the "regions" field, by doing this:

$node->field_regions = $node->field_countries;

Here is the result when I select France in the countries field :

Country: France

Regions: France

Edit: I tried with the function:field_get_items(), but all I get is an array:

$items = field_get_items('node', $node, 'field_countries', $node->language);

Something is wrong? I also tried with this but I get the same result...

$items = $node->field_countries[$node->language][0]

Because fields can have multiple values both of the methods you describe will return an array. Each of those array items will itself be an array, of all the possible columns for the field. In the case of text fields the only column you really need to worry about is the value column.

Assuming your particular field does not accept multiple values, or it does and you only want the first value, the following should work:

$items = field_get_items('node', $node, 'field_countries', $node->language);
$item = array_shift($items);
$value = $item['value'];

or

$value = $node->field_countries[$node->language][0]['value'];


Edit Node Title in Template.php UPDATE: I know that I could accomplish this inside of a tpl.php file. But I would prefer to keep as much logic in the template.php file as possible, reserving tpl.php adjustments for markup. I have been informed that Drupal is NOT an MVC paradigm but an AOP, and I am trying to adapt to that as quickly as possible. But I feel that since I have already accomplished this IN the Template.php file that there is bound to be a 'Best Practices' way of doing this that I would like to adopt.

Currently, I have a node_field called field_unique_card. This is a Boolean field.
If field_unique_card == 1 then the title of the node needs to be something like this:

$title = '* ' . $title;

The way I am currently doing it is as follows:

UPDATE: I just remembered the better way of (expr1)?(expr2):(expr3); so I updated my preprocess function.

function theme_preprocess_node(&$variables)
{
    ...
    $variables['title'] =  $variables['field_unique_card'][0]['value'] ? '*' . $variables['title'] : '';
}

I am wondering if this is 'Drupal Best Practices' or if there is a smarter way? I ask because this only affects the nodes when they are displayed as a field. But on every node display there is an additional output of the Node title that happens at the top of the page. I can't figure out how to make it so that the title shows the * there as well.

Any help would be greatly appreciated.

The easiest (and less expensive) way I see to do this is as follows (did not try this, but should work):

Copy node.tpl.php from the core node module (/modules/node) to your theme's folder (/sites/all/themes/).
Modify the code to display the desired title. By default the code to display the title is:

<h2<?php print $title_attributes; ?>>
  <a href="<?php print $node_url; ?>"><?php print $title; ?>

can be changed to:

<h2<?php print $title_attributes; ?>>
  <?php if($unique_card == 1) { ?>
    <a href="<?php print $node_url; ?>"><?php print "*" . $title; ?>
  <?php } else { ?>
    <a href="<?php print $node_url; ?>"><?php print $title; ?>
  <?php } ?>

Note: I used the variable $unique_card because the comments from node.tpl.php mentions:

  Field variables: for each field instance attached to the node a corresponding
  variable is defined; for example, $node->body becomes $body. When needing to access a field's raw values, developers/themers are strongly encouraged to
  use these variables. Otherwise they will have to explicitly specify the
  desired field language; for example, $node->body['en'], thus overriding any
  language negotiation rule that was previously applied.


How to embedding Comment form for each individual item in drupal's view? In my current project I want to embedding comment form for individual item in views but I did not get any settings/ configurations for the same in view. I tried to override template for the same using

print drupal_get_form('comment_form', array('nid' => $nid));

code but I got an error, so please suggest my any idea or any module using that I can show comment form in views.

Error: The website encountered an unexpected error. Please try again later.

In Drupal 7, function comment_form() is expecting an object parameter instead of array. This code should work for you:

$comment = new stdClass;
$comment->nid = $nid;
$form = drupal_get_form('comment_form', $comment);
print render($form);


extracting data from specific content type I have an old site developed with drupal 7 and now I have created a new site (with new template) with drupal 8. I want to extract a specific content type data and restore in the new site. suppose I have a content type called Academic and I want to restore it on the new site. Is it possible to do that automatically, because it has more than 1000 contents. Any help would be appreciated. Thanks in advance

You can create a custom migration for that node type - see https://www.drupaleasy.com/blogs/ultimike/2016/04/drupal-6-drupal-81x-custom-content-migration (more than you need for just the one migration, but it should help).


FetchObject() only return one result Select query will always return a result set object of one record.. There are several ways to then retrieve data from that result set, depending on the use case.

   user's flaged entity id:

  $query = db_select('flagging', 'f');
  $query->condition('f.uid', $data['uid'], '=');
  $query->fields('f', array('entity_id'));
  $result = $query->execute()->fetchObject();

and also used following query statements

         $query->__toString()

         SELECT f.entity_id AS entity_id  FROM {flagging} f WHERE  (f.uid = :db_condition_placeholder_0)

I replace the db_condition_placeholder_0  with specify uid.
It return me the right result (2 results).

   **$query->execute()->fetchAssoc()**`, return one result.

In Drupal 7, there are fetch methods that can help to avoid loops like that. From http://drupal.org/node/310072:

<?php
  // Retrieve all records into an indexed array of stdClass bjects.
  $result->fetchAll();
 // Retrieve all records into an associative array keyed by the field in the result specified.
  $result->fetchAllAssoc($field);

  // Retrieve a 2-column result set as an associative array of field 1 => field 2.
  $result->fetchAllKeyed();
 // You can also specify which two fields to use by specifying the column numbers for each field
  $result->fetchAllKeyed(0,2); // would be field 0 => field 2
  $result->fetchAllKeyed(1,0); // would be field 1 => field 0

  // Retrieve a 1-column result set as one single array.
  $result->fetchCol();
  // Column number can be specified otherwise defaults to first column
  $result->fetchCol($column_index);
 ?>


What does the option "Enable Display field" shown when creating a new file field do/mean? What does the option Enable Display field shown when creating a new file field do/mean?

It will provide you an additional option whether you want to display the attached file or not. As you can see the description provide under that option in following image.

Now enabling it, will add check box option to content editing layer as you can see in following image.

Include file in display

So, if you check it will show the file in final display and if you uncheck it will not show the file.

Hence, it provides one extra quick option to author whether they want to show the attached file or not other-wise previously they had to go back and delete entire file from the content and again if they want to put they have to again upload and insert. Here, it is like On-Off Switch.


Create basic server using Docker I am trying to work out how to create a Drupal dev environment using Docker.  I am trying to use the Docker containers for Drupal (https://hub.docker.com/r/library/drupal/) and MySQL (https://hub.docker.com/r/library/mysql/) to set up a Drupal server.

I am assuming that I need to link the MySQL container to the Drupal container.  I have created a docker-compose.yml file which seems to run fine on docker-compose up (I am using a Mac).

docker-compose.yml file:

drupal:
  image: drupal
  ports:
   - "8080:80"
  links:
   - db
db:
  image: mysql
  environment:
    MYSQL_ROOT_PASSWORD: mysql
    MYSQL_DATABASE: drupal
    MYSQL_USER: drupal
    MYSQL_PASSWORD: drupal
    MYSQL_ALLOW_EMPTY_PASSWORD: yes

After docker-composer completes, I can access the Drupal site from my web browser.  The Drupal installation works up to the point where I have to enter the database details.  At this point it fails:

Make sure to put in the "Host" of the MySQL database under "Advanced Configuration" as db and not the default localhost.


Get the values of a checkbox field in node when evaluating in block condition plugin I have a field that is a checkbox with multiple values... I'm trying to do an evaluation in a condition plugin where I'm checking against the checked values. For a boolean field, the syntax is:

$value = $this->getContextValue('node')->field_news_filter_menus->value;

Since field_news_filter_menus is a checkboxes field, I need to get the array of checked values.
These all return null:
$this->getContextValue('node')->field_news_filter_menus->list->values;
$this->getContextValue('node')->field_news_filter_menus->values;
$this->getContextValue('node')->field_news_filter_menus->list;

PHPstorm xdebug says the path is $this->getContextValue('node')->field_news_filter_menus->list[0]->value;
But null is returned for that also.
I can see the values in xdebug that follow a path as $this->getContextValue('node')->field_news_filter_menus->list[0]->values and see an expected value, but that path also returns null.

What is the syntax for getting that array list?

Original Answer

The proper way to access field values is $entity->get('my_field')->getValue() in your case this will return an array like:

Array(
  0 => Array(
    'value' => 'value1'
  ),
  1 => Array(
    'value' => 'value2'
  ),
  2 => Array(
    'value' => 'value3'
  ),
  // And so on as many values your field has.
)

Also you can check if the field is empty by calling $entity->get('my_field')->isEmpty(). Calling only your field like $entity->get('my_field') will NOT return the field value but the field instance. Calling for an unexisting field will throw a runtime exception.

UPDATE

To check if the value exists you can either iterate over the array or do something like this

$arr = [
  0 => [
    'value' => 'value1',
  ],
  1 => [
    'value' => 'value2',
  ],
  2 => [
    'value' => 'value3',
  ],
];

$arr = array_map(function ($v) {
  return $v['value'];
}, $arr);

assert(in_array('value2', $arr, TRUE), 'Assert that contains value2');
assert(in_array('other', $arr, TRUE), 'Assert that contains other. This will fail');

You can try it here.


How to delete a cck field base in Drupal 6 I have programatically created some cck fields with this function:

content_field_instance_create($field)

and I tried to delete them with this:

content_field_instance_delete($field_name, 'product', FALSE)

However, this didn't actually delete the cck field from the Product types database table. The fields didn't show up on the UI edit page but they still exist in the database, which is causing me some issues.
How can I systematically make sure the database entry is wipes as well?

I believe deleting the fields programmatically like this flags the fields as deleted by CCK or the Field API in Drupal 6/7. You must then run Cron to have the system fully purge the database tables from the system.