How to do a redirect in node.html.twig? I'm trying to do a redirect on my node.html.twig template based on the content type because I'm using views for my content.

I tried this:

{% do redirect('/example') %}

or this:

{% redirect '/example' %}

but nothing works. Any idea?

Don't do it in the Twig file. This is not where that logic belongs. It should be in an Event.

See this similar question: EventSubscriber called on specific node type or path

All that is left is checking the node type and sending a RedirectResponse.

Gabe Sullice has a Gist that sounds very close to what you are trying to accomplish: https://gist.github.com/gabesullice/96bdae1518d11bb4565e72c33ffcae4c

So your code would fill in something like:

  /**
   * Determines whether we should send a RedirectResponse for this node.
   */
  protected function redirectApplies(NodeInterface $node) : bool {
    $redirect_types = ['type_1', 'type_2', 'type_3'];
    return in_array($node->getType(), $redirect_types);
  }

But if you go to different urls for different types, you will need to adjust it a little more.


Drupal Relative Path I am using Drupal 7. The website I am on was configured previously. My goal is to add an external link to a page. However, i am having trouble. Every link I add to any page is read as a relative link. For example, if I have the following code:

Google

The URL in the browser becomes: dev.mysite.com/#http://www.google.com
But, I want the URL to be http://www.google.com

First, Can i fix this using PHP?
Second, Is this something the Pathauto Module is responsible for, or maybe the Rewrite module? Both are enabled on the site
Lastly, is it a mod rewrite issue? If so, how would i fix it?

You must have some kind of text filter that is acting on your text
see what filters are applied here:
admin/config/content/formats

Or you are using a WYSIWYG editor to add the link.  If that is ckeditor, you have to set relative links to "Other" rather than http in the link editor.


Composer.json deletes dir even with preserve path I am running composer on Drupal 7 and I am just trying to update my site; however when I run composer update, the composer deletes all the preserve paths I had specified.

My structure is as follows:

composer.json

composer.lock

web/

    -sites/default

in my composer.json I have as follow:

{
...
"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/7"
    }
],
"require": {
   ...
},
"conflict": {
    "drupal/core": "8.*"
},
"minimum-stability": "dev",
"prefer-stable": true,
"config": {
      "sort-packages": true
},
"autoload": {
    "classmap": [
        "scripts/composer/ScriptHandler.php"
    ]
},
"scripts": {
    "pre-install-cmd": [
        "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
    ],
    "pre-update-cmd": [
        "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
    ],
    "post-install-cmd": [
        "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
    ],
    "post-update-cmd": [
        "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
    ],
    "post-create-project-cmd": [
        "DrupalProject\\composer\\ScriptHandler::removeInternalFiles"
    ]
},
"extra": {
    "installer-paths": {
        "web/": ["type:drupal-core"],
        "web/profiles/{$name}/": ["type:drupal-profile"],
        "web/sites/all/drush/{$name}/": ["type:drupal-drush"],
        "web/sites/all/libraries/{$name}/": ["type:drupal-library"],
        "web/sites/all/modules/contrib/{$name}/": ["type:drupal-module"],
        "web/sites/all/themes/contrib/{$name}/": ["type:drupal-theme"]
    },
    "patches": {
        "cweagans/composer-patches": {
            "Call the preserve paths hooks" : "https://github.com/SebCorbin/composer-patches/commit/1cb9bacba51f8bba0c5f3f322c3bb61e4ceae974.patch"
        }
    },
    "preserve-paths": [
        "web/sites/all/drush",
        "web/sites/all/libraries",
        "web/sites/all/modules/contrib",
        "web/sites/all/modules/custom",
        "web/sites/all/modules/features",
        "web/sites/all/themes/contrib",
        "web/sites/all/themes/custom",
        "web/sites/all/translations",
        "web/sites/default"
    ]
}

}

What ends up happening is it install the core and modules correctly in web/ folder, but deletes all the preserve paths as well. Any suggestions as to why i am having this problem? Thank you.

I have tried to put composer.json in the web/ folder as well, that just imports all the require modules and core in a subfolder (web/web/).

I am now getting:

Files of installed package were overwritten with preserved path x/web/sites/default!

Files of installed package were overwritten with preserved path x/web/sites/all/libraries!

and the preserve paths didn't do anything.

It looks like you haven't installed the plugin. Just run:

composer require drupal-composer/preserve-paths

And try again.

If it still doesn't work, you'll probably need to report it as a bug to the plugin's issue queue.


Using panels everywhere... without Panels Everywhere I recently discovered how awesome Panels is and I want to use it as a replacement essentially for the default theming mechanism that comes with Drupal (I'm using version 7).  In fact, I want to use it just about everywhere.  Unfortunately, it looks like the Panels Everywhere module for Drupal 7 is completely dead.

I noticed that any panel that you create is just dropped into the content area.  So, with an out-of-the-box Drupal installation that is going to leave all the heading information at the top of the page intact, even if you've defined a header section in your panel.

So, right now I'm thinking that the best way to deal with this is to tell Panels to disable output to regions, and to also override page.tpl.php so that it doesn't include any extraneous junk with the exception of wrapper HTML and the content region.

Does this approach make sense or is there a better way to go about accomplishing this?

I believe the answer to your question is "Use Panels everywhere". :)

As one of the maintainer of Panels Everywhere, I wonder what you mean with "completely dead"? Yes, I'm a bit slow in the issue queue, but that's because 1. Both me and merlin are crazy busy with the Panels queue (318 issues vs 15), and 2. I'm also not aware of any serious issues. Any help from the community in the Panels queue will greatly help with any PE issues as well.

You should use Panels Everywhere because:

There only thing that's preventing a stable release is a bug on d.o. (I just now updated the module page to say so.)
Merlin is also planning to redo the UI to be much more user friendly.
I build websites with Panels everywhere every single day at work. It works great. If any serious issues were to come up, they will most definitely be fixed. At NodeOne, we build nearly every single site with PE. We need it to work well. :)

I will take the opportunity to shamelessly suggest that anyone interested in Panels and/or Panels everywhere could contribute a bit of time to the issue queue. The current number of contributors, 2, is vastly outnumbered by the number of questions being asked. This slows down development considerably. My d.o profile has the necessary info for contacting me about this. :)


better exposed filters for block view I have created a block view for filter options and tried to display the filter options as check boxes using Better Exposed Filters(BEF) but in the BEF settings i don't get check box option in select option list of  "display tid as" drop down. now how to solve dis problem?

Make sure that the term reference field settings is set to "Dropdown" and Under views Other settings Use Ajax option is set to "Yes"


Error 500 on accessing update.php Long ago I got a message about updates to my modules. I've updated the modules.
But I received a message to update the database.

I want to run the update.php script but I encounter the following error message:

  Server error.

  The website encountered an error while retrieving http://MYSITE.COM/update.php. It may be down for maintenance or configured incorrectly.
  Here are some suggestions:
  Reload this webpage later.

  HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.

I do not remember which modules got updated.
Please help me.

The errors output to Apache are often somewhat cryptic.

You probably want to check the Drupal Reports page, dblog, and the Apache logs.

This sounds like one of the new updates has a problem in the .install or cannot be loaded (permission problems, although that comes proper from Drupal, I never had that problem on an upgrade.)

To test whether the PHP code is invalid, you can run

 php <filename>

The update.php will generate some errors, but it should not tell you it cannot parse it. All the module .install should not generate any errors (a very few modules have code outside functions and those will generate errors, but again no syntax error.) Those syntax error are reported by Apache.


Autofill fields for logged-in users I have a content type with several fields; one field defines a postal address. If new content is created and the user has logged in, this field should be automatically filled with the address defined in the user profile. If a guest is creating new content, he will have to fill in the address by himself.

How I can achieve this? Are there any modules?

The Token module is a start, but it alone won't allow you to pre-fill the content.  By default it will provide a token for the value of every field defined in the user profile.


update order status after order creation i try to update status like this

function module_order($op, &$arg1, $arg2) {
  switch ($op) {
      case 'update':
      $money = 'Cash';
      if (isset($arg1->custompane) && $arg1->custompane == $money) $arg1->order_status = 'completed';
      break;
    }
}

It does not work.

What do I do wrong?

Use conditional actions to achieve this. Conditional actions are part of Ubercart.


View for Full Content? I have a custom content type named "My content type".

I want to use a custom view to render a full content page for that content type. Currently I can only use a Default view that can be found in "Structure > Content types > My content type > manage display" but that is not what I want. I want to get rid of that and be able to use a custom view (from Views module).

How can I achieve that?

I would recommend you to have a look on the Display Suite module. This module allows you to add different view modes (displays) for your content. These view modes can then be used in several places. Beside that, the display suite module offers a lot of other very handy features to deal with any entity in your system and how they are displayed.


CAS module - disabling auto login / want nonpersistent cookies - deleted when browser closes Our security team says we need to modify the cas module so that it either deletes the session cookies when the browser closes or use a session variable rather than a cookie. I can't figure out how to satisfy their requirements. I don't see such a setting in the cas module.

Currently, the cas module auto logs in users even though the Gateway autologin setting is disabled. The security team says this is OK on the first load but after the browser is closed, the site is not reauthenticating but instead relying on the cookie which is not acceptable. I don't know how they know this is what is happening.

I'm using Drupal 8.5.3.

It seems to me that the CAS settings under Configuration -> CAS

Gateway Feature (Auto Login)
when the radio button "disable gateway feature" is checked, that users should be required to login but though this option is checked, they are not required to login.

The cas module READ.md file writes this about the Gateway feature,
 "This feature is not currently compatible with any form of page caching."

Page caching is disabled in settings

$settings['cache']['bins']['render'] = 'cache.backend.null';

Dynamic Page cache is also disabled

$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

In addition, the CAS settings "Forced Login" is enabled.

php.ini has cookie lifetime set to 0

; Lifetime in seconds of cookie or, if 0, until browser is restarted.

session.cookie_lifetime = 0

Thanks for any help.

Resolved:

I resolved this issue by making the following changes to the following files:

core.services.yml
default.services.yml
services.yml

# Set session cookie lifetime (in seconds), i.e. the time from the session
# is created to the cookie expires, i.e. when the browser is expected to
# discard the cookie. The value 0 means "until the browser is closed".
# @default 2000000
cookie_lifetime: 0

Not sure if this would meet your requirements but look at the require_login module.  I'v done CAS and Shib authenticated sites using this module.

My solution was to have an excluded custom login page that was set up as the user login path in this module.  This page generally had the welcome / security blurb and a button that linked to the Authentication agent (CAS / Shib).  I seem to remember having to custom craft this to include the page to return to after login.

The part that might not work for you is that if a user had authenticated via CAS on another site and then came to this site, they did not see this page but where autologged into Drupal.. after all CAS, Shib, and the like are Single Sign On solution.. ;)

This might work for you with the Gateway option off.

Otherwise you might have to look at creating a custom event subscriber that handles the CAS authentication.  E.g., if a user logs in and they are a CAS user, send them to the login page.  Set some flag on the login page and then allow them to "login".


Can I theme fields depending on view or block that contains them? Let's say I have a contact content type with fields address, tel, fax, etc. My task is to create 2 views - with following markup:

First view

[address]

[tel]

[fax]

Second view

[address]

[tel]

[fax]

The above is just a simple example, in general I want to know how much control can I get over fields html markup, can I somehow change it depending on view or block that contains the field or even depending on field itself. If so - what is the best way ?

Here is introduction for views2. To read manuals exactly for your views version, use Advanced Help module.

You can template everything, overriding template files in complex manner.


What function should I use to truncate a string? What function should I use to truncate a string in Drupal 5?

truncate_utf8() is present in all Drupal versions; just check that the parameters are the same.


entityFIeldQuery on user table, how can I add a condition for $user->data I have tried extending EntitiyFieldQuery to add a condition that would be able to match on a $user->data["somevar"], but to no avail. I am not sure this is even possible, as  $user->data is serialised.

I have just the base class working, returing users with status set to 1:

class SubscriberEntityFieldQuery extends EntityFieldQuery {
  // define some defaults for the class
  public function __construct() {
    // now we don't need to define these over and over anymore
    $this
      ->entityCondition('entity_type', 'user')
      ->propertyCondition('status', 1);
  }
}

Would anyone have an idea if this is even possible? Or would I need to resort to using db_query for a case like this?

The data column contains a serialized PHP string, which MySQL doesn't understand. As far as MySQL is concerned the data is just a string like any other.

Because of that you won't be able to query the properties of the serialized objects in that column without doing some seriously nasty work with SUBSTRING/regex/insert-other-unreliable-method-here.

If possible you should add a field to the user entity instead that represents the same data, and use the EntityFieldQuery with that field. It might not be ideal but it's probably the easiest solution.


Create View That Overlays The Theme When Field Clicked Hello i like the feature that ive seen on a few themes where it lets you have an overlay button top left and when you click it it overlays the whole screen with a grid or in my case a picture. Here;s a video explaining more if you dont mind. Its just brief.
http://www.youtube.com/watch?v=cwXV20VJAr8&feature=youtu.be

I would like to create a View and let the items on it have the same function as this overlay button. Im sure it would be possible. I could do most of it barr the action of clicking a view title (button) and making html overlay.

Actually there sounds like there will be a module to do this. I would rather avoid if i could. Maybe some jquery or something wuld be easier?

Thanks

You can achieve this effect like this for example:

You put a view block on top (which will overlay the other content) and put the other content below, position them on top of each other with position: absolute.
Then create a button and position it however you prefer.
Use jQuery .click() with this button (http://api.jquery.com/click/) to hide and show your view block. One possible solution is that on click, you examine if the view block has a "hidden" CSS class (for example). If it has "hidden" on click, you remove the class with .removeClass("hidden"), if it doesn't have the class, you add it with .addClass("hidden").
CSS styling should be like this: .hidden{ display: none; }


One filter criteria for two different displays of the same view? Hi there drupal wizards.

I want to be able to filter two different view displays and display the search results of a filter query simultaneously on the same page with only one shared filter criteria search that works on both views.

I have no problem to do the filter criteria for each one, but I want one common filter search criteria that filters both views and displays them one after the other on the same page.

How do I do this?

If possible I don't want to hack code, just configure things.

To be more precise:
I have one map search working based on location data. The filter is exposed as a block. However I've created a block display showing the same view as a table list that the filter block query does not seem to affect at all. I'm using context to display the second view display block In the same path.

Seems like you want to display two different views with a common shared exposed filter in the same page (or as you said "same path"), instead of making two displays of the same view:

After created your view and your primary "view block", add the needed filter to that block, make sure that the filter is valid for all pages.
Then create an Attachment (you can find it in view configuration page Add>Attachment), and attach its to the block in
Attachment settings by chosing "Attach to:Block" and set a preferred
display position of that attachment (Attachment position)
Configure your Attachment with your needed format and fields, making
sure that these configurations are for "this Attachment
only"(*override)
Finally Set to Yes the "Inherit exposed
filters:" in Attachment settings
Et voilà enjoy your block+attachment with the same shared filter!

If you want to share the same filter in more than one views globally in the entire site, you can take a look to modules like Views Global Filter


Drupal 7: use Form API to make a button that doesn't submit the whole page I want a button that runs a callback function using the AJAX method included in Form API.
The button I have still submits the whole node edit form. I don't want it to do that - just pass a couple variables to the callback function and display the results. How can I do that?

This is my FAPI code for that button:

    $form['rid_import']['rid_get'] = array(
                '#type' => 'button',
                '#value' => t('Import'),
                '#attributes' => array(
                    'id' => array('fetch_rid'),
                    'class' => array('col-sm-3', 'col-xs-4')
                ),
                '#parents' => array('rid_import'),
                '#limit_validation_errors' => array(),
                '#executes_submit_callback' => false,
                "#submit" => array('sql_no_submit'),
                '#ajax' => array(
                    "callback" => 'sql_fetch_restid',
                    "wrapper" => 'rid_sql_query',
                    "event" => 'click'
                )
          );

EDIT

You're right, I was being unclear. Basically what I wanted is something that works like your "Add More" or "Remove" buttons when you have multiple-value fields, but just to run my function without reloading the page – grab some data from the DB and show it there on the node edit form. I have a multivalue field collection that should be populated with those values and then saved together with the rest of the node. That's why I don't want it to go ahead and save the node. However, if it isn't possible I guess I will have to find another way to do what I need.

And tried to add a submit function, still reloads the whole page.

Just try to use "submit" as the type and specify a custom "#submit". From the ajax_example module:

$form['add_name'] = array(
  '#type' => 'submit',
  '#value' => t('Add one more'),
  '#submit' => array('ajax_example_add_more_add_one'),
  '#ajax' => array(
    'callback' => 'ajax_example_add_more_callback',
    'wrapper' => 'names-fieldset-wrapper',
  ),
);

This does not submit the form with the default submit handler but with your own. In this case it is "ajax_example_add_more_add_one".

Hope it helps, j


Matching values between two different fields, each of which have multiple values I have a content type with an imagefield and a link field. Each of those fields accepts four values; so the user uploads four images and types four URLs in each node.

I want to use Views to create a block based on that node that displays the first image linked to the first URL; the second image linked to the second URL; etc. I don't want to use CCK 3 with Multigroup (if possible) because it seems to sometimes cause weird behavior in Views, Contemplate, etc.

Given the existence of Delta fields, "Group multiple values", etc., it seems like this should be possible. But I can't make it work. Is it possible? Or should I bite the bullet, use CCK 3, and hope it's not confusing as all get-out?

You shouldn't use delta for such thing as data sometimes get reordered in the tables (ex: for node reference, the nid gets reordered regarding the title of the node referenced).
So I'll recommend you to create 4 fields for images and 4 for the URL and eventually put them in groupfields.

Also to make things prettier you can theme your form and put each group of field in a row using div or table.

Have a look at Theming Forms in Drupal 6 for information regaring form theming and the official documentation: The theme registry for special cases.

Another nice tutorial: http://www.akchauhan.com/theme-drupal-form/


Ecommerce site with square area calculation in price I am currently looking to make a shop selling carpets. For this I need to use a system that calculates a price per Square area. I have seen Posts where people are in the same position as I am but had no feedback. Is Magneto the answer or Ubercart Druple 6 or 7. I am a developer with no Drupal experience and I am using this as an introduction to Drupal.

Any advice for the best solution would be much appreciated.

I strongly recommend you get some formal instruction, such as the book "Pro Drupal Development" or "Front End Drupal" as well as get accounts at BuildAModule.com and/or Drupalize.me to get a deeper look into Drupal. The decision is ultimately one where you need to figure out your own level of technical competence - creating an eCommerce web site is complex, with legal ramifications if you screw up. So, this is serious.

Magneto is a good platform, but they just got bought by eBay, and in my mind that places their structure (support, UI, community) in an uncertain position. Drupal's not going anywhere but up.

I suggest you create one or two non-eCommerce Drupal sites first, just to learn the environment. Do this on your local machine, so you get personal experience with where files go, their organization, how to add and remove AND update modules. How to configure a what-you-see-is-what-you-get editor, and so on. These are all essential Drupal skills that take time to develop; not a huge amount of time, but time none-the-less that you NEED to spend before you take on the larger and more serious task of creating your online store. After that, move one of your web sites to an online host; forcing you to learn how to manage and maintain a remotely hosted Drupal site. Another essential skill you do not want to be developing with live customers.

Frankly, I would never recommend creating an online store as your first exposure to any eCommenrce environment. You need to be familiar with the CMS first, to insure you are not doing basic entry-level mistakes; such mistakes in a live online store could bankrupt you, land you in jail, or even expose your customers to massive credit card fraud.


Creating a Testimonials Content Type and making it work as it should I have a Testimonials content type which asks for a visitor's name and testimonial. Is it possible to make this form available to Anonymous users so anyone can post a testimonial without having to register?

I don't want people going through the Admin theme so I'm guessing I'll have to create my own form in the standard theme but how do I connect that to the actual Content Type? Posts must also not be published immediately but are set for moderation so I myself can say who gets in and who doesn't. Is this possible?

You can give anonymous users the permission to create content of that type. And you can set the default publishing setting to unpublished (They can't change that unless they have the required permission).

For the theming part, if you are using the admin theme for the node add/edit forms, then you'll have to disable it for that content type. You can do so with a bit of custom code and implement hook_admin_paths() and return 'node/add/content-type' => FALSE path. This will override the definition in node_admin_paths(). Because for a path to be considered as an admin path, there needs to be an entry that returns TRUE and no entry that returns FALSE.


Data coming from entityTypeManager->getStorage is cached data? I am working on one Drupal 8.3 site. I created my own custom Authentication provider for REST API authorisation.

Following are the "authenticate" method sample code.

/**
   * {@inheritdoc}
   */
  public function authenticate(Request $request) {
      try {

          $uid = 1;// passing 1 for testing.

          $accounts = $this->entityTypeManager->getStorage('user')->loadByProperties(array('uid' => $uid, 'status' => 1));
          $account = reset($accounts);
          if ($account) {
              return $this->entityTypeManager->getStorage('user')->load($uid);
          }
      }
      return [];
  }

My doubt here is "$this->entityTypeManager->getStorage" is getting data from cache table. Or everytime it connect to db and generate response?

load() and loadMultiple() are cached, loadByProperties() is a shortcut for an entity query + load, the entity query is not cached.

Do not use loadByProperties() if you know the entity ID.


Convert a regular autocomplete field into an autocomplete deluxe field? I am using the following code.

   $form['usershare'] = array(
     '#title' => t('Share Collection Internally - Example: Alice, Bob, Pat'),
     '#type' => 'textfield',
     '#default_value' => empty($flag->usershare) ? '' : $flag->usershare,
     '#autocomplete_path' => 'user/autocomplete/fl',
     '#multiple' => TRUE,
   );

I installed the Autocomplete Deluxe module.

How do I convert the code I am using to have a form field that uses autocomplete deluxe?

I tried changing the form field type to autocomplete_deluxe, but that didn't work as only a blank input box shows up.

As per the README.txt file, something like this should work

   $form['field_term_ref_tid'] = array(
     '#type' => 'autocomplete_deluxe',
     '#autocomplete_deluxe_path' => url(
       'autocomplete_deluxe/taxonomy/field_term_ref',
       array('absolute' => TRUE)
     ),
     '#multiple' => TRUE,
     '#autocomplete_min_length' => 0,
     '#autocomplete_multiple_delimiter' => ',',
     '#not_found_message' => "The term '@term' will be added.",
   );


Incompatible Mail System setting detected In order to get the Newsletter (Simplenews module) to send out emails correctly (in HTML format) I selected HTMLMailSYstem in the mail system settings. Having the DefaultMailSystem setting instead, does not work, in a sense that it only sends out plaintext newsletters, not html.

The status report however is giving me the following error:

Printer, email and PDF versions - Send by email
Incompatible Mail System setting detected
The send by email module requires the use of the DefaultMailSystem, please configure it in the Mail System Settings page.

Is it possible to have different mail system settings for different modules? Or is there another way for me to make this work?

SMTP Authentication Support module works best with the Print module. I has an option allow sending mail in HTML format.

  This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.


Getting WSOD, can't view any errors even after editing index.php I've tried entering:

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

at the beginning of my index.php file (after begin php tag and it hasn't done anything.  When I run cron, it comes back and tells me that everything is ok.

Here's a brief overview of things that have transpired today:

I updated my views modules and made a database backup (i have no idea
how to restore from this, btw)
I updated to core .24
I ran cron andfixed errors concerning .htaccess files. I followed this tutorial:
https://drupal.org/SA-CORE-2013-003
I turned off error reporting (cause it's a production server: www.jcoledesign.com is the address)
All hell broke loose.  At first it stopped loading some images, then it stopped loading all CSS, this is likely due to caching
I added the above code to my index.php file
I cleared cache, went back and tried to replace my .htdocs files with something more simplistic and still no go.

I'm running out of ideas and nothing I try from here or google seems to work.

Please help and thanks in advance!

I figured it out!

The .htaccess file in sites/defaults/files/  CAN NOT include Deny from all

The tutorial I referenced earlier mentioned that /temp/.htaccess should have this included, but it didn't say that if you included it in other files that it would crash your site.

As a side note: It would be great if there was a basic tutorial out there for .htaccess files so that I can get an understanding of everything that's going on here without having to spend months/years learning everything else associated with hosting a drupal website completely inside and out.


Deny node access depending on field value I'm trying to restrict the access to nodes of type article depending on a field value of the node. When I implement hook_node_access() it seems to have no effect on the node.

Even if I try to restrict the whole access it seems to have no effect.

function mymodule_node_access($node, $op, $account) {
  $type = $node->getType();
  if ($type == 'article') {
    return AccessResult::isForbidden;
  }
}

What's my mistake?

With what user do you check the access, as stated in the docs

  The administrative account (user ID #1) always passes any access
  check, so this hook is not called in that case. Users with the "bypass
  node access" permission may always view and edit content through the
  administrative interface.

user 1 will always have access ..

Make sure to check with an anonymous or regular user.


How do I limit the number of nodes posted by a user to an entity referenced node? I have created a content type (Reviews). I am referencing another content type (Books) using the Entity Reference module. How do I limit the number of reviews posted per book to 1 per user? Is there a module for this?

I have already experimented with the node_limit module but that doesn't work in this particular context. It restricts the user from posting content per content-type but not per node.

I don't think there is a module for that ("yet", may be). However, this can be done easily with a form alter hook and validation.

<?php
function MYMODULE_form_node_form_alter(&$form, &$form_state) {
  if ($form['#node']->type == 'article') {
    $validate = TRUE;
  }
  // You can also use field existence like following:
  if (isset($form['field_name_that_you_want_to_validate'])) {
    $validate = TRUE;
  }

  if (!empty($validate = TRUE;)) {
    $form['#validate'][] = 'MYMODULE_node_validate_only_one_review';
    form_load_include($form_state, 'inc', 'MYMODULE', 'FILE_THAT_CONTAINS_THE_VALIDATE_FUNCTION');
  }
}
?>

Then, define the validate function:

<?php
function MYMODULE_node_validate_only_one_review($form, &$form_state) {
  if (!empty($form_state['field_name_that_you_want_to_validate'])) {
    $nids = array();
    foreach ($form_state['field_name_that_you_want_to_validate'] as $language => $items) {
      foreach ($items as $delta => $item) {
        if (!empty($item['target_id'])) {
          $nids[$item['target_id']] = array($language, $delta);
        }
      }
    }
    if (!empty($nids)) {
      $query = new EntityFieldQuery();
      $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'article')
        ->propertyCondition('uid', $GLOBALS['user']->uid)
        ->fieldCondition('field_name_that_you_want_to_validate', 'target_id', $nids);

      $matches = $query->execute();
      if (isset($matches['node'])) {
        foreach ($nids as $nid => $pack) {
          if (isset($matches['node'][$nid])) {
            list($language, $delta) = $pack;
            form_set_error('field_name_that_you_want_to_validate][' . $language . '][' . $delta,
              t('You have already submitted a review for this content.');
            );
          }
        }
      }
    }
  }
}
?>

There are 4 assumptions:

Node type is article. Change all instances of article with the correct node type machine name.
Your field name is field_name_that_you_want_to_validate. Change it accordingly.
You are using Entity Reference module for node reference (hence, the target_id key. It would be nid if you use References module)
This bounty gave you the hat ;)

There is 1 fact:

I submitted this answer for the hat.

There is 1 hope:

I will get that hat.


In hook_form_alter(), how can I access the entity that is being flagged? In hook_form_alter(), I want to load the entity being flagged so that I can do some processing based on the field values of that entity.
However, I can't find an entity object using kint($form).  I know it must be there somewhere because the flag is correctly attached to the entity.
function MYMODULE_form_flagging_MYFLAG_add_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  kint($form);
  kint($form_state);
  // Where is the flagged entity object id?
}

On the flagging object, after the flagged has been saved, the entity id can be accessed like this:
    $flagged_entity_id = $flagging->get('entity_id')->value;

However, in hook_form_alter(), when the flag has not yet been saved for the first time, I can't find the entity_id in $form.
I thought it might be in $form_state, but I got a NULL result for $form_state->get('entity_id').

Ok, thanks to leymannx and No Sssweat, I think I finally understand how to get the entity from a form.
To get the entity being flagged inside a flag, this is what I had to do:
function MYMODULE_form_flagging_MYFLAG_add_form_alter(&$form, FormStateInterface $form_state, $form_id) {
      $flagging_entity = $form_state->getFormObject()->getEntity();
      $flagged_entity_id = $flagging_entity->get('entity_id')->value;
}


dynamic flter with views Is it possible to display dynamic result based on the URL, with the Views module?

I have a database table with thousand messages, and I would display those containing the words in the URL. For example, with test.com/variableparent/variableschild, it should display the text containing the  variables_child variable.

I tried with the filter, but I have to put a specific word, not a dynamic one.

You can do this using Views Argument Substitutions and I'm just assuming the Title field here. It should work for any text field.

Add some Global: Null contextual filters to take each raw component of the url. (Provide default: Raw Value from URL 2 / 3 / 4 etc.
In your views filters, add Title: Contains: ***!1***. Repeat this for however many url components there are. ***!2*** ***!3*** etc. for each Title filter.
Use AND / OR in between your Title filters section to control your final result.


How I change my Site URI in Drupal 8 In Drupal 7 I put in settings.php this:

$base_url = 'http://mysite.local';

And when I run:

$ drush uli
http://mysite.local/user/reset/1/1460387746/mTqwCdJ7hi_pmrPRuFOScYwFtoHTmVAW07MV23O3UVk/login

The url generated will be fine.

In Drupal 8 I check and still there.

But in my Drupal 8 site, when I try run:
$ drush uli

I got:

mysite does not appear to be a resolvable hostname or IP, not starting browser. You may need to use the --uri option in your command or site alias to indicate the correct URL of this site.                          [warning]
http://mysite/user/reset/1/1460387905/ntObZiBxAnYdgGoc9jLqCIeQYpN_WjO04UlXcfSNZMo

I know I can do this:
$ drush uli --uri='mysite.local'

But much work.

Too I can do this with some drush config.

Then, how I do this like Drupal 7 in settings.php?

Since Drupal 8 uses Symfony's request stack which generates the base url, some things are not possible to do in the same manner as was possible in Drupal 7.
Instead create sites/default/drushrc.php and add
<?php

$options['uri'] = 'http://mysite.local';

and you should be fine.


Facebook Friend List Import using fboauth I am using fboauth for enabling login with facebook for the website. Here is an overview of how I achieve the functionality:

When the user clicks on the facebook login button on the website, he or she is taken to a facebook login page. After logging in with facebook, the user is taken to the app authorization page where the user asks for permission to connect with the app. Once necessary permissions are granted, a local account (account at my website) is automatically created for the user and the user is brought back to a welcome page to set password. The user won't even have to verify their email address. On subsequent visits, when the user clicks on the login link, he/she is taken to the same facebook login page where they supply their login credentials. On successful login, they are brought back to the website. So far, everything works fine with the fboauth module.

What I am trying to achieve now is a functionality similar to what is found with the fbconnect module. The user is provided with a block/page where the user can import the list of his friends who has authorized with the app, and see the links to their local accounts (accounts at the website). How to achieve this functionality? The fboauth module has its own API which can be utilized. Here is what I already have, written using the API of fboauth.

<?php
function mymodule_fboauth_actions() {
  $actions['mymodule_friend_import'] = array(
    'title' => t('Imports your friends),
   'callback' => 'mymodule_fboauth_action_friend_import',
    'permissions' => array(
      'user_friends',
    ),
);
  return $actions;
}
function mymodule_fboauth_action_friend_import($app_id, $access_token) {
$result = fboauth_graph_query('me/friends?fields=name', $access_token);
drupal_set_message(t('Import complete!'));
}
?>

This will import all the friends of a user as an object into $result. However, what I am finding it difficult is to display those names with the user's corresponding local accounts (accounts at the website). This is because of my lack of knowledge in php. What I am looking for is here is the exact lines of code that can be inserted after $result recieves its value so that the names of the users are displayed along with the links to their profile pages at my website.

The code you have there is returning friend's names which could be problematic if any of the user's friends have the same name (names like John Smith and Mohammed Abdul spring to mind).

You should change your friend import function to get the facebook user id like this:

function mymodule_fboauth_action_friend_import($app_id, $access_token) {
  $result = fboauth_graph_query('me/friends?fields=id', $access_token);
  drupal_set_message(t('Import complete!'));
}

As you rightly pointed out fboauth has a useful API including this method which turns facebook user ids into Drupal user ids:

/**
 * Load a Drupal User ID given a Facebook ID.
 */
function fboauth_uid_load($fbid) {
  $result = db_query("SELECT uid FROM {fboauth_users} WHERE fbid = :fbid", array(':fbid' => $fbid));
  $uid = $result->fetchField();
  return $uid ? (int) $uid : FALSE;
}

To make an array of Drupal user profiles you could write this in your code:

$accounts = array();
foreach($result->data as $fbuid){
  $accounts[] = user_load(fboauth_uid_load($fbuid->id));
}

How you then use those profiles depends on where you want to display them, but something like this should do the trick:

foreach($accounts as $account){
  print l($account->name, 'user/'.$account->uid);
}

If you put it all together you will have something like this - you may need to adjust some of the specifics as I do not know how you wish the information to be displayed:

<?php
function mymodule_fboauth_actions() {
  $actions['mymodule_friend_import'] = array(
    'title' => t('Imports your friends'),
    'callback' => 'mymodule_fboauth_action_friend_import',
    'arguments' => array)
      'app_id' => MISSING,
      'access_token' => MISSING,
    ),
    'permissions' => array(
      'user_friends',
    ),
);
  return $actions;
}

function mymodule_fboauth_action_friend_import($app_id, $access_token) {
  $result = fboauth_graph_query('me/friends?fields=id', $access_token);
  drupal_set_message(t('Import complete!'));

  $accounts = array();
  foreach($result->data as $fbuid){
    $accounts[] = user_load(fboauth_uid_load($fbuid->id));
  }

  foreach($accounts as $account){
    print l($account->name, 'user/'.$account->uid);
  }
}

If this doesn't display anything that means print is the wrong function to use in this context.  How you get the items to display depends entirely on where and how you are calling this function.  If it's part of a hook such as hook_node_view() you can edit the node entity before it is rendered, but if (as I suspect) this function is being run in the background without refreshing the screen you will likely have to employ some JQuery or AJAX to get the relevant items to display.

I would start with this post on Javascript and JQuery for an explanation of how Drupal uses JQuery, and this post on building AJAX into non-form elements in Drupal.


Sanitizing strings before adding as taxonomy term I am programatically creating taxonomy terms from a JSON object. I have a simple script that iterates over the converted JSON, and creates a taxonomy hierarchy. Since these terms come from a client-generated CSV they have random spaces and characters in them I want to sanitize/normalize them before I add them using taxonomy_vocabulary_save()

I've looked at the list of drupal Sanitization Functions, but those all seem to deal with HTML/JS strings. Is there a drupal way for me to format these strings, or should I just use a PHP regex to do it?

Running the text through check_plain() will sanitize anything dangerous, giving you the same result you'd get if you were to input the same title as part of the normal 'create term' process via Drupal's UI. I'd also run it through trim() to get rid of preceding/trailing whitespace. Beyond that, yes, you might need to do some custom regex to clean up things in your data, but that's impossible to say without seeing your data.


create double view with same url alias for different theme In my drupal. I created a two theme one for desktop and another for mobile using Mobile switch I change the theme. Now I Created a View as a page for desktop with alias "xxx/yyy" and for mobile also I created a view as a page with same alias "xxx/yyy"(some modification Done). While switching the theme from desktop to mobile, the desktop view is appear. How to differentiate?

ok

create a menu with hook_menu
then with checking condition you want load your views in callback of your menu

Something like below

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items['myurl'] = array(
    'title' => 'title',
    'page callback' => 'myfunction_callbackfuction',
    'access callback' => TRUE,
  );

  return $items;
}

function myfunction_callbackfuction() {
  $view = views_get_view('view_name');
if($mycondtion)
  $view->set_display('page1');
else
  $view->set_display('page2');

  $view->pre_execute();
  $view->execute();
  print $view->render();
}


How to execute javascript within drupal for a specific field on a specific page? The Initil question
I have a input field which should activate a function on the onfocus javascript event on a field on the user page.

Step 1
Add code to a custom module:

(function ($) {
  $(document).ready(totalname(){
    document.getElementById("fullname").style.background = "yellow";
  });
})(jQuery);

The currently HTML is:

<input type="text" id="fullname">

And it should become like this:

<input type="text" id="fullname" onfocus="totalname()">

How to get the onfocus=... inside the input element?
Is the custom code ok?

Addition to this question.

Thxs you so much for all the comments. Based on that I learned i few things more so I now understand what the real question should be.

To understand how I can executed javascript code in a certain field on a certain page in drupal.

I assumed this was needed by a callback but this is not encoured according to @Jimmy so I'm trying to understand the way it should be according to drupal standards. Also I was suprised that no change in HTML was needed as @Adrian gave an example. I could not get it run because of the typo :-( So in mean time I made another solution.

The  script is basicly just a real time concatination of first, middle and last name into a fullname field.

(function ($) {
  $(document).ready(function(){

        function setFullName() {
            var nameParts = [document.getElementById("edit-field-voornaam-und-0-value").value,
                             document.getElementById("edit-field-tussenvoegsel-und-0-value").value,
                             document.getElementById("edit-field-achternaam-und-0-value").value],
                name = nameParts.join(" ").trim();

            document.getElementById("edit-field-naam-und-0-value").value = name;
        }

        var fields = [document.getElementById('edit-field-voornaam-und-0-value'),
                      document.getElementById('edit-field-tussenvoegsel-und-0-value'),
                      document.getElementById('edit-field-achternaam-und-0-value')];

        for (var i = 0; i < fields.length; i++) {
            fields[i].addEventListener("keyup", setFullName);
        }

  });
})(jQuery);

So this is working and I put it in a custom module.

I still do not understand how I should be if I rewrite the code following the example of @adrian as this code is still executed on every page and not a specific page.

Thank you for learning !! and not using the correct words. I'm not native english ...

Your jQuery:

//Making a focus over the element
(function ($) {
    $('#fullname').blur(function() {
        $(this).removeClass("color");
      })
      .focus(function() {
        $(this).addClass("color");
      });
})(jQuery);

Your HTML:

<input type="text" id="fullname"><br>

Your CSS:

.color {
  background-color : yellow;
}

EDIT:
To attach the js code to your page you can use #attached in a renderable array (this is the recommended way). I think that you should read: How to add jQuery UI libraries to a page.


Is there any security or operational problems if I do not have any .htaccess file in drupal root? I realise that having the .htaccess file in the root of my installation is probably the way the program is designed to run, but I was having some difficulties accessing the site, and then fixed the problem by deleting the .htaccess file in the root. But then it made me wonder if this was a good idea to leave my Drupal 7 installation without a .htaccess file in the root at all.

Is there any security or operational problems if I do not have any .htaccess file in drupal root? I imagine that I would have to put it back in order to enable clean URLs.

You may have some problems, depending on how Apache is configured.

People may be able to browse directly to some hidden files.  Look at lines 6 and 73 in the .htaccess to see what it restricts.

People may be able to browse directories directly.  See line 10.

The site may not work right if you accidentally put a file called index.html in the root.  Line 20 makes index.php the primary file.

Clean URLs won't work.  I am not 100% sure if image cache will, either.

There may be some PHP security issue, but the php_flag directives have been standard settings in php.ini for a several years now.

Are you on shared hosting?  If so, the problem with the .htaccess could be the Options lines.  Some hosts restrict these.  Everything else should be feature checked the the <IfModule> directives.

It is possible to not have a .htaccess in the DOCROOT by placing the contents into the Apache config for the site, or in an include.  On high volume sites, there are some performance gains from doing this (.htaccess is read each request, where Apache config is read once when it starts).


Can relationships be used to show Content and linked content in the same view I'm trying to display content in a view and, beneath each entry, show a teaser of other content to which it is linked via Node Reference.

Here is roughly what I'm trying to show in my View:

Classroom A (title with link)
  L Teacher A (teaser)
  L Teacher B (teaser)

Classroom B (title with link)
  L Teacher B (teaser)
  L Teacher C (teaser)
  L Teacher D (teaser)

I've tried using Relationships and Contextual filters, but find them quite confusing and unintuitive.

The best I've managed is showing the same Classroom A link multiple times, one for each Teacher...

create a view filtering by classroom node types
add a relationship like "Entity Reference: Referencing entity", it is related to teacher nodes that are referencing the classroom node.
after this, add the classroom node fields and using that relationship, add the teachers fields.
in the format views settings, you can choose a field to grouping this nodes, so, choose the node reference field.

This view configuration, it will works only if the node reference field is in teacher node.


Plans for a D7 version of the Spam module, and possible alternatives? I am thinking about porting an existing D6 site to Drupal 7. The main shortcoming that I see is that the splendid Spam module is still missing for Drupal 7.

I don't want to relay on third-party services, so I wonder whether there is any plan to port the Spam module to Drupal 7 and if not, what alternative spam filter can be used for Drupal 7.

I think you were looking for an antispam module, weren't you? Try Mollom.

It kills comment, contact form and registration form spam, has image and audio CAPTCHA service.

Try it, it is made by Drupal core developers.


I'm trying to get all duplicate rows using db_select Before I run db_delete, I'm trying to run db_select to test that I am getting all duplicate rows, based on a specific column value.

db_select('node_revision', 'n')
    ->where('n.nid NOT IN SELECT MIN(n.nid)')
    ->groupBy('hash')
    ->execute()
    ->fetchAll();

Basically, delete (select for the test) all rows with the same hash value, except for the first one, is my goal.

I'm basing it on this page:

http://blog.sqlauthority.com/2007/03/01/sql-server-delete-duplicate-records-rows/

But for some reason I get the following error:

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM node_revision n WHERE (n.nid NOT IN SELECT MIN(nid)) GROUP BY hash' at line 1: SELECT FROM {node_revision} n WHERE (n.nid NOT IN SELECT MIN(nid)) GROUP BY hash; Array ( ) in include()

What am I doing wrong? Why is ; array ( ) there?

At the moment your query is:

SELECT
FROM
{node_revision} n
WHERE  (n.nid NOT IN SELECT MIN(n.nid))
GROUP BY hash

You need to add some fields...

db_select('node_revision', 'n')
  ->fields('n', array('vid'))
  ->where('n.nid NOT IN SELECT MIN(n.nid)')
  ->groupBy('hash')
  ->execute()
  ->fetchAll();


How to get a fixed picture in the field without affect by responsive effect? I want to get this picture fixed on original size. Please refer to this picture. There is a picture showing up a drill. I want to make it keep on 100x59px. When I adjust the browser's window, the responsive effect is that I want but the picture will shrink its width. Here is the webpage. I also use this command:grep -inR image-style-cu-product-list /mydrupalcssdirectory. I can't figure out why I did't get this specific CSS? Are there any methods to keep this picture fixed on 100x59px. (At least I want the width able to be fixed.) The solving method is not limit in CSS. Wish a help. Thanks.

Tables are by definition "responsive" (quotes intended), meaning they will give more space to the more "filled" cell. You need to tell the browser to reserve a certain amount of space for the cell with the following css:

.views-field-uc-product-image {
  min-width: 110px;
  max-width: 110px;
}

The extra 10 pixels are to account for the padding around the image. The max-width: 110px is added to ensure the cell will also not take more space then needed.


Unable to Retrieve Custom Taxonomy Fields Using PHP I have added a custom image field to a Drupal 7 taxonomy called "field_uc_catalog_image2".

I am now attempting to get the path of that field using PHP with this code:

$normal_path= drupal_get_normal_path($_GET['q']);
$tid = array_pop(explode('/', $normal_path ));
if ( is_numeric( $tid ) ) {
  $term = taxonomy_term_load($tid);
  print $term->field_uc_catalog_image2['und'][0]['uri'] . '
';
}

However, I am getting the following error:

  Notice: Undefined index: und in eval() (line 6 of C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\le\modules\php\php.module(80) : eval()'d code).

Whereas, this similar expression for the standard image works fine:

print $term->uc_catalog_image['und'][0]['uri'] . '
';

Do you have any suggestion?

Using print_r($term) (as per Mohammad's suggest) I could see the correct expression was actually another one.

$term->field_image['und'][0]['uri']


Contact form block with data from the page the blocks featured on So I have a content type "Real Estate." On the view for a "Real Estate" node, I want to have a contact block in the right side bar that has a feild for the node id of this specific "Real Estate" node.

An example of the feature I'm trying to make can be seen here

This problem has two parts which I'm not sure how to do. The first is that I don't know how to make a block for a contact form. I know drupal has a default Contact module but I'm not sure how to turn this into a block or even if that is the best way to go (maybe WebForms module can help?) Second is that I'm not sure how to pre-load the node id into the form. I'm sure that this would require a hook of some kind but seeing as I don't know how to make the contact form block, I don't know what hook to use.

Any help would be much appreciated. Thanks!

If you don't want to write custom theming and you want less coding, you need to create a custom page with 2 columns using panels module.

Install the panels and ctools modules if you don't have.
Enable Chaos tools, Page manager and Panels.
Create a custom page at admin/structure/pages/add with the path "estate/%node" which will be a new mirror page of the existing path "node/%node".
Assign Node: ID context to the argument %node.
Choose two column layout.
Add Existing node to the left column. To use a NID from the URL, use %1 in the title box.
For the right column, add the contact form from Widgets.

To get node information in the contact form, you need to write a hook hook_form_FORM_ID_alter in your custom module using the argument NID.
You can study custom moduling here.
Here is the example code snippet.

<?php
/**
 * Implementation of hook_form_alter().
 * @see http://api.drupal.org/api/function/hook_form_alter
 */
function yourmodule_form_contact_mail_page_alter(&$form, &$form_state, $form_id) {

    if(arg(0) == 'estate' && is_numeric(arg(1)){
        $node = node_load(arg(1));
    }

}
?>

You can also see how can you customize the contact form here:
http://www.metaltoad.com/blog/how-add-field-drupal-contact-form
http://www.isegura.es/blog/modifying-contact-form-drupal-how-add-field
http://www.pensamientosdivergentes.net/blog/modifying-contact-form-drupal-how-add-field

The drawback of this solution is you have to use the new path "estate/%node" to the node view page instead of using the default existing path "node/%node".
Any better answer is welcome.


Command "generate-votes" is not defined I'd like to use Drush 10.3.6 to generate votes on my development server.
Based on these instructions for a previous Drush version (8.x), there is some kind of module/extension for this.
drush generate-votes

However, when I try it, it doesn't work for me. The error message I get is the following one.

Command "generate-votes" is not defined.

Has this feature been removed or deprecated? Is there any other way I can generate votes from the command line?

This command doesn't come from Drush core but from the Voting API module. This command simply doesn't exist yet in the currently latest Voting API release: 8.x-3.0-beta2.  See, the directory /src/Commands where Drush commands since Drush version 9 get registered now simply isn't there yet.
You need to get the latest Voting API dev:
$ composer require 'drupal/votingapi:3.x-dev@dev'

There the /src/Commands directory contains a VotingApiCommands.php file with all the commands in it. The module needs to be enabled to use them, of course.

Voting API version 3.0-beta2 only contains the legacy votingapi.drush.inc file for Drush commands up to Drush version 8.


Calling a class defined from another module I am calling the method defined in a class implemented from another module using the following code.

use Drupal\module_name\MyClassName;

$instance = Drupal\module_name\MyClassName::getinstance($host, $user, $pass);

My code doesn't work, as I get an error about a class not found. What am I doing wrong?

The class is contained in module/src/controiller/controller_name.php.

In your comment, you say the class is inside module/src/controiller/controller_name.php, but you refer to the class as Drupal\module_name\MyClassName. That is wrong.
Assuming module_name is the directory containing your module (and the short name of the module itself), and that module_name/src/Controller/controller_name.php is the file containing the class definition, you need to use the following code.

use \Drupal\module_name\Controller\MyClassName;

$instance = MyClassName::getinstance($host, $user, $pass);

That is evident in any file referring a class, for example user.routing.yml.

user.logout:
  path: '/user/logout'
  defaults:
    _controller: '\Drupal\user\Controller\UserController::logout'
  requirements:
    _user_is_logged_in: 'TRUE'

As you notice, the class is referenced as \Drupal\user\Controller\UserController, not \Drupal\user\UserController.

Also, the filename is generally the name of the class plus the php extension, so in your case the file name should be module_name/src/Controller/MyClassName.php, not module_name/src/Controller/controller_name.php.

As side note, if you are calling a static method for a controller class, you probably need to do something more than just invoking it. Normally, controllers get also the dependency injection container; without that, they would not work. See for example UserController::create().

public static function create(ContainerInterface $container) {
  return new static(
  $container->get('date.formatter'),
  $container->get('entity.manager')->getStorage('user'),
  $container->get('user.data')
  );
}

If you call controller a class that is not a controller class as Drupal defines that, then your code could work; differently, if you are calling a Drupal controller class, resolved the error about a class not found, you will get more errors to fix.


Custom HTML link is not working I have used a custom html link More search results   to link to the homepage.
When clicking the link,I am taken to this urlhttp://localhost/homepage instead of the correct one localhost/cars/homepage
What am I doing wrong?
thanks

Your site is installed in the /cars folder, but you're pointing to the root of the server by using the forward slash at the front of your HREF. You should use Drupal's l() function to generate a proper link:

<?php echo l(t('Homepage'), 'homepage'); ?>


About drupal_realpath() and PDF Formatter The PDF Formatter module uses pdftohtml to transform PDF to HTML, and show information.

Changing the module code, it is possible to show images too, but the path used for the image in the HTML markup is wrong.

What can I do to fix it?

The code used by the module is the following.

// PDF to html formatter
case 'file_pdf_to_html_formatter':
  $pdftohtml_installed = pdf_formatter_pdftohtml_installed();
  foreach ($items as $delta => $item) {
    $html = '';
      $html = shell_exec('pdftohtml -q -stdout '.escapeshellarg(drupal_realpath($item['uri'])));
      // pdftohtml tends to generate too many non break spaces,
      // replace them with standard spaces
      $html = str_replace('&nbsp;',' ',$html);

      // pdftohtml generates a complete HTML file.
      // Drupal only waits for contents between the body tag
      $html = preg_replace('/.*<BODY[^>]*>(.*)<\/BODY>.*/si', '\\1', $html);
    }

    $element[$delta] = array('#markup' => $html);
  }
  break;

The output I get is the following.

<img src="/var/www/html/drupal/sites/default/files/imgtest.jpg" />

To get the web-accessible URL for a local file, you should use file_create_url().

$html = shell_exec('pdftohtml -q -stdout '.escapeshellarg(file_create_url($item['uri'])));

Using it would probably not work, anyway: I think that pdftohtml first tries to access the local file to see if it is a PDF file, and it outputs what you see when the file is an image. I doubt that pdftohtml uses <img /> for every file that is not a PDF file or that is not able to access.
In your case, file_create_url('public://imgtest.jpg') would return $base_url/sites/default/files/imgtest.jpg where $base_url is the content of the global $base_url, which includes the http:// or https:// part. While that would be perfect to be used for the <img /> tag, it could not be used as filename, since pdftohtml is not probably able to handle a filename starting with http:// or https://. (In other words, it expects the filename of a local file.)

It is probably easier to check if the file is an image, and output the <img> tag using the output of file_create_url() as image URL in that case, or the output from pdftohtml when it is not an image.


Add comment with Inline Entity Form while adding content I'm creating a content type. and want to add comment for the same content on same form of add content.

I've installed Entity Reference, and selected Entity reference as Field type & selected Inline entity form - multiple values as the widget. I've chosen Selected Target type Comment under FIELD SETTINGS and I'm still not getting the comment section on content addition form.

Why is it not showing? Is there another way to show comment on content addition form?

Inline Entity Form doesn't support Comment forms out of the box.

Part of the process of building the IEF widget is a call to inline_entity_form_get_controller() which will retrieve a controller class from the entity metadata. As you can see in IEF's hook_entity_info_alter() invocation, it only adds this controller metadata for node, taxonomy, commerce product, & commerce line item entities.

Theoretically, you could build your own custom module that could:

Invoke hook_entity_info_alter() to add support for comment entities.
Build your own custom class that extends EntityInlineEntityFormController(e.g. CommentInlineEntityFormController) to be evoked for form processing.

Keep in mind this is an unusual use case, a comment entity is predicated on a its parent entity pre-existing before it's created; you're likely to run against logic that might prevent this (e.g. database integrity checks) .

It might be easier just to create your own custom node type entity that's configured just to appear like comments on your nodes.


Programmatically set property based on other properties in a custom entity I created a custom entity and want to programmatically set the title based on 2 other properties.

For example, the entity has year and state properties. When the entity is created, I want to populate the title property with year state.

How can I achieve this?

For a custom entity type, you can override EntityStorage::doPreSave() in your entity class:

function doPreSave(EntityInterface $entity) {
  parent::doPreSave();

  // Perform field manipulation here.

  return $entity->id();
}


How to add a top nav bar? I would like to add a Facebook style or StackExchange style top navbar to my site. It should show the username, mini profile pix, userpoints, search box and a few other links.

Is there a module for that?

I don't find any module does that specific purpose of making top bar.
It is usually done by custom themeing. Basically, you add a new region to your theme.
For example, You define a new region called "topnav" in .info;  code the markup in template.php and .css files. Then go to block administration page, assign stuffs to the topnav region.


Can I write MySQL settings in drupal settings.php file? I am using Drupal 7 and i am getting MySQL server has gone away error in my current site.
By doing Google i figured out that i need to increase some of the parameters of my.ini file

key_buffer
max_allowed_packet
table_cache
sort_buffer_size

Is there any way that I can write this in Drupals settings.php?

No, those need to be set in your MySQL server's my.ini/my.cnf file.

Those settings can't be changed on the fly from any process (PHP, Apache, even MySQL itself), you need to set them in the .ini/.cnf file and then restart the MySQL server for the changes to take effect.


My subtheme css is overriden by the parent theme. How to I reverse this? I have created a subtheme and for some reason the css I add in there to override the parent theme doesn't work. THe parent theme's css seems to be prioritized over my new stuff. Is there any way of weighting themes or ordering loading of themes?

I'm encountering the same issue.  If I disable the css aggregation I can see that the reason is that my sub-theme's css stylesheet is being @imported before the one(s) from the base theme, which means, of course, that the base theme's styles are overriding mine anywhere where I use the same selectors.  Which is crazy.  How is this not a problem for more people?  Is there something we're missing here?

Edit: sure, I can use !important, which is what I'm doing as a workaround (and presumably the OP @Nigel Waters could do the same?), but doesn't this rather defeat the purpose to some degree?


module to customization product in drupal commerce Is there any module to let my shop customers design their own t-shirt, mugs, caps, mouse pads. They can upload an image to t-shirt, back and front side, or select existing image from the logo categories, and they can also write their text on the template shirt.
and have below features

Features:

Upload an image on the template t-shirt.
List item
Change t-shirt side, front or back.
Select an Image from the existing logo categories, to put on the
template t-shirt
Write text on the template t-shirt
Up to 4 text lines - New
Change text size, color, font type

my shop is based on drupal commerce

anybody know  module to provide something like this features, or any idea that how can I implement it?

You are looking for Commerce Customizable Products

  Drupal Commerce allows you to sell customizable products that require
  customer input when added to the cart. Use cases for this
  functionality include:

Business cards that require contact information and a logo upload.
Event registrations that require attendee information.
Donations the allow the customer to specify a donation amount.

and especially for t-shirt design it is possible only through third party tools, we can integrate but it is not free, they have drupal support with their tool http://www.online-product-designer.com/online-advance-tshirt-design-tool.php and http://harboarts.com/shirtdesigner/


Omit the Front Page when Using Contextual Filters? Content on my site is set up via taxonomy term, and I've created a view using contextual filters which does a fabulous job of sorting all the content to the appropriate page.

However, on the front page we want to present that content differently, so I have created a block which presents anything marked "front" to appear inside it.

The two are mutually exclusive, as I have filtered the data so that ONLY front page stuff appears in the block, and NO front page items appear in the page view.

This is problematic, however, as some of these highlighted items should appear on other pages in the Web site.  Removing the 'exclude home' filter from the page view, however, makes the page view of items marked "front" appear beneath the block, which we don't want.

In order to get the content on the home page AND elsewhere content owners are required to enter the data twice -- unless I can get this fixed.

Any ideas?

Thanks!

First : NEVER enter data twice. You're sure you'll regret it sooner or later, and it's always the sign something's wrong with the design.

As for your problem, you could probably set up a Views Attachment or a plain other view to add nodes with different criteria.

Or perhaps you could use Flag or another module of that kind to differenciate your nodes more precisely ?


Output tabs and content in different regions? The default behaviour of Quicktabs is to make accessible a block containing the tabs and the linked content. That doesn't meet my requirements, unfortunately.

Is there any way of theming Quicktabs module (7.x-3.2) in such a way, that the tabs are output in one region (eg. right sidebar in page--nodetype.tpl.php) and the linked content is displayed in the main content region? Or is it stretching the concept of tabs too far?

I am also trying to achieve the same result. I found this patch for an older version of quicktabs that never really got off the ground I guess.

http://drupal.org/node/1085116

I think it would be an appropriate feature.

EDIT:

Using a few ideas from the patch above, I have come up with a quick mod that splits the block into two blocks for each tab instance. Just edit your quicktabs.module as follows.

Simply add a second block definition:

function quicktabs_block_info() {
  $blocks = array();
  foreach (quicktabs_load_multiple() as $qt_name => $quicktabs) {
    $blocks[$qt_name]['info'] = $quicktabs->title;
    $blocks[$qt_name . '_qt_content']['info'] = $quicktabs->title . ' - Content';
  }
  return $blocks;
}

Then alter the block_view function as such:

function quicktabs_block_view($delta = '') {
  $block = array();

  // Check if it is the content block or not
  substr($delta, -11) == '_qt_content' ? $content_tab = 1 : $content_tab = 0;
  if($content_tab) {
    $delta = substr($delta,0, strrpos($delta, '_qt_content'));
  }

  if ($qt = quicktabs_build_quicktabs($delta)) {
    if (isset($qt['content']) && !empty($qt['content'])) {
      $block['content'] = $qt['content'];
      $block['content']['#contextual_links']['quicktabs'] = array('admin/structure/quicktabs/manage', array($delta));
      $block['subject'] = check_plain($qt['#title']);
      // remove either the tabs or content depending on the block
      if($content_tab){
        unset($block['content']['content']['tabs']);
      }else{
        unset($block['content']['content']['container']);
      }
    }
  }
  return $block;
}

It isn't the most elegant mod, but it does the job with little changes. All you have to do is add the original block (tabs) and the new contant block to wherever you want.


Rollover image swapping as a field I'm learning Drupal and I'm trying to create a field where I can upload 2 images and let one face into the other while I mouse over/ hover / rollover it. Then I eventually plan to make it into a views like one in Zappos where the user can see alternate views on mouse over.

I've looked up the other thread and found the Rollover filter on Drupal but I still don't know how to make that work. I need it as a field of a node so that I can display a view of all the related nodes.

I would set it up as a single image field with two values and then use https://drupal.org/project/custom_formatters to create a custom formator for that field and do a display hide/show with css or jquery.


POST taxonomy item using Services module I want to POST a new taxonomy item. I'm using Postman in Chrome to test, I'm logged in fine, and I'm posting RAW JSON:

{
  "name": "building",
  "description": "",
  "vocabulary" : {
    "id" : 1,
    "resource" : "taxonomy_vocabulary",
    "uri" : "http://site/cms/taxonomy_vocabulary/1"
  }
}

And I just get this:

<?xml version="1.0" encoding="utf-8"?>
<result>Access denied for user anonymous</result>

Here is the JSON format to add taxonomy term. I've tested it and works perfect.

{
    "vid": "2",
    "name": "Term Name",
    "description": "your description"
}

Here vid: vocabulary ID

Make sure the current logged-in user has privileges to add taxonomy term. and make sure to add token in Headers like follows

name: X-CSRF-Token

value: your-token

To know your token access the following path

yourdomain/services/session/token


Rules Invoke Event doesn't work My aim is to trigger a rule via Ajax.

Until now I create a custom module called "iscrizione"

Here my iscrizione.rules.inc

function iscrizione_rules_event_info() {
$items = array();

$items['iscrizione_evento'] = array(
  'label' => 'Iscrizione all\'evento',
  'group' => t('Links'),
  'variables' => array(
    'path' => array(
      'type' => 'array',
      'label' => t('Path accessed'),
      'description' => t('The path which has just been accessed.'),
    ),
    'account' => array(
      'type' => 'user',
      'label' => t('updated user'),
    ),
  ),
);

return $items;
}

Here my iscrizione.module

function iscrizione_menu() {
$items = array();

$items['conferma/%'] = array(
'title' => 'Conferma Iscrizione',
'page callback' => 'iscrizione_evento',
'page arguments' => array(1),
'access arguments' => array('access content'),
);

return $items;
}

function iscrizione_evento($arg) {
echo $arg;
// rules_invoke_component('rules_stampa_messaggio', $arg);
rules_invoke_event('rules_iscrizione_iscrizione_evento', $arg);
}

I tried both functions (invoke event and component), but if I type the url I can see only the $arg printed.

No action was fired (as actions I put "
Show a message on the site" and a "Create entity")

Any help?

Within $items of your iscrizione_rules_event_info(), you used iscrizione_evento. So in your iscrizione.module you should refer to that. Try this variation of it:

function iscrizione_menu() {
$items = array();

$items['conferma/%'] = array(
'title' => 'Conferma Iscrizione',
'page callback' => 'iscrizione_evento',
'page arguments' => array(1),
'access arguments' => array('access content'),
);

return $items;
}

function iscrizione_evento($arg) {
echo $arg;
// rules_invoke_component('rules_stampa_messaggio', $arg);
rules_invoke_event('iscrizione_evento', $arg);
}

Maybe it would also help if you'd slightly adapt the readability of your code, by not using iscrizione_evento for different things. How about, eg, these variations of it:

menu_iscrizione_evento.
rules_event_iscrizione.


Is there a way to set the active menu's text as page title? I would like to set the active menu's text as the page title in drupal7. I tried using the page title module and found no replacement patterns to set the active menu as the page title. Any help is widely appreciated.

Thanks

I found the answer with this link http://sivaji.drupalgardens.com/how-set-custom-page-title-drupal-7.

There exists no way to dynamically set the active menu as the page title, but with the Classes_array from the vars, we can check the page's id and then set the page title as per our need.

In my case I used a if check to check the page id (Page-contact's page title to Contact) and so. It worked for me though, but still found no way to dynamically set the title from the active menu !


Drupal 7: How do I translate the content of a checkbox I created? I have a multilinugual site, content translation works. Now I added a content type and used the checkboxes/dario buttons field for a new field. How can I translate the content of such a field.

Let's say I put in gender male|Male female|Female now I have spanish and want the spanish text to be shown. How do I do that?

I found someone suggesting I had to use php fields, but I don't even see a php field there, although the module works in other places, besides even though I am a programmer this seems pretty complicated for the task.

You've got content translation enabled but have you installed and enabled the entity translation module as well? In Drupal 7, you need this to be able to translate each field / entity. I've used this guide (also referred from the entity translation project page) as a good step-by-step process on how to set this up.


Config entity form fails to load entity I have a custom config entity modelled closely on the example documentation and example module.  The example module works fine on my site, my code does not, and I can't see the difference.

What works

Show an empty list of config entities with an add button.
Add a config entity and check it exists via "drush cget".

What fails

In my edit settings form (extends EntityForm), $this->entity has null/default values exactly as if I were adding a new entry.  It does not load the actual entity. It does not perform validation (if I pass a URL /admin/config/content/rrssb/BADPARAM that doesn't map to an existing entity I still see a page, whereas if I do the same test with the example code, I get a 403 error).
In my listing page (extends ConfigEntityListBuilder), if an entity exists I get an error - for some reason the list builder fails to pass the id (machine name) from the entity when building the route.

  Symfony\Component\Routing\Exception\MissingMandatoryParametersException:
  Some mandatory parameters are missing ("button_set") to generate a URL for
  route "entity.rrssb_button_set.edit_form". in
  Drupal\Core\Routing\UrlGenerator->doGenerate() (line 180 of
  core/lib/Drupal/Core/Routing/UrlGenerator.php).

Details

/**
 * Defines the RRSSB button set entity.
 *
 * @ConfigEntityType(
 *   id = "rrssb_button_set",
 *   label = @Translation("RRSSB Button Set"),
 *   handlers = {
 *     "list_builder" = "Drupal\rrssb\RRSSBListBuilder",
 *     "form" = {
 *       "add" = "Drupal\rrssb\Form\RRSSBSettingsForm",
 *       "edit" = "Drupal\rrssb\Form\RRSSBSettingsForm",
 *       "delete" = "Drupal\rrssb\Form\RRSSBDeleteForm",
 *     }
 *   },
 *   config_prefix = "button_set",
 *   admin_permission = "administer rrssb",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label"
 *   },
 *   links = {
 *     "edit-form" = "/admin/config/content/rrssb/{button_set}",
 *     "delete-form" = "/admin/config/content/rrssb/{button_set}/delete",
 *     "collection" = "/admin/config/content/rrssb"
 *   }
 * )
 */

rrssb.routing.yml

entity.rrssb_button_set.collection:
  path: '/admin/config/content/rrssb'
  defaults:
    _entity_list: 'rrssb_button_set'
    _title: 'Ridiculously Responsive Social Sharing Buttons'
  requirements:
    _permission: 'administer rrssb'

entity.rrssb_button_set.add_form:
  path: '/admin/config/content/rrssb/add'
  defaults:
    _entity_form: 'rrssb_button_set.add'
    _title: 'Add RRSSB Button Set'
  requirements:
    _permission: 'administer rrssb'

entity.rrssb_button_set.edit_form:
  path: '/admin/config/content/rrssb/{button_set}'
  defaults:
    _entity_form: 'rrssb_button_set.edit'
    _title: 'Edit RRSSB Button Set'
  requirements:
    _permission: 'administer rrssb'

entity.rrssb_button_set.delete_form:
  path: '/admin/config/content/rrssb/{button_set}/delete'
  defaults:
    _entity_form: 'rrssb_button_set.delete'
    _title: 'Delete RRSSB Button Set'
  requirements:
    _permission: 'administer rrssb'

Help requested

Please can an expert suggest what I'm likely to be missing, or at least help me understand where to look?

In particular, what mechanism (Drupal class/code file) loads the config entry or generates a 403 if it is not found?

The relevant code in my own module spans several files, so I've not pasted it all here, but could upload specific snippets if asked.

Looks like the id key isn’t matching the router parameter defined in the routing file. It should be either button_set or rrssb_button_set, depending on which one is right. Get that fixed and clear the cache and it should work.


What is the best practice to upgrade Drupal core without breaking the Git repo and the production website I've got a Git repository in which all my code is in the master branch, and I was previously just ignoring all the Drupal files, so that I kept a strict separation between code that I wrote (or modified or might modify) and code that could be generated with Drush or whatever.

This seemed like a good strategy until I had to upgrade Drupal.  I realized I want to be able to roll back if things went poorly, and what better tool to use than Git to do that.   I thought to myself this would be the perfect situation for a feature branch, so I made a drupal-7.14 branch, gave it its own .gitignore to ignore all my code and settings files and pay attention to only files that are part of the Drupal install which I wouldn't be touching.  I did an upgrade by hand (download, unzip, untar, copy), sorting through borderline cases like robots.txt and .htaccess, and overwriting Drupal's .gitignore with my own.  I fixed some settings that worked with 7.14 but not with 7.15, to recover from a 500 error, and then everything seemed perfect.  I renamed the branch to drupal-7.15 and was about to go happily on my way.

Until I realized what I had inadvertently done:  files that were previously untracked by my master branch but left in the working directory were now removed from the working directory when I checked out master, since they were no longer untracked files!  D'oh!

If I merge the drupal-7.15 branch with master I'll lose the separation of code.

There's probably some way to convert a branch to a submodule.  Assuming that's possible, that might be the best strategy.  I knew before I did this that submodules were the "right" solution, but since I didn't realize the side effect of using branches for previously untracked files, I decided to cut corners and go that route.  (Also, all the approaches I've seen to using submodules with Drupal assume that you're starting a new project and Drupal will be the master branch.  It is undesirable to me to make someone else's code the master branch, and I already had a repo with a master branch.  This looked like it would be unnecessarily complicated just to do an upgrade.)

There may be some other solution that I haven't thought of.

How can I best recover from this with the fewest possible downsides?

UPDATE: This is in development (in a Linux VM on my laptop), and has not gone to production yet.  By the time we go to production I plan to have everything wrapped up in feature modules, but that's not in place yet.

UPDATE 2: Submodules may not work.  According to Pro Git, "Submodules allow you to keep a Git repository as a subdirectory of another Git repository".  Drupal doesn't provide any such a nice separation.  Instead of all Drupal code being in a subdirectory, the relationship is more or less inverted, but there's still no clean separation, since you may be editing your .htaccess and robots.txt, so your code and the Drupal repo are mixed together.  I'm looking for a workaround to this problem.

It seems from discussion above that your question isn't about fixing your git repo, but about maintaining a Drupal site in git, and how that works with core updates.

I think that standard practice is in fact keeping all files in your repository, including Drupal core. The separation of Drupal code from custom code seems like a nice idea, but I don't think it's necessary, and I don't see what advantages it gives you. It also seems to assume that you will never want to patch core (or have to do it as a part of your deploy), which, while it isn't best practice, is definitely something you want to be able to do if something breaks in production.
Keeping your commits nice and focused also helps to get this kind of separation.

The solution I've used is to keep all code in the same repository, put as much as possible in Features or other kinds of exports/code/configuration, and maintain a list of patches that need to be applied to out-of-the-box core and contrib.

When you update core, start in your dev environment:

Make sure working directory is clean
Dump latest database (drush sql-dump). Either make a commit with the dump or save it somewhere safe.
Update core (drush up drupal)
Commit all changes.
Check patches file. If any patches need to be applied, apply them, and make another commit
Run update.php if necessary (already done if you used drush for the update)
Test your dev site. If everything is fine, push code to production. Run drush updb on production.
If there's a problem and you need to revert, either revert or reset your repo (git reset --hard HEAD~2 should do it), or revert the two commits if you want to keep the history. Replace your database with the dump.

The database dump is necessary because you otherwise can't undo changes made to the database by updates. You can also do the updating in a branch, in which case reverting just means checking out master. It's slightly inadvisable if you're working on one dev site because you can't really switch back to master and keep working there in parallel because of the database.

Using this more simple git-side workflow will allow you to use git's full power when you need it without the complication of submodules, etc. If this doesn't seem adequate, could you explain why you need further separation of code?


Get the current ProductVariation from the formElement of a custom widget in the "Add to cart" form I've a custom field in my Order Item, i need the value of a field of my ProductVariation in the widget of my custom field.
Let's say that my Variation has a "remote ID" field, when i select one of the Variation in the Add to cart form, in my custom field i've to retrieve that ID and use it to do some things.
If i've only one Variation everything works great doing something like that:
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $purchased_entity = $items->getEntity()->getPurchasedEntity();

    $my_cusrom_id = $purchased_entity->get('my_variation_field')
      ->first()
      ->getValue()['value'];
  }

The only problem is that if I have multiple variations, when i chose one from the select, in this code always the first one is returned from the getPurchasedEntity method, and i see no informations in $form_state or $form of something that could be useful.
Is there a way to retrieve the selected variation from there? seems strange that's not possible...

At the moment i ended by getting the value directly from the $_POST, sounds a bit hacky but can't find another way to do that...


Open Atrium: Customizing user badge In the Default installation of Open Atrium, Under the navigation bar, on the right side you will see User Badge. For Anonymous user it shows Login text with link and for the authenticated user it shows Username text with image and link and sub menu shows Dashboard, Edit Profile & Logout (all with their associated links respectively).

I want to customize the user badge when user is logged in. I want to add/delete option under the drop-down. Is there any ways to do so?

check the hook

function hook_preprocess_oa_user_badge(&$vars) {
  if (user_access('YOUR PERMISSION')) {
    $vars['links']['#links']['YOUR BUNDLE'] = array(
      'title' => t('ITEM TITLE'),
      'href' => 'ITEM URL',
    );
  }
}


drush sqlq --file on remote server with local file Im trying to run run write a command where I can execute remote queries stored local.

I was trying:

drush @remote.master sqlq < src/sql/data.sql

but no luck, also tried the option --file=path/to/file but it's only for remote files :(

Any ideas?

you should try with other command:

drush sql-sync --source-dump=src/sql/data.sql --target-db-url=mysql://remoteusername:remotepass@remoteserver/remotedatabase


Why should we avoid theming forms with template files? The issue was raised in this question. Why not exploit the advantages that template files offer in the case of forms?

I can see no good reason for not using a template file to theme a form. As I stated in that question, the simple #prefix and #suffix tricks might not be enough, say if you wanted the entire form to be a table rather than div based. I've used drupal_render with a form element parameter in a template to draw the individual fields in the form, but make sure you call drupal_render without an argument at the end of the template to populate the rest of the form, such as the form hash etc. as it won't validate.


How to check which node should be posted on which domain? I am looking for a feature which should be able to check the node destination before save it in the database.
This will be used in multi site  Drupal set up.

And it must be work like if node 1 has already created in site1 and I want to save node 2 in site2 then it save the node with nid=2 in the site2's node table.

Which means the nid must continues its sequence regardless of domains. Here, database and codebase are same only tables are having different prefixes.

Consider using the Domain Access module. Here's an excerpt from its project page:

The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database.
The module uses Drupal's Node Access system to determine what content is available on each site in the network. Unlike other multi-domain modules for Drupal, the Domain Access module determines user access based on the active domain that the user is viewing, rather than which group or site the user belongs to.


How can I restore the security of an old site with a sql injection vulnerability which was probably exploited? Edit: Sorry, the question was marked as unclear. In a nutshell, there are two questions:

Does the code below indeed create an sql injection vector? (It seems clear that the answer is yes, even though I was unable to craft a successful attack on my current server architecture.)
Assuming someone successfully exploited that sql injection vector on the old server, what would I have to do to make sure that there are no leftover attack vectors? Would it be sufficient, for example, if I took the following actions:

Move to a new server
Build a new Drupal codebase from scratch
Remove the insecure code from the theme
Block or delete all users except those that are recognized
Force password resets for the recognized users
Check the menu_router table for bad items
Check all node and comment titles, bodies and fields for  tags

...Or is the situation even more hopeless than that, and the site should simply be abandoned or rebuilt from scratch? For various reasons I don't think it is possible to restore from a backup, mostly because the attempted exploits go back 6 years.

=== Original post ===

I'm looking at an old D6 site that was done in a very non-standard way. What concerns me most are some .tpl.php files from the theme that use $_POST parameters to insert data into some tables, e.g.:

<?php
  $uid = $user->uid;
  $name = $user->name;
  $title=$_POST['title'];
  $comment=$_POST['comment'];
  $nid=$_POST['nid'];
  $cid=db_result(db_query("select  max(cid) from  comments"));
  $cid2=$cid+1;
  $timestamp=mktime();
  db_query("insert  into  comments  values($cid2, 0, $nid,$uid,'$title' , '$comment', '127.0.0.1', $timestamp, 0, 3,'01/', '$name', null, null)");
 ?>

This seems like very straightforward sql injection vector, but I'm not really an expert at exploiting such things, and my relatively feeble attacks have been caught by the new server. However, there are 1000 entries in the database where the titles are pretty clear attempts to execute injection attacks, and worse yet are the 1000 more with empty titles which might represent attacks that were successful.

So how bad is this? Here is my scale:

37GB of spam! Ha ha ha! No problem!
Removing the insecure code and moving to a new server should be safe.
The site will not really be safe until you switch to a new server, remove all the insecure code, and run some automated tests on the database and/or file structure to check for residual attack vectors.
The site will not really be safe until you switch to a new server, remove all the insecure code, and then go through each file and each database row and manually check to make sure that it isn't an attack vector — in other words, it's probably easier to give up and start over, no matter the size of the site.

Theoretically, that SQL query could be used to do anything on that database server, including changing the password for a Drupal  account not used so often, or creating a new account in the users table.

Suppose that $_POST['title'] contains the following.

"ddddd', 'comment', 127.0.0.0.1, 1469987843, 0, 3, '01/', 'Tintin', NULL NULL); DELETE FROM {users} u WHERE u.uid > 0; -- "

This would change ""INSERT  INTO {comments}  VALUES($cid2, 0, $nid, $uid, '$title', '$comment', '127.0.0.1', $timestamp, 0, 3,'01/', '$name', NULL, NULL)" into the following.

"INSERT INTO {comments} VALUES($cid2, 0, $nid, $uid, 'ddddd', 'comment', 127.0.0.0.1, 1469987843, 0, 3, '01/', 'Tintin', NULL NULL); DELETE FROM {users} u WHERE u.uid > 0; -- ', '$comment', '127.0.0.1', $timestamp, 0, 3,'01/', '$name', NULL, NULL)"`

I added a query to delete the users table, but I could have added any query, including the one to alter the password of an existing account, or creating a new user.

How that type of attack is effective depends only from how much the attackers know about your site: which software you are running, which version, etc. Once they have access as administrator, they could do enable the PHP input format, and execute arbitrary code. I would say that spam is the last of your problems.

As side note, as Clive said, template files should never contain SQL queries; eventually, those could be in preprocess functions, but in most of the cases, they should be in a module.
Also, in Drupal SQL query, you should wrap the database table names in {}. This allows Drupal to use prefixes in the table names, and even use tables from different databases.


Creating custom panel page gives page not found error I have been striving hard to make this work.I have created a custom panel page with the page url as taxonomy/term/%term/content-type/how-to.
So i have this via pathauto url
Vocab : Category
Parent term: food
Child term : pizza

After setting up the panel page when i go to
www.example.com/category/food/pizza/content-type/how-to it gives me 404 error(page not found).

And when i manually set up a custom panel page for each url(for e.g www.example.com/category/food/pizza/content-type/how-to)  it is working fine.

Can you guys point out whats wrong withtaxonomy/term/%term/content-type/how-to url ?

The most common and likely reason is that you have not assigned a context to your %term argument. This causes Page manager to reject the term argument, failing to find the path, and finally returning a 404. There's a similar issue here.

I could tell more specifically if you provided an export of the Panel.


Styling label of a select list I want to style the label of my select list with bold font and give it some color.

This is the code for rendering form which I am using in a hook_block_view

  $form['dropdown_first'] = array(
    '#type' => 'select',
    '#title' => 'City',
    '#options' => $options_first,
    '#prefix' => '
',
    '#suffix' => '
',
    '#default_value' => $selected,
    '#ajax' => array(

      'callback' => 'get_citylocations_dropdown',
      'wrapper' => 'dropdown-second-replace',
    ),
  );

The #prefix and #suffix is wrapping entire select list and effecting/applying the select list which is not I want. I just want to style the City to something likeCity

Its not working as I expected.

How do i do it?

Not sure why you insist on using Form API for this, but form element labels are rendered in theme_form_element_label(). You may want to override that function in your theme's template.tpl.php file to produce the desired markup.


Dont cache hook_form_form_id_alter I made a form, with a few fields. In the hook form alter I add some info text depending on the value of a $_GET variable.
Only the hook alter is only called the first time.
I want is to be called every time the form is viewed.

Am I using the wrong hook?

You need to either disable cache entirely with max-age = 0 or to make it vary based on the GET argument value, which is the better way unless your GET argument unique for everyone or most people.

Something like $form['#cache']['max-age'] = 0;

See https://www.drupal.org/developing/api/8/render/arrays/cacheability for the documentation.