Manually changing URL alias values via phpmyadmin? What does this affect? I have a bunch of aliases in my url_alias table. I want to change the source of certain rows, but I'm not sure if it would affect anything. What I need to know is if the column PID in the url_alias table is linked to anything else. Currently I just want to switch node/33 to node/2343, but im afraid I might break something if im doing it via phpmyadmin. I can't do it via the site as I have over 100+ entries I have to modify. The easiest way is by doing it in mysql.

Also is there a drupal database table map I can generate that shows me how each table is linked to each other?

Doing any manual updates to the Drupal database is a bad idea unless you know exactly what you are doing.

The {url_alias} table is written to with path_save().  If you look at the source, two hooks may be fired, depending on whether the path is new or update: hook_path_insert() or hook_path_update().

So, if you update  {url_alias} manually, you don't give any other modules the chance to react via the hooks.  Whether or not anything bad will happen depends on whether your system has any of these hooks in use.  Off the top of my head, I am unaware of any modules that do, but you would need to run a module_implements('path_insert') and module_implements('path_update') to be sure.

Your safest bet is to always use the API.  Write a standalone script, and execute it with drush -u 1 scr yourscrpt.php to make sure all of your hooks execute.


What is the proper permission settings to create a moderated, private organic group (in commons 3)? I'm trying to create a private group in Drupal Commons. It is my assumption that one follows open, public groups.

However, I've marked a few groups as private using the default roles and permissions. I anticipated seeing a Register option for that group.

I guess I'm trying to create a moderated group where the user is approved by the group owner. How does this happen?

I'm also seeing that Commons Groups may be interfering with the group permissions by graying out the Member subscribe only with the approval option (drupal ticket link).

In the group field settings, I have the following fields attached to groups and content types.

The group settings for one example group I wish to make private are the following.

However, while masquerading as authenticated user, I still see the Follow button. I would expect to see a Register for this group option.

I understand your confusion. In Drupal Commons, follow is not the same as registering as a group member.

If you check off the non-member checkbox on the Subscribe to group line then non-members can apply to register for that group. AS you have your other settings then an administrator can approve this registration.

Becoming a member of a group allows you to post. However, in the default configuration, posts in even private groups are visible unless additional permissions are applied and users may still follow the group.


How to display tags inline? How can I display tags below an article inline? I have tried using firebug to no avail. I am using Drupal 7 and the zen sub theme.

You can use CSS to style the tags.

If your html output is this:

Tag 1</l1>

Tag 2</l1>

Tag 3</l1>

Tag 4</l1>

Then use the following CSS to align tags horizontally.

.tags li { display:block; float:left; }


Changing node/%/edit title I have created custom content type for upload the details. I have used hook_form_alter to set the node title as "Upload". When I edit the node in node/%/edit the title remains "Upload". I want the title to be "Edit" .How to do this?

Please try this:

function hook_form_alter(&$form, &$form_state, $form_id) {
   if($form_id == 'form-id') {
   if(arg(0) == 'node' && arg(2) == 'edit'){
     drupal_set_title('Upload Edit');
    }
    else{
     drupal_set_title('Upload'); }

  }
}


How to add cursor to text field on page load? I'm working on an attendance site in Drupal 7 and I use a reference entity field to accept scanned ID badges. Once the ID number is saved in the field the page reloads.

I'd like to have a cursor appear in the field after the page is reloaded. I know this can be done with java script but I haven't been able to get it to work. I added scripts[] = scripts.js in the .info of the theme and created a .js file with the same name in my theme directory.

(function setFocus() {
document.getElementById("field_student").focus();

}

function select() {
    document.getElementById("field_student").select();

}

I'm not very adept at javascript and I'd appreciate it if someone could point me in the right direction.

You can actually do it with html autofocus now - no need for JS.

You should be able to do it with this:

<?php
  // inside a hook_form_alter()

  $form['field'] = [
    '#type' => 'textfield',
    '#attributes' => array('autofocus' => TRUE)),
  ];


Bearer Token in url is not parsed by route I Installed Drupal 9.1.0 on a VPS running on Ubuntu 20.4 and using Nginx 1.18.0, with Composer 2.0.8.
I installed two modules (Token and Devel) and a theme (Barrio) using Composer. I can enable the modules without problem, but when I try to install Barrio and set it as default theme, I get an access denied error.
I tried to enable other themes, but I always get the same error.
I cleared the cache and installed the theme with Drush. Still, setting the theme as default one causes an error. In this case, the error in the log is the following one.
Path: /admin/appearance/default?theme=THEME_NAME&token=TOKEN. Drupal\Core\Http\Exception\CacheableAccessDeniedHttpException: 'csrf_token' URL query argument is missing. in Drupal\Core\Routing\AccessAwareRouter->checkAccess() (line 117 of /PATHTOSITE/core/lib/Drupal/Core/Routing/AccessAwareRouter.php).

...:: UPDATE ::...
I used to start debugging to check where exactly the problem happens and realized that in line 57 of /Drupal/Core/Access/CsrfAccessCheck.php where code says :
$request->query->get('token', '')
there results become '' , which means $request->query->token is empty. debugging backward I looked at many files including :
Drupal/Core/Access/AccessArgumentsResolverFactory.php where it produces $request for csrfCheck
Drupal/Component/Utility/ArgumentsResolver.php which is used in above file

and finally I got to the place where problem is started:
Drupal/Core/Routing/RouteMatch::createFromRequest
this method can not recognize the token in url and cause all other problems, but I still don't know what cause this method failure
could it be my Nginx configurations?
Nginx config is:
location / {
try_files $uri $uri/ /index.php?query_string;
}
One more thing , when I use dsm on request, token can be find in $request->requestUri (is shown as /admin/appearance/install?theme=stark&token=qI5_B99oNr4TWdNfu5aTdd01NezSpPKOZje8HCVOMEs), But $rquest->query["query_string"] is ""

Finally after spending few days doing debugging and searching I noticed that the error was due to my Nginx configuration , this configuration from Nginx website was what solved the problem for me:
server {
    server_name example.com;
    root /var/www/drupal/MYSITE/web;

    location = /favicon.ico {
      log_not_found off;
      access_log off;
    }

    location = /robots.txt {
      allow all;
      log_not_found off;
      access_log off;
    }

    # Very rarely should these ever be accessed outside of your lan
    location ~* \.(txt|log)$ {
      allow 192.168.0.0/16;
      deny all;
    }

    location ~ \..*/.*\.php$ {
      return 403;
    }

    location ~ ^/sites/.*/private/ {
      return 403;
    }

    # Block access to scripts in site files directory
    location ~ ^/sites/[^/]+/files/.*\.php$ {
      deny all;
    }

    # Allow "Well-Known URIs" as per RFC 5785
    location ~* ^/.well-known/ {
      allow all;
    }

    # Block access to "hidden" files and directories whose names begin with a
    # period. This includes directories used by version control systems such
    # as Subversion or Git to store control files.
    location ~ (^|/)\. {
      return 403;
    }

    location / {
      try_files $uri /index.php?$query_string;
    }

    location @rewrite {
      rewrite ^ /index.php;
    }

    # Don't allow direct access to PHP files in the vendor directory.
    location ~ /vendor/.*\.php$ {
      deny all;
      return 404;
    }

    # Protect files and directories from prying eyes.
    location ~* \.
    (engine|inc|install|make|module|profile|po|sh|.*sql|theme|twig|tpl(\.php)?
    |xtmpl|yml)(~|\.sw[op]|\.bak|\.orig|\.save)?$|/(\.(?!well-
    known).*|Entries.*|Repository|Root|Tag|Template|composer\.
    (json|lock)|web\.config)$|/#.*#$|\.php(~|\.sw[op]|\.bak|\.orig|\.save)$ {
      deny all;
      return 404;
    }

    # In Drupal 8, we must also match new paths where the '.php' appears in
    # the middle, such as update.php/selection. The rule we use is strict,
    # and only allows this pattern with the update.php front controller.
    # This allows legacy path aliases in the form of
    # blog/index.php/legacy-path to continue to route to Drupal nodes. If
    # you do not have any paths like that, then you might prefer to use a
    # laxer rule, such as:
    #   location ~ \.php(/|$) {
    # The laxer rule will continue to work if Drupal uses this new URL
    # pattern with front controllers other than update.php in a future
    # release.
    location ~ '\.php$|^/update.php' {
      fastcgi_split_path_info ^(.+?\.php)(|/.*)$;
      # Ensure the php file exists. Mitigates CVE-2019-11043
      try_files $fastcgi_script_name =404;
      # Security note: If you're running a version of PHP older than the
      # latest 5.3, you should have "cgi.fix_pathinfo = 0;" in php.ini.
      # See http://serverfault.com/q/627903/94922 for details.
      include fastcgi_params;
      # Block httpoxy attacks. See https://httpoxy.org/.
      fastcgi_param HTTP_PROXY "";
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
      fastcgi_param PATH_INFO $fastcgi_path_info;
      fastcgi_param QUERY_STRING $query_string;
      fastcgi_intercept_errors on;
      # PHP 5 socket location.
      #fastcgi_pass unix:/var/run/php5-fpm.sock;
      # PHP 7 socket location.
      fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
      try_files $uri @rewrite;
      expires max;
      log_not_found off;
    }

    # Fighting with Styles? This little gem is amazing.
    location ~ ^/sites/.*/files/styles/ {
      try_files $uri @rewrite;
    }

    # Handle private files through Drupal. Private file's path can come
    # with a language prefix.
    location ~ ^(/[a-z\-]+)?/system/files/ {
      try_files $uri /index.php?$query_string;
    }

    # Enforce clean URLs
    # Removes index.php from urls like www.example.com/index.php/my-page -->
    www.example.com/my-page
    # Could be done with 301 for permanent or other redirect codes.
    if ($request_uri ~* "^(.*/)index\.php/(.*)") {
      return 307 $1$2;
    }
}


How to get Webform Field data for a custom module? I'm trying to set up a view permission based on a webform field.  I've been able to get to my custom module using hook_webform_submission_access().

So I have an email field in the webform, and I want to check that based on the current user's email address.  Should be pretty simple, I just can't get the field data.  Anyone know?

Example:

if ($submission->data['field_email'] == $user->mail)

What is the correct syntax instead of $submission->data['field_email']

I'm on Drupal 7 and Webform 4.x branch.

Provided Token is installed, you can use token_replace to access Webform submission values by field name.

$email = token_replace('[submission:values:email]', array('webform-submission' => $submission));

Note: The Devel module can be useful for exploring object properties and tokens (among other things).


How to customize default add content page I want to customize the default add content page, more specifically, to get rid vertical tab in the bottom, and add explanation text to each field.

How can i do this?
what php file should i tinker ?
is there already some modules to to this ?

thank you for reading this.

You can use the Renderable Elements module. If you've ever had any experience with Display Suite, it works exactly like that, but for forms like Add Content. You can change up the display, remove the vertical tabs below, etc.

For the explanation, each field comes with a description/help field that you can fill out. Now it depends on the admin theme you're using on how that text is displayed.


Modifying base_url in settings.php When we deployed to a production site, CSS and images got broken.

One approach to mitigate this was editing settings.php, the base_url

$base_url = '/oursite';

(Where "oursite" is our domain, i.e. http:localhost/oursite/ )

But that also broke some functionality on our local site. For example:

The requested page "/oursite/?q=oursite/node/add/cmsdeliverable%3Ffield_demo_id_reference%3D1208" could not be found.

What other approaches can I take?

Firstly, your $base_url should be fully qualified: http://www.example.com.

Secondly, you should configure your $base_url to be 'dynamic' - different for development, staging and production.  Detect the 'environment' and then set the $base_url accordingly.

As for the broken styling, I have seen broken theme problems related to file system rights.  It may be that your site is using CSS/JS aggregation / compression.  These compressed files are created on the fly by Drupal (check admin/config/development/performance).  If there are file/folder rights issues on the production, the files will not be created.

May be useful to check the error log (/admin/reports/dblog) - could just point you in the right direction.


How to share saved data from 2 different input fields This is hard to explain...but i will try.

I want users to be able to input their age in 2 different ways:

Date of birth field (this will display age with computed field)
Age with drop down integer (age from 18-99)

I want the age to be displayed on the same field in the User View Display.

Please ask for clarification if not clear.

You can use this code to compute age from date field:

    //compute age
    $bdayunix = strtotime($data->node_data_field_role_field_birthdate_value);
    $nowunix = time();
    $unixage = $nowunix - $bdayunix;
    $age = floor($unixage/ (365 * 24 * 60 * 60));

    print $age;

I hope these links will also help you solving your problem:

https://www.drupal.org/node/149237
http://www.kadimi.com/en/age-from-date-of-birth-in-drupal-7


jquery integration issue when attempted to execute on load It may just my limited js experience but until recently I had some js attached to the drupal context on one of my sites to produce some small animation/style effects that took the form:

$(window).on("load",function() {
    //do something
})

This worked great until recently then suddenly stopped working with no errors or messages. Eventually I got it working by changing the above to:

$(document).ready(function() {
    //do something
})

Did something change in core or jquery that caused this? Why would there be no errors? I use the first $(window).on() successfully on at least two other sites but have not been able to figure out why it stopped working on this one.

Some of the js I wish to run relies on the entire page being fully loaded so I really would rather use $(window).on()- which I believe triggers later.

I am using the latest release version of drupal 8

As @Kevin mentioned

  Drupal 8.4 introduced jQuery 3.x

And according to jQuery Core 3.0 Upgrade Guide  the "ready" event has been removed.

What you should do is to implement your functional code in Drupal.behaviours. This would have the similar effect as $(document).ready() but with more benefits.

(function ($, Drupal) {

  Drupal.behaviors.myHandler = {
    attach: function (context, settings) {
      // do something
    }
  };

})(jQuery, Drupal);


Create A Product On Drupal 7 Hello I Am Making A Website So I Want To Add Some Of My Product In My Product Page So I Want To Know That How I Can Add Product With Name Cost Of Product And Description Can Any One Suggest Any Module To Setup Product In D7

You can use either of these ecommerce solutions:

Drupal Commerce

  Drupal Commerce is used to build eCommerce websites and applications
  of all sizes. At its core it is lean and mean, enforcing strict
  development standards and leveraging the greatest features of Drupal 7
  and major modules like Views and Rules for maximum flexibility.

or Ubercart.

  Ubercart is the most popular Drupal E-Commerce platform for your
  website. It implements everything you need to start selling products
  online. Web Developers from all skill ranges can use it to support a
  variety of E-Commerce industries-- including physical goods, digital
  downloads, or even subscription based billing services. Ubercart can
  do it all!


How to generate a list of all valid URLs served by my site Is there a way to generate a list of all valid URLs that a site will resolve, including redirects?

Specifically, all views, nodes, and redirects (the from and to.)

The list is required for record reasons by a college in another department.

An answer would be especially useful if it didn't require a code change, as it's production site, and a code change would have to go through code review and require a release, but if it's necessary then it's necessary.

Module wise, among many others, xmlsitemap, redirect, path redirect import, pathauto and pathologic are installed. I'm not sure if any of those might be of any use.

As a second question, if there isn't a way of automatically generating all of the URLs in a pleasantly formatted list, then besides manually collecting all of the views URLs and the redirects urls, where else should I be looking?

There exists a number of website checking tools (aka. robots or spiders) that will crawl a given website and generate a number of reports, including a report of all URLs found on that site by recursively crawling the site from some starting point (crawl foundation page).

Below are links to three such tools that I've used for this purpose:

WebCheck: http://arthurdejong.org/webcheck/
Link Sleuth: http://home.snafu.de/tilman/xenulink.html
DRKSpider: http://www.drk.com.ar/spider.php

Note that these will only report URLs that are reachable from the crawl foundation page. If your site consists of sub-sites that are not reachable from each other, you need to set up more than one crawl foundation.


Fatal Error HtmlRouteProvider not found? Fatal Error: Fatal error: Class
  'Drupal\custom_avatar\CustomAvatarHtmlRouteProvider' not found in
  /Sites/drupal8/core/lib/Drupal/Core/Entity/EntityTypeManager.php on
  line 252

I am creating config Entity type and below is structure of my module shown in screenshot:

I below code I have defined below routing so that I don't have to define each of these routes statically in our module's routing.yml file. My class extends AdminHtmlRouteProvider :

  "route_provider" = {
         "html" = "Drupal\custom_avatar\CustomAvatarHtmlRouteProvider",
       },

<?php

namespace Drupal\custom_avatar\Entity;

use Drupal\Core\Config\Entity\ConfigEntityBase;

/**
 * Defines the Avatar profile entity.
 *
 * @ConfigEntityType(
 *   id = "custom_avatar",
 *   label = @Translation("Avatars for user profiles"),
 *   handlers = {
 *     "list_builder" = "Drupal\custom_avatar\CustomAvatarListBuilder",
 *     "form" = {
 *       "add" = "Drupal\custom_avatar\Form\CustomAvatarForm",
 *       "edit" = "Drupal\custom_avatar\Form\CustomAvatarForm",
 *       "delete" = "Drupal\custom_avatar\Form\CustomAvatarFormDeleteForm"
 *     },
 *     "route_provider" = {
 *       "html" = "Drupal\custom_avatar\CustomAvatarHtmlRouteProvider",
 *     },
 *   },
 *   config_prefix = "custom_avatar",
 *   admin_permission = "administer site configuration",
 *   entity_keys = {
 *     "id" = "id",
 *     "label" = "label",
 *     "uuid" = "uuid"
 *   },
 *   links = {
 *     "canonical" = "/admin/structure/custom_avatar/{custom_avatar}",
 *     "add-form" = "/admin/structure/custom_avatar/add",
 *     "edit-form" = "/admin/structure/custom_avatar/{custom_avatar}/edit",
 *     "delete-form" = "/admin/structure/custom_avatar/{custom_avatar}/delete",
 *     "collection" = "/admin/structure/custom_avatar"
 *   }
 * )
 */

class CustomAvatar extends ConfigEntityBase implements CustomAvatarInterface {
  /**
   * The Avatar profile ID.
   *
   * @var string
   */
  protected $id;

  /**
   * The Avatar profile label.
   *
   * @var string
   */
  protected $label;
}

<?php

namespace Drupal\custom_avatar;

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Routing\AdminHtmlRouteProvider;
use Symfony\Component\Routing\Route;

class CustomAvatarHtmlRouteProvider extends AdminHtmlRouteProvider {

  /**
   * {@inheritdoc}
   */
  public function getRoutes(EntityTypeInterface $entity_type) {
    $collection = parent::getRoutes($entity_type);

    $entity_type_id = $entity_type->id();

    if ($collection_route = $this->getCollectionRoute($entity_type)) {
      $collection->add("entity.{$entity_type_id}.collection", $collection_route);
    }

    return $collection;
  }

  /**
   * Gets the collection route.
   *
   * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
   *   The entity type.
   *
   * @return \Symfony\Component\Routing\Route|null
   *   The generated route, if available.
   */
  protected function getCollectionRoute(EntityTypeInterface $entity_type) {
    if ($entity_type->hasLinkTemplate('collection') && $entity_type->hasListBuilderClass()) {
      $entity_type_id = $entity_type->id();
      $route = new Route($entity_type->getLinkTemplate('collection'));
      $route
        ->setDefaults([
          '_entity_list' => $entity_type_id,
          // Make sure this is not a TranslatableMarkup object as the
          // TitleResolver translates this string again.
          '_title' => (string) $entity_type->getLabel(),
        ])
        ->setRequirement('_permission', $entity_type->getAdminPermission())
        ->setOption('_admin_route', TRUE);

      return $route;
    }
  }

}

Please suggest what is cause of error, the module gets installed without any error but when I clear all cache it shows error and the routs are not build using this way(page not found). I want to try using this class to build dynamic admin (canonical, add, edit, and delete forms for entities ) routs rather than defining in routing.yml

Thanks!

Unless you’re doing something custom, your classes need to be under ./src to be discovered. By default, MODULE/src/Foo.php is mapped to the Drupal\MODULE\Foo namespace and so on.

Move the two classes out of the root of your module and into ./src, clear cache, and try again.

See PSR4 namespaces and autoloading in Drupal 8 for full details.


DSM output intermittently shows up For some reason my DSM output is only occasionally showing up. Nothing significant is changing on the template I'm calling it from. It will show up, then on refresh go away, and randomly re-appear 10 refreshes later.

Any idea what can cause this behavior?

Especially in templates files, dpm() doesn't show up, I'm not sure about the cause but I guess it's because the drupal_set_message() function is called earlier. So while working on templates I prefer using kpr(), it works the same way but print directly the krumo message into the page instead of using drupal_set_message.


Grouping field in tabs - views Under views when i select unformated settings and can Grouping field, it is working fine.

Now i am using bootsrap tabs but it is not working

How we can do this

For using Bootstrap tabs with views you need to use the Views Bootstrap module: Views Boostrap module enables you to create components following the theme structure of the Bootstrap framework all within the configuration settings of the powerful Views module.

Views Bootstrap module supports following:

List item
Grid
Tables
Thumbnail
Media object
Accordion
Carousel
Tabs
List group


Services Module Unable To Update User Fields I am using the Services module configured with a REST endpoint. I can update all other fields on the user account but when I attempt to update the mail field (user e-mail field) it doesn't appear to change.

I think this has to do with the "current_pass" field. Am I supposed to validate the password somehow?

I am testing this but any "hey, silly guy, did you try this?" would be helpful.

Way 1:

Yes, you need to send the current password to update the user email that is default Drupal user account configuration, and the default user update enpoint exposed by services programmtically submit the same user profile form, which triggers all the validation your form has. In order to send the current password your request load may look like

{
    "current_pass": "onso",
    "mail": "test@example.com"
}

Way 2:

If you don't want to provide current password, you can consider using No Current Password module, but remember that it will remove the current password field from the form UI as well.

Way 3:

Expose custom endpoint to update user email. Make sure you have authentication on your endpoint.


Manage content type by admin menu link I wants to manage content type by admin menu tab, suppose I am having a "news" content type and if I would go to put some news, then I have to go first "content" tab then "Add content option" would appear and after navigate it, it shows all content types where I would select news this is default Drupal functionality but I wants that there should be link in admin menu like news, so when I click on news it directly navigate to news content type page and there should be only news contents not all. So how to do that? Actually I am having a lot of content types that I wants to show, each content type by each admin menu tab and also shows the data particular for its.

Please tell every thing step by step.

You can install the Administration menu module. Then you can navigate to your Content Types like this:

Or you can install the Menu block module and create a block with the links to your Content Types like this:


Migrate as separate files How can I create individual migration groups - one for each XLM file, without having to write a new migration class for each file?

I have dozens of XML files waiting to be imported into Drupal using the Migrate module and API.

Currently, all my migrations are registered under a single group called Questions as shown below:

That single group of 222 imports represents 5/6 of my XML files. If I import the pending dozens of XML files, I will have upwards of 10,000 imports.

What I would rather have is each XML file having it's own individual group.
That way I can revert a single XML file where necessary instead of all them.

Can anyone help me with this scenario?

Update: this answer is probably fine for D8 but not D7.

Using the migrate_plus module, I was able to specify shared configuration for about a dozen different feeds that needed to be given separate taxonomies upon import based on which organization's media I was importing. I created a group with my source and process configuration, then created individual importers for each feed with just the configuration that was specific to that feed. If I wanted to import them all at once I could run drush mi --group=<group_name>, and if I wanted to roll back a single feed I could run drush migrate-rollback <migration_name>. The only tedious part for me was creating a dozen nearly-identical migrations.

So, for example, here's a group definition for an Twitter importer:

id: twitter_importer
source_type: twitter
shared_configuration:
  source:
    plugin: url
    data_fetcher_plugin: http
    data_parser_plugin: json
    authentication:
      plugin: oauth2
      base_uri: 'https://api.twitter.com'
      token_url: /oauth2/token
      grant_type: client_credentials
    fields:
      -
        name: id
        selector: id_str
      -
        name: text
        selector: text
      -
        name: timestamp
        selector: created_at
    ids:
      id:
        type: string
  process:
    title:
      plugin: substr
      source: caption
      start: 0
      length: 254
    type:
      plugin: default_value
      default_value: twitter_feed_item
    # etc. etc.

Then a few migrations like this:

id: tw_dept_a
dependencies:
  - migrate
  - migrate_plus
migration_group: twitter_importer
source:
  # this changes from migration to migration
  urls: 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=tmountjr&count=10'
process:
  field_source:
    # this also changes; works because the group's shared config specifies the plugin
    default_value: tmountjr
destination:
  plugin: 'entity:node'

It's annoying setting it all up on the frontend but after the third one you get pretty quick at copy/pasting the template and replacing one or two variables.

So I guess to answer your question:

  How can I create individual migration groups - one for each XLM file, without having to write a new migration class for each file?

I'm not sure you can get around that...but you can abstract a lot of the repeated configuration out of each individual file using shared configurations. You can maybe further refine the process by having a template file with placeholder variables, duplicating the file, and using sed on the new file to replace filenames:

cp migration_template.yml migrate_plus.migration.migrate_xml1.yml
sed -i "s/filenameplaceholder/file1\.xml/g" migrate_plus.migration.migrate_xml1.yml


Relate data in a custom sql table to a regular drupal field using views I have a field collection, with a field "Attribute number", which contains a text value of the format "b1_a1", "b7_c2", etc.

I have a custom table that has a column that references an attribute number, and a column that contains a survey response value (yes or no).

I want to create a relationship between the attribute number field and my table, so that in views, I can list the attribute numbers, and display the corresponding response.

I'm looking at hook_data_alter().  There are example to extend a base table, such as node, and join with a new table, but there is no example to extend a non base table, such as my field_data_field_attribute_num.

How do I make a views join with a non base table?

I assume you will be associating your "Attribute number" field to a node type, and that your view will be showing nodes. So, what you need to do here is describe your custom table (I call it "custom_an" here) to the views API and provide a way to join it when displaying node data. Here is a way to do that:

function YOURMODULE_views_data() {
  // Assign a group for the custom table:
  // can be an existing group - e.g. t("Content") -
  // or, like I  do here, a new custom group.
  $data['custom_an']['table']['group'] = t('Extended content');

  $data['custom_an']['table']['join'] = array(
    // This table will be available for join for any 'node' view.
    // 'left_table' is the referenced table,
    // i.e. the one that contains your field's data
    // 'left_field' is the join key in the referenced table.
    // 'field' is the foreign key in the custom table.
    'node' => array(
      'left_table' => 'field_data_field_attribute_number',
      'left_field' => 'field_attribute_number_value',
      'field' => 'attribute_number',
    ),
  );

  // here we describe the field(s) in the custom table
  // that we want to show in the view.
  $data['custom_an']['response'] = array(
    'title' => t('Response'),
    'help' => t('Response field.'),
    'field' => array(
      'handler' => 'views_handler_field',
      'click sortable' => TRUE, // This is use by the table display plugin.
    ),
    'sort' => array(
      'handler' => 'views_handler_sort',
    ),
    'filter' => array(
      'handler' => 'views_handler_filter_string',
    ),
    'argument' => array(
      'handler' => 'views_handler_argument_string',
    ),
  );

  return $data;
}

Please be aware that this is only a proof of concept, and that it's meant to get you started but in no way you should use this code as is for a production site.
Two major issues to be addressed would be:

testing this code against a node type which does not contain the "Attribute number" field (and possibly find the right way to avoid that adding the custom data to that view results in a corrupted view), and
if attribute_number in your custom table is not unique, the view could output duplicate rows. The join key in the custom table should actually be a primary key, according to hook_views_data() documentation.


Pass querystring to XSL through module I'm trying to do some fancy navigational work within a large XML sheet, and am generating links with querystrings in my transformation.

What I would like to do is parse the querystring within my .module file, and then pass it somehow to the XSL processor.

Essentially, right now I have (without any error handling at present):

/* generate hook */
function _xml_import_generate()
{
  $p = $_GET['p'];

  $path = drupal_get_path('module', 'xml_import');

  $xsl = new DOMDocument();
  $xsl->load("{$path}/xml_import.xsl");

  $xslt = new XSLTProcessor();
  $xslt->importStyleSheet($xsl);

  $xml = new DOMDocument();
  $xml->load("feed.xml");

  return (string) $xslt->transformToXML($xml);
}

I can't seem to find any documentation regarding this...but how do I pass $p into my XSL transformation?

I think you just need to parse out the query string, and then use XSLTProcessor::setParameter:

/* generate hook */
function _xml_import_generate()
{
  $p = $_GET['p'];

  $path = drupal_get_path('module', 'xml_import');

  $xsl = new DOMDocument();
  $xsl->load("{$path}/xml_import.xsl");

  $xslt = new XSLTProcessor();
  $xslt->importStyleSheet($xsl);

  $xslt->setParameter("", "p", $p);

  $xml = new DOMDocument();
  $xml->load("feed.xml");

  return (string) $xslt->transformToXML($xml);
}

Your parameter should then appears as a <xsl:param /> in your XSLT.


How do I remove duplicates when using the random sort? I have created a view where I am displaying the the node title and a logo (a cck field). In the arguments I have passed the taxonomy term name.

In the result a node is displaying 2 or 3 times; I already checked the distinct checkbox in the Query settings but that also does not work. I have used the random sort, which seems to cause the duplicates; when I remove the random sort, it works fine.

How can I avoid the duplicates without disabling the random sort?

The simple way to achieve distinct values in a view is to make the following:

Go and edit your view
In Advanced » OTHER section click on "Query setting"
Check "Distinct" check-box.


What's the advantage of view blocks? Instead of creating a block for each view, I simply display the master views in the panels on my website. As that works perfectly until now, I'm wondering why one should create a view block. Do they have any advantages over master views? Is my way of acting risky in a sense?

I wonder how you embed the View in your site.
(I'm aware of views_embed_view() or any other PHP method. We good people don't even enable the PHP module do we?)

Block caching. Views exposed the Views to the blocks system, so they can cached, altered, and just about anything regarding blocks can be done.
If you want to have multiple blocks/displays out of the same View, you do have to create blocks. More views = more headache.


CSV migration always returns "id is defined as a source ID but has no value" I have a freshly composer installed Drupal 8.6.13. I tried to migrate csv sources and allways got the error message

  [error] Migration failed with source plugin exception: id is defined as a source ID but has no value.

I switched to an example that is running in another installation https://www.drupal.org/docs/8/api/migrate-api/migrate-source-plugins/migrating-data-from-a-csv-source, but still get this error.

My versions: migrate  8.6.13, migrate_plus 8.x-4.1, migrate_source_csv 8.x-2.2, migrate_tools 8.x-4.1

Does anyone have an idea what causes the error?

This are the files:

CSV:

id,title,body
1,title 1,some body text 1
2,title 2,some body text 2
3,title 3,some body text 3

Migration configuration:

id: article_csv_import
label: Import articles
migration_groups:
  - ACME import
source:
  plugin: csv
  path: 'public://articles.csv'
  delimiter: ','
  enclosure: '"'
  header_row_count: 1
  keys:
    - id
  column_names:
    0:
      id: 'Unique Id'
    1:
      title: 'Title'
    2:
      body: 'Post body'
process:
  title: title
  body: body
  type:
    plugin: default_value
    default_value: article

destination:
  plugin: entity:node

I already had the same error you've got; in fact it's a mistake :
Please double check that the delimiter set in the yml file is the same as in your source file (edit it with notepad++ to be sure). Sometimes Excel change delimiter when reopening csv file before resave it without settings file format.

Also, note the column_names key is not mandatory, as the plugin will automagically extract column from your file (see migrate_source_csv\src\Plugin\migrate\source\CSV.php line 110 ... 123). Here you can also print the $column_names array to check if it contains same number of items as your file columns.

BR


Views change "Exclude from display" at run-time Main question: How to change the value for "Exclude from display" on runtime, programmatically ?

Background:
I am rendering a View programmatically.
The View has attached Data Export to it (exporting to CSV)
The view has multiple fields (42 actually).

On some action (hook_node_update, etc.), I load a node object.
The node object has 2 fields of interest.

field_views_filter = field that is using the Field Embed Views module
and stores
exposed filter settings
field_export_select_fields = list(text) field    that selects which
of those 42 fields should be exported to csv. Sometimes all fields will need to be displayed, sometimes only 5 fields will have to be displayed.

Scenario:
What I have tried:

<?php
function test () {
      // Loading arbitrary node
      $node = node_load(44165);

      $select_fields = array();

      $displayed_fields = array();
      foreach ($node->field_export_select_fields[LANGUAGE_NONE] as $key => $value) {
        $select_fields[] = $value['value'];
      }

      $name = 'MY_VIEW_NAME';
      $display = 'views_data_export_1';
      $view = views_get_view($name);
      $view->set_display($display);

      // Gets the exposed filters.
      $exposed_filters = $node->field_views_filter[LANGUAGE_NONE][0]['settings'];
      $view->set_exposed_input($exposed_filters);

      foreach ($view->display['views_data_export_1']->display_options['fields'] as $key_field => $value_field) {
        // This sets the value of "Exclude field from display to 1", but it is not working.
        $view->display['views_data_export_1']->display_options['fields'][$key_field]['exclude'] = 1;
      }
      $view->display['views_data_export_1']->display_options['fields']['title']['exclude'] = 0;

      $output = $view->preview();

      $file_string = 'sites/default/files/private/' . time() . '.xls';
      file_unmanaged_save_data($output, $file_string, FILE_EXISTS_REPLACE);

      $view->destroy();
    }

You need to save your view with hidden fields and then load it again

<?php

function test () {
  // Loading arbitrary node
  $node = node_load(44165);

  $select_fields = array();
  foreach ($node->field_export_select_fields[LANGUAGE_NONE] as $key => $value) {
    $select_fields[] = $value['value'];
  }

  $name = 'MY_VIEW_NAME';
  $display = 'views_data_export_1';
  $view = views_get_view($name, TRUE);

  // Hide selected fields.
  foreach ($view->display['views_data_export_1']->display_options['fields'] as $key_field => $value_field) {
    if (in_array($key_field, $select_fields)) {
      $view->display['views_data_export_1']->display_options['fields'][$key_field]['exclude'] = 1;
    }
    else {
      $view->display['views_data_export_1']->display_options['fields'][$key_field]['exclude'] = 0;
    }
  }

  // Save view.
  views_save_view($view);
  // Load updated view.
  $view = views_get_view($name, TRUE);
  $view->set_display($display);

  // Gets the exposed filters.
  $exposed_filters = $node->field_views_filter[LANGUAGE_NONE][0]['settings'];
  $view->set_exposed_input($exposed_filters);

  $output = $view->preview();

  $file_string = 'sites/default/files/private/' . time() . '.xls';
  file_unmanaged_save_data($output, $file_string, FILE_EXISTS_REPLACE);

  $view->destroy();
}


Best way to benchmark Drupal stack performance I recently asked a question regarding Drupal performance and got some great replies.

This got me thinking, what is a reliable/meaningful way to benchmark Drupal?

It's easy to say "install APC, memchached & Varnish" or "install module x or y", but how can I quantify just how big of a performance gain I'm getting from each setup? Basically, a sure-fire way to compare setups and find bottlenecks to squeeze the most possible performance from a Drupal site. What is the best method to find out?

Targetting Drupal 6.

I like jmeter, http://jakarta.apache.org/jmeter

It allows actual benchmarking of authenticated sessions, which many of the other approaches like ab do not. There's an article about using jmeter with authenticated users at this link


How can I know whether user has logged in through facebook account or through Site login? How can I know whether user has logged in through FB or through site's login section? I am giving points to user based on FB login that's why It's important to know. Thanks

You could use Rules module together with Notification module, to achieve what you want. There is no out of the box solution for this problem.

You will have to look into Adding a new rule to react to user registrations
Or to user logins. You will properly have to create a custom module depending on the deepth of what you exactly need


Split an array returned by menu_tree_output I want to display an expanded menu and split it in two columns after a certain amount of items:

Right now I have the following in my hook_block_view:

$menuTree = menu_build_tree('my-menu');
$menuOutput = menu_tree_output($menuTree);
$block['content'] = array('#markup' => drupal_render($menuOutput));
return $block;

So I would have to put some extra logic between menu_tree_output and drupal_render splitting the array after 5 items and wrapping the result in something like <div class="first_column">...

But dfb($menuOutput) gives me this huge array which I can't just array_chunk($menuOutput, 5).

Any idea how to handle this?

Just in case someone needs this: I found a solution altering menu_build_trees output:

$menuTree = menu_build_tree('my-menu');

// flatten out the hierarchic menu tree
foreach ($menuTree as $key=>$value) {
    // if the item has children
    if (count($value['below']) > 0 && $value['link']['hidden'] != 1) {
        $flatMenu[$key]['link'] = $value['link'];
        // add a custom class to the first level items
        $flatMenu[$key]['link']['localized_options']['attributes']['class'] = array(
          'first-level-item',
        );
        // override nested menu items
        $flatMenu[$key]['below'] = array();
        // and add those to the new array
        $flatMenu = array_merge($flatMenu, $value['below']);
    // if the item has no children
    } elseif ($value['link']['hidden'] != 1) {
        $flatMenu[$key] = $value;
        $flatMenu[$key]['link']['localized_options']['attributes']['class'] = array(
          'first-level-item',
        );
    }
}

$markup = '';
$chunk = 5;
// split the new array in chunks and wrap them each with a numbered class
foreach (array_chunk($flatMenu, $chunk, true) as $key=>$value) {
  dfb($value);
  $markup .= '
';
  $markup .= drupal_render(menu_tree_output($value));
  $markup .= '
'."\n";
}

$block['content'] = array('#markup' => $markup);
return $block;

It is a bit hacky but with some extra lines of CSS it works perfectly well!


How to override Breadcrumb theme template? I have a custom theme that has base theme: classy setting in the mytheme.info.yml file. When we enable twig debugging locally, we find that the <!-- BEGIN OUTPUT from 'themes/custom/mytheme/templates/navigation/breadcrumb.html.twig' --> is displayed, but there are no theme suggestions available.

This is what displayed on the page.

How can we create theme suggestions for breadcrumbs?

We tried the following in the mytheme.theme file, but it did not print out the ksm() statements.

function mytheme_theme_suggestions_breadcrumb_alter(array &$suggestions, array $variables) {
  ksm($suggestions); // this returns empty
  ksm($variables); // this only returns theme_hook_suggestion and links array
}

The code is based off of what we can do for block suggestions alters.

function mytheme_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  if (isset($variables['elements']['content']['#block_content'])) {
    $suggestions[] = 'block__' . $variables['elements']['content']['#block_content']->bundle();
  }
}

As mentioned by @Clive, breadcrumbs are not entities so I was not be able to get it done by adding a mytheme_theme_suggestions_breadcrumb_alter. Instead to solve the problem I had to do the following. On top of this, I ended up downloading and enabling Easy Breadcrumb to further modify the Breadcrumb

Copy the breadcrumb.html.twig file from the Classy theme into my mytheme directory
Clear cache
make any edits into the sites/themes/custom/mytheme/templates/navigation/breadcrumb.html.twig file
save and clear cache (if necessary)


Is there any way to reorder the nodes in a View? I have a complicated View containing many pages and attachments. When I built the View, I didn't think much about the order of the pages and attachments, but now I would like to change the ordering because it affects how they are displayed in the end. I would also like the flexibility to add additional pages in the future and be able to control where those attachments appear in the page.

I know you can control an attachment's position using the Above/Below options, but I have one page with 6 attachments and I can't seem to break the ordering except by creating and deleting nodes.

Edit: I discovered that I can accomplish this by exporting the View and reordering the code there and then reimporting, but if a cleaner solution exists, I would love to hear it.

You may also consider using the draggableviews module. Basically you create an "administrative" display of your view allowing arbitrary reordering of the content of the "main" display using drupal drag-and-drop interface.

There's also a comparison page for node ordering modules on drupal.org


Only sort views after selected I am looking to sort nodes in a view, but only after the user has selected the sorting value.

So the nodes are currently listed in posting order, but I would like to provide the user to sort by price, but only once selected the price sorting?

Creating a standard sort by price, sets this from the initial page load and does not give the use a chance to see recently posted items.

How could this be achieved?

Two ideas:

(1) Expose the sort to the user to allow them to control sorting. You need to enable "Expose this sort to visitors, to allow them to change it" for the sort criterion in views. See below for more detail on how to get the two sorts grouped together.

(2) Present the data in a table and make the columns you want the user to be able to sort, "sortable". You'll find this option under Format: table > Settings.

With both approaches, you can set an initial sort, so the user will see content in the order you wish when the page first loads.

Edit: more detail for #1: by default, views will sort the output based the first sort criterion, and clutter the exposed form with sort order controls. To get the default sort you want, and to clean things up, you can try:

Add both sort fields and expose to visitors (post date first)
Under exposed form options: enable autosubmit and hide the submit button
Under exposed form options: disable "Expose sort order"
Adjust exposed sort labels if needed for clarity

(exposed form options are in the Advanced section of the view)

When the view loads, the user will see a single select list that contains both sort options, and no submit button. The view will be sorted according to the first option.


Bypass publish approval on content creation for a certain role I have a content type "place" which can be created by any registered user but needs to be published by a "site editor" role. I also have a "place editor" role which will have his "place" content published as soon as it is created, not needing an approval.

There are other content types such as "event", which will have their own editors, so that a "place editor" will have to have his "event" content published by a site editor, but his "place" content will be published right away.

Can you name a module for this? I am using drupal 7

You could user Rules to publish or unpublish content based on a role or any other condition.


Where is the autocomplete function for user/addressfield/autocomplete? I searched but I cannot find the autocomplete function for addressfield module.
The path of this autocomplete function is user/addressfield/autocomplete.

So I need the file that declare this function.
Thanks!

I was using the Commerce Admin Order Advanced module.  This is was providing the autocomplete.


Exception\UnknownExtensionException: The module does not exist or is not installed I get this error on my site

  Drupal\Core\Extension\Exception\UnknownExtensionException: The module
  does not exist or is not installed. in
  Drupal\Core\Extension\ExtensionList->getExtensionInfo() (line 346 of
  ...core/lib/Drupal/Core/Extension/ExtensionList.php).

This error is happening in shared hosting server.

  public function getExtensionInfo($extension_name) {
$all_info = $this->getAllInstalledInfo();
if (isset($all_info[$extension_name])) {
  return $all_info[$extension_name];
}
throw new UnknownExtensionException("The {$this->type} $extension_name does not exist or is not installed."); // line 346

}

I have been searching online and found lot of discussions but I could not fix it. How can I fix the error?

Php: 7.0
Drupal: 8

I have agree with @4k4 you can fix this with database

If your module have been deleted from the system use this query

delete from `key_value` where collection = 'system.schema' and name = '$extension_name';

for example:

delete from `key_value` where collection = 'system.schema' and name = 'config_tools';
delete from `key_value` where collection = 'system.schema' and name = 'git_config';


How to download file from URL manually? I need to upload on Drupal 8 a file from an URL programmatically without using a form and a field type 'managed_file'.
I'm not sure how to do this, I found different web pages on it but it's often the old version of Drupal and only some part of code.

What exactly I want to do :

I Have an URL (for example a PDF document, a *.doc, ...)
I need to save it on Drupal and create the associated record in the database

You could keep it really simple by using something like file_get_contents() to retrieve your file and save it on somewhere on the servers filesystem, presumably /sites/default/files. After that, you can put in the database whatever you want.

The thing is, drupal won't know what to do with that in most cases. Files in drupal must be associated with a file field. That's the way things work.


Could drush require significantly more memory than same action in Drupal I am running Drupal 7.23 and drush 5.9

I can clear all caches in Drupal without an error but get "memory exhausted" if I try using drush cc all. I get "memory exhausted" when using "drush up", after it has downloaded and updated modules but was able to download and update the modules from within Drupal.

Is there anything that might be leading to a greater need for memory when using drush?

Probably not - but remember that in PHP 5, the command line or client interface for PHP was separated out and has its own ini file. if you search for your php.ini file, you'll probably see two versions, something like this

/etc/php5/cli/php.ini
/etc/php5/apache/php.ini

and you just need to match the memory limit in the (cli)ent ini file with what you have for Apache (or your web server).


How to display a comma-separated list of multiple field values? How can I render for example each taxonomy terms value as an inline comma-separated list (or add between each of them a "/" Character) in my field template field--node--field-tags.html.twig file or even visually with css?

While it's possible to use CSS for this I think it's better to avoid it. I've simplified the field twig file to illustrate, but it would look something like this:

{% for item in items %}
  {% if loop.last %}
    {% set separator = '' %}
  {% else %}
    {% set separator = '/' %}
  {% endif %}
  {{ item.content }}{{ separator }}
{% endfor %}


How to add an existing field to an user account? I created a vocabulary in Structure>Taxonomy>Add Vocabulary. Then I add terms to it.

My Vocabulary fields look like this :

I want to display this vocabulary into accounts fields, I want to add existing fields but I can't find the term reference.

You have to use "Add new field" until you haven't used your term reference field for the Departements at least once before.

If have created this field once, you can reuse it for other content types.


Drupal 7 Form API, Checkboxes with key -> value from database I'm working on a custom module and I'm adding a form that uses checkboxes.  All is fine with using code like:

$form['tags'] = array(
   '#type' => 'checkboxes',
    '#options' => array(
      88 => 'option1',
      100 => 'option 2',
      79 => 'etc'
    ),
   '#title' => t('Tag this project as...'),
  );

The problem comes from the fact that I'd like to pull the key and value from the database (a specific taxonomy).  I do not want to use an autocomplete, I want to use checkboxes.

Specifically, how do I get the results from the database and format into a proper array for the options array?  Also, on the edit version of the form I'm creating, how do I show items that have been "checked" based on their value?

All of the examples I've seen are extremely basic and never show how to do this from a database call.  Thanks for reading/answering

To populate your options array with data from table my_table, with value keys from column value and text from column atext, you can use:

$options = array();
$result = db_select('my_table', 'mt')
            ->fields('mt', array('value', 'atext'))
            ->execute();
foreach ($result as $row) {
  $options[$row->value] = $row->atext;
}

To get taxonomy terms, you could use the code above to query tid and name from the taxonomy_term_data table (plus add a condition() for the vocabulary id), but for this specific usage you'd better to use the right API:

$options = array();
// Get term tree for vocabulary which id is in $vid.
$terms = taxonomy_get_tree($vid);
foreach ($terms as $term) {
  $options[$term->tid] = $term->name;
}

Just do not forget that vocabularies are tree structures. See the documentation for the taxonomy_get_tree() API to know how to limit the terms you want to get from a vocabulary wrt starting term and tree depth.


Programmtically add image to custom image field User I can't figure out how to add image to a custom image field on a sepcific user.

    $f = file_save_data($user['thumbnailphoto'][0], 'private://profile/'. $data['name'] .'.jpg', FILE_EXISTS_REPLACE);
    $fid = $f->fid;

    //Add to virtual map 'Profile images'
    $file_entity = file_load($fid);
    $file_entity->status = 1;
    $file_entity->field_folder['und'][0]['tid'] = 180;
    file_save($file_entity);

    $user = user_load(334);

    $details['field_profile_picture'] = array(
                                        'und' => array(
                                            0 => array(
                                            'fid' => $fid,
    )));

    $u = user_save($user, $details);

But nothing get saved? Field_profile_picture is just an image field.

Thx!

In Drupal 7 you can use system_retrieve_file()

  system_retrieve_file : This function will download a file from a remote source, copy it from temp to a specified destination and optionally save it to
  the file_managed table if you want it to be managed.

  $usr_info = user_load(334); //load user object
  if (!empty($usr_info)) {//assign only if user exist
    $image_url = 'http://g-raph.be/sites/all/themes/g_raph_/images/image03.jpg'; //image URL to save. If image already saved in the drupal system then get the file ID(fid)
    //I have used picture folder to store images using image field settings
    $file_info = system_retrieve_file($image_url, 'public://pictures/', TRUE, FILE_EXISTS_REPLACE); //storing image inside picture folder
    if ($file_info->fid) {//if fid exist then image is saved from URL.
      //$usr_info->picture = file_load($file_info->fid); //for default profile pic
      $usr_info->field_profile_picture[LANGUAGE_NONE][0]['fid'] = $file_info->fid; //for custom profile pic
    }
    user_save($usr_info);
  }


Use node custom field to choose my posts background I'm building my first Drupal 8 theme and I'd like to add the possibility to change the page background header when editing a post.

I've added a custom field in my post type to provide an image to each post. It works, I can add an image and access the image url on my page.

The problem is that I can't find a way to add inline css to my page to add the background-image property.

Here's my code, located in my .theme file :

function hugo_preprocess_page(&$variables) {

  $node = \Drupal::request()->attributes->get('node');

  if($node->field_image_de_fond->entity) {
        $image_url = $node->field_image_de_fond->entity->url();
        $css_code = ".header-bg-home { background-image: url('" . $image_url . "'); }";
        $page['#attached']['css'][] = array(
              'data' => $css_code,
              'type' => 'inline',
              'scope' => 'header'
            );
  }

}

Any help would be really appreciated!

As it's my first D8 theme I'm really not sure about the way am doing that, it would probably be better to write a custom css stylesheet with the image url as a parameter, but I've no idea how to do that. Also, I'm not sure about the \Drupal::request()->attributes->get('node'); in terms of performances.

Why use a preprocess function ? Instead use a template =).

Here is an example of how I achieve this functionality for the content type "Article" + the image field.

node--article.html.twig

  <header class="main-header post-head " style="background-image: url({{ file_url(node.field_image.entity.fileuri)}})"> </header>

I added the image on the header on top of my template and use the file_url to get the image from the field_image.

  {{ file_url(node.field_image.entity.fileuri)}}

This will allow you to get the image URL.

Few wrappers + classes to make it this image as background image. And every node will have a custom image background.


Is there an existing way to make blogs for nodes (not users)? I want to be able to set up blogs (or blog-like things, anyway) on arbitrary nodes -- imagine that you have a content type representing an organization, and that organization's owner can create blog entries about the organzation, its activities, etc.  This would not be a lot of code to write, but I'd sure prefer to use an existing solution than hack a new one together.

Is there anything out there like that?  Any experiences to report about adapting/hijacking the existing blog module for this purpose?  Thanks!

It is a little bit of a learning curve at first but you could use OG Groups for something like this. Make your organization node be a group and add an audience field to blog content type.


How to display form element and label inline This must be simple, but I cannot find the answer.

I want the label and the textfield on the same line. I tried this:

'odt-filter' => array(
  '#type' => 'textfield',
  '#title' => 'Filtra',
  '#attributes' => array(
    'id' => array(
      'odt-filter',
      ),
    'class' => array(
      'container-inline',
    ),
  ),
) ,

but then the class is applied to the input element, not to the item that contains both it and the label:

  Filtra
  <input id="odt-filter" class="container-inline form-text" data-drupal-selector="edit-odt-filter" name="odt-filter" value="" size="60" maxlength="128" type="text">

so that the class has not the desired effect. I can (and I actually did, somewhere else) enclose the form element in a container which I can apply the class to, but since a container is already provided by default, I guess there should be a way to add a class to it... isn't there?

The label placement is something set by the theme you're using, and should be consistent across your site. If all labels are above the corresponding element, you should think twice about changing that position just for one or only a few form elements. If you want all the labels next to the element instead of above, the proper place to change that is in the theme.
But let me answer the question as posed:
There is no need to complicate the document structure by adding container elements for the sole purpose of adding a class. The Form API already wraps input elements with a div, and adds standard classes to these divs, so the trick here is to target the existing div and put your class on that existing div.
You can add your class to the div surrounding the form element by using the totally undocumented property #wrapper_attributes. It is used like this:
'odt-filter' => [
  '#type' => 'textfield',
  '#title' => 'Filtra',
  '#wrapper_attributes' => [
    'id' => 'odt-filter',
    'class' => ['container-inline'],
  ],
] ,

Note this is Drupal 8 so I have changed your example to use short array syntax and I have changed your 'id' attribute to be a string, not an array. You may use both the #attributes and the #wrapper_attributes properties at the same time, in case you wanted to add the class to the div and the id to the input, for example.


How do I override recurring text/strings with icons/images? I'm not sure this is possible or if there is a module that does this already, that's why I am asking :) Think of String Overrides except to turn strings into an image.

I ran into the module Iconify which basically adds icons to the admin config headings, and I was wondering if there is a way to use icons/images to replace specific recurring strings. For example:
Say I would like to change the "View" link on the Page content type into an icon of an eye. Or the "Edit" link into a little pencil.

How can I achieve what I am trying to do?

Drupal allows you to override almost anything and what you are referring to here is the theme()ing of various pieces.  In your specific example, 'View' and 'Edit' are tabs/local tasks on a node page, and they are themed something like this in Drupal 6:

/**
 * Generate the HTML output for a single local task link.
 *
 * @ingroup themeable
 */
function theme_menu_local_task($link, $active = FALSE) {
  return '
'. $link ."
\n";
}

and this in Drupal 7:

/**
 * Returns HTML for a single local task link.
 *
 * @param $variables
 *   An associative array containing:
 *   - element: A render element containing:
 *     - #link: A menu link array with 'title', 'href', and 'localized_options'
 *       keys.
 *     - #active: A boolean indicating whether the local task is active.
 *
 * @ingroup themeable
 */
function theme_menu_local_task($variables) {
  $link = $variables['element']['#link'];
  $link_text = $link['title'];

  if (!empty($variables['element']['#active'])) {
    // Add text to indicate active tab for non-visual users.
    $active = '' . t('(active tab)') . '';

    // If the link does not contain HTML already, check_plain() it now.
    // After we set 'html'=TRUE the link will not be sanitized by l().
    if (empty($link['localized_options']['html'])) {
      $link['title'] = check_plain($link['title']);
    }
    $link['localized_options']['html'] = TRUE;
    $link_text = t('!local-task-title!active', array('!local-task-title' => $link['title'], '!active' => $active));
  }

  return '
' . l($link_text, $link['href'], $link['localized_options']) . "
\n";
}

So, to change this from text to a graphic, you would create a theme function of your own in your theme's template.php file:

function YOURTHEME_menu_local_task(....

that looked at either $link or $variables['#link'] and output an image instead of the text.

And if php isn't your forte, but jQuery is, you could also do it in the browser with something like:

$('.tabs a[href$="edit"]').html('');

which would replace the text of your edit link with an image.  If you went this route you would put this in a suitable drupal behavior wrapper in your theme or custom module as well.


How to display Meta tag description for Views genereated page How to display meta tag description for Views generated page. Title is displaying by views but not description. Even I entered in Views description PFA.

Along with that I tried "Metatag Views Overview" module that gives an error when I created new meta tag.

You need to enable the metatag_views module, that already comes with the Metatag bundle. Once you install it, you will see a new section on the page where you edit views, and you can update description there.

The section is called "Metatags", and there you can override the defaults for a specific view.


Include CSS to module specific template I have a custom module which contains a template directory and a .tpl.php. I would like to add a specific stylesheet for this template. Right now, my tpl-file looks like:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">

  <title>My Title</title>
 <link rel="stylesheet" type="text/css" href="sites/all/themes/mytheme/css/styles.css" />

My content

And it works, but only partially... How can I include the css stylesheet in a more proper (read: more Drupal) way? I've tried the drupal_add_css(), but with no results... But maybe I did it the wrong way. Any suggestions?

In mymodule.info file, add following line:

stylesheets[all][] = css/styles.css

Then, in html.tpl.php be sure to print scripts and styles, like that:

  <?php print $styles; ?>
  <?php print $scripts; ?>
</head>

Failing to output these will break many modules, and make Drupal Core to fallback to non-javascript behavior, and you don't want this to happen.


How do you reorder the shipping services for drupal commerce? There doesn't seem to be a weight option. How would one reorder the shipping services for drupal commerce?

You can use a custom hook to reorder services:

<?php
/**
 * Implements hook_commerce_shipping_service_info_alter().
 */
function mymodule_commerce_shipping_service_info_alter(&$shipping_services) {
  if (isset($shipping_services['my_flat_rate'])) {
    $shipping_services['my_flat_rate']['weight'] = -10;
  }
}
?>

See discussion here: https://drupal.org/node/1537394#comment-7003814

Steps would be create a custom module or add this hook to existing module for your site, set the weight as code above ranging from -10 to 10 and you should be all set till there is a patch or update to overall Shipping module.


How can I pass user real name as a contextual filter in views I am trying to simply provide a view of author content by passing a contextual link for the author ID to provide a URL with the author's name as selected with the Real Name module.

For instance: "/sitename/content-type/realname".

When I set up the filters, the only way I can get it to work is by providing the user name, not the real name as set by the real name module. I would like to keep the login name private, and use the real name as assigned.

Has anyone had any success doing this?

If the real name is stored in one field in your user, you can set up a relationship with the user and then point to that in the contextual filter, eg, here I just created a "real name" text field in the user and then did this:

and then for nice looking urls, did this in the filter:

so I can go to

www.example.com/by-real-name/this-real-name

or

www.example.com/by-real-name/that-real-name

It's really up to you re: case transformation, but two real caveats:  you have to make sure real names are unique AND it gets really squirrelly if and when special characters are in the real name field.


Add Google Analytics JS file to every page We use Google Analytics on each of our sites for our own reporting. We have implemented GA using the Google Analytics module, and everything works as expected.

However, I'm also part of a large organization that wants to start collecting analytics (using GA) on all of its sites. I've been given a .js file that I just need to add to the head of every page.

Should this be added in each site's theme or added to the GA module somehow?

Thanks for taking the time to look...

When I have been in this situation, I use the GA module, look at the JS file that the organization give me, and then update the Code snippet (before) and or Code snippet (after) under the Advanced Settings => Custom Javascript code tab on admin/config/system/googleanalytics as needed.


No results behavior - HTML link I have created a View (for /blog). The blog page is just articles grouped together. Underneath each blog post I'd like "Comments (x)" (x = showing the number of comments).

That part is done, using Rewrite results > Output this field as a link. Link path = blog/[title]#comments

What I would like to do now is when there are no comments, have a HTML link "Comments (add)" which goes to the comment form for that blog post. E.g. blog/[title]#comment-form

Problem:

I haven't been able to create the "Comment (add)" HTML link using No results behavior > No results text (Is it possible?)

I've tried:

add

and many other alternatives. The link becomes

/blog/%3Ca%20href=

Am I on the right track? How do you recommend I go about this?

You may want to investigate Page Manager (Ctools suite).  This module allows you to intercept a URl and create variants based upon conditions (contexts) from the URL call.  Page Manager works very well with Panels which allows you to break down regions in your them into subregions and insert views in the panel.  Panels is fairly easy to use and even if you do not want to include additional sub regions, it combines well with Page Manager to accomplish what you want.  You can find more on how to use Page Manager at nodeone.se
By way of an example  you could create a panel page using Panels or Page Manager (it works the same starting in either module).  If the path were /blog/%blog then the page definition will intercept all /blog/anything URLs.  You could then create two variants, one to act if there are no comments and one if there is. You would then add a layout and include a view for each one.
Another approach might be to use Page Manager variants to redirect a URL request to another location so one could call the View directly and the other could go to the comment form.


Using Drush with ENVVARS I use EnvVars (vhost) to set my MySQL settings so I can have cross-server settings.php file without having to update it 3 different times.

I am wondering if there is a way to get drush to do one of the following.

Read the EnvVars from the VHOST (in which case where so I find the Drush database config gathering stuff).
Override the MySQL settings for pm-update

This is an existing Drush feature request.  See http://drupal.org/node/1848766 and http://drupal.org/node/1335626.

You could also make a bash alias (one per Drupal site) that set the appropriate environment variables, and then called Drush.


How to show the description of primary links Possible Duplicate:
  How can I add a caption to my navigation menu?

I would like to print my primary links description too in my navigation like this website.

The answer in your previous question should help you with this. The $link['description'] will contain the description you set in the drupal menu item via the ui. You can then just print this below the title to achieve your example.

As a side note, you would be best amending your original question rather than starting a new one which is so similar.


Microkernel with low bootstrap level? Drupal 7 had a neat feature of different bootstrap levels that allowed to write really fast micro services that didn't require to fully bootstrap Drupal.

Drupal bootstrap levels no longer exists in Drupal 8, but what would be the best approach to build some kind of microkernel to handle simple database queries? I'd like to initialize the database and configuration to do some SQL queries and send a JSON response.

A lot of the bootstrap process happens now implicitly as services are requested.

If nothing requests the database service then Drupal won't open the connection to it and so on.

The minimal amount of code to do a custom php file that bootstraps Drupal and does some queries can be seen in statistics.php:

$autoloader = require_once 'autoload.php';

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

$views = $container
  ->get('config.factory')
  ->get('statistics.settings')
  ->get('count_content_views');

if ($views) {
  $nid = filter_input(INPUT_POST, 'nid', FILTER_VALIDATE_INT);
  if ($nid) {
    $container->get('request_stack')->push(Request::createFromGlobals());
    $container->get('statistics.storage.node')->recordView($nid);
  }
}

Depending on what it is for, you could also do a normal controller and return a cacheable JsonResponse with the right cache tags and contexts, then Drupal will automatically cache that in the internal and dynamic page cache. Which, depending on your queries, might not be much or not at all slower.


How to change page title of Manage Fields screen based on bundle name? Is it possible to change admin screen page title based on bundle related to the screen. For example, I would like title of admin/structure/types/manage/datasheet/fields page to be Manage datasheet fields. Is it possible?

You need to replace the static title with a dynamic title.

Reference: https://www.drupal.org/node/2067859

This describes how to define dynamic titles for new routes in yaml files. You need to change the existing route entity.node.field_ui_fields in a route subscriber:

$route->setDefault('_title_callback', '\Drupal\mymodule\Controller\MyController::getTitle');

Reference: https://www.drupal.org/docs/8/api/routing-system/altering-existing-routes-and-adding-new-routes-based-on-dynamic-ones


Different image width on a node and on block I noticed that there are differences in the way inline images are displayed when added to 'Body' of the 'Basic Page' and 'Body' of a 'Basic block'. In the first case the image is internally scaled down to match the width of the container (added attribute 'width=909' [screenshot 1]) whilst in the second case the image spills out over the element [screenshot 2]

I looked at image styles and field display options but couldn't figure out what is causing this behaviour. I'd like to preserve the scaling of the 'Basic Page' for the blocks. Has anyone else come across this issue? I'm running Drupal 8.1.9.

EDIT 1:
 @Smalution I checked the region width, too. Both 'region-content' and my custom region are 940px wide (descendants of 'col-sm-12')

You can always make the image fit the container with CSS.

For example:

.block .content img {
  max-width: 100%;
  height: auto;
}

If you're using Bootstrap, you can achieve the same effect by adding the class img-responsive to the image.


generate commerce coupon bulkly Is there any way to generate Drupal commerce coupon code bulky?
I found commerce_coupon_batch module but it require Commerce_coupon_ui module that there is not exist in sub module of  commerce_coupon version 7.x-2.0-beta1.

I don't try anything yet, How can I generate coupon code bulky?
I look at db and found there is a table for coupon ,commerce_coupon is just sufficient to add record to this table programmatically?

I try below code to create one coupon , but nothing added to coupon list in admin/commerce/coupons :

$No=$form_state["values"]["code_NO"];
    $type_id=$form_state["values"]["type"];
    $record['type']='discount_coupon';
    $record['code']=commerce_coupon_generate_coupon_code($type_id);
    $record['commerce_discount_reference']['und']['0']['target_id'] =$type_id;
    $record['commerce_coupon_conditions']['und'][0]=Array('condition_name'=>'commerce_coupon_usage_evaluate_usage',
            'condition_settings' =>Array( 'max_usage'=> 1),
            'remove_condition'=> 'Remove',);
ym(entity_get_controller('commerce_coupon')->create($record));

I think your code is good but you forget save entity .I hope this get clue to you to achieve your job.

$No=$form_state["values"]["code_NO"];
    $type_id=$form_state["values"]["type"];
    $record['type']='discount_coupon';
    $record['code']=commerce_coupon_generate_coupon_code($type_id);
    $record['commerce_discount_reference']['und']['0']['target_id'] =$type_id;
    $record['commerce_coupon_conditions']['und'][0]=Array('condition_name'=>'commerce_coupon_usage_evaluate_usage',
            'condition_settings' =>Array( 'max_usage'=> 1),
            'remove_condition'=> 'Remove',);
$entity=entity_get_controller('commerce_coupon')->create($record);
commerce_coupon_save($entity);


minihtml is not compress output I am using the Minify HTML module to compress the HTML output. Once, I enable this module and view my node page, the HTML is not compressed. Is there any additional setting for this?

Remember what this module does is:

This module removes all the whitespace in your HTML except those between TAGS.

It will not compress all your HTML into one single line.


How to change the 'Name' label on term add/edit pages programmatically? In Drupal 7 this was pretty easy. But now when I try to change the term name label on the term add/edit form all I find are protected methods.

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id == 'taxonomy_MYVOCABULARY_form') {
    ksm($form['name']);
    // ?????
  }
}

This is no translation issue.

If you mean you want to change the title of the form element, then it is basically the same as it was in 7.x.

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'taxonomy_MYVOCABULARY_form') {
    $form['foo']['#title'] = t('New Title');
  }
}

Adding in what 4k4 said... field widgets behave differently than general form items:

$form['name']['widget'][0]['value']['#title'] = 'New Title';


Comment form above comments? Is there a simple way to move the comment form above the comments in Drupal 6?

You can use the Comment form above comments module which adds option to place comment form above the comments thread.


Create jump menu with more options using programmatically I am using Drupal 7 and CTools. I want to create a jump menu using Ctools. I have checked the example code provided in the Ctools module. And it is working fine for one link only.

How do I add more links in Jump menu:

In the code shown below, look at here: $url = url('mypostings/groupsort'); I want to add more links in the jump menu,like url('mypostings/test1'), url('mypostings/test2') etc..

/**
 * Implementation of hook_menu();
 * @return
 */
function post_display_menu() {
    $items['mypostings'] = array(
            'title' => 'My Posts in Group',
            'page callback' => 'get_my_postings',
            'access callback' => TRUE,
            'expanded' => TRUE,
    );
    $items['mypostings/groupsort'] = array(
            'title' => 'My Postings Filter',
            'page callback' => 'get_my_posting_filter',
            'access arguments' => array('access simple page'),
    );
    return $items;
}

function get_my_postings() {
    global $user;
    // Include the CTools tools that we need.
    ctools_include('ajax');
    ctools_include('modal');
    // Add CTools' javascript to the page.
    ctools_modal_add_js();
    $header = array(
            array('data' => t('Title'), 'field' => 'n.title'),
            array('data' => t('Created'), 'field' => 'n.created'),
            array('data' => t('Author'), 'field' => 'u.name'),
    );
    $query = db_select('node', 'n');
    $query->leftjoin('users', 'u', 'u.uid = n.uid');
    $query->fields('n',array('title', 'created'))
    ->fields('u',array('name'))
    ->groupBy('n.nid');
    $result = $query->execute();
    $rows = array();
    foreach ($result as $row) {
        $rows[] = array('data' => (array) $row);
    }
    $build['tablesort_table'] = array(
            '#theme' => 'table',
            '#header' => $header,
            '#rows' => $rows,
    );

    drupal_add_js($sample_style, 'setting');

    ctools_add_js('ctools-ajax-sample', 'ctools_ajax_sample');
    ctools_add_css('ctools-ajax-sample', 'ctools_ajax_sample');

    $output .= $build;

    // Create a jump menu
    ctools_include('jump-menu');
    $form = drupal_get_form('post_filter_jump_menu_form');
    $output .= '<h3>'. t('Jump Menu') .'</h3>';
    $output .= drupal_render($form);

    return array('markup' => array('#markup' => $output));
    return $build;
}

/**
 * Helper function to provide a sample jump menu form
 */
function ctools_ajax_sample_jump_menu_form() {
    $url = url('mypostings/groupsort'); // I want to add 3 links in jump menu How can i add it
    $form_state = array();
    $form = ctools_jump_menu(array(), $form_state, array($url => t('Sort')), array());
    return $form;
}

See below code !

$form = ctools_jump_menu(array(), $form_state, array($url => t('Jump!') , 'http://www.google.com' => 'Go to google'), array());

OR

$options = array();
$options[$url1] = $label1;
$options[$url2] = $label2;
$form = ctools_jump_menu(array(), $form_state, $options, array());

Third argument of ctools_jump_menu is $select which is

  An array suitable for use as the #options. The keys will be the direct
  URLs that will be jumped to, so you absolutely must encode these using
  url() in order for them to work reliably.


Exporting Custom Menu Translation Question: How do I export/import translation of Custom Menu Items

I have a module that takes all the .po files for custom strings and then uses locale to batch import them. This works great.

I was wanting to translate my custom menu links, but when I search for them in the translate interface (or searching the .po from exporting my translations) I am unable to find any of the menu items.

I've included my admin/config/regional/content-language settings below so you can see that Custom Menu Link (and it's menu link title) is ticked.

I am able to translate the menu items only by going to admin/structure/menu/item/#/edit/translations, but this isn't (seemingly) exportable in either the .po files (via locale export), nor the config management system (via drush cex).

Anyone know how to do this? Thanks in advance.

So what I ended up doing was to create a module that reads from a json file, and adds the translation. (Import controller + drush command)

a) Load up the custom menu items by menu name:

$main_menu_items = \Drupal::entityTypeManager()->getStorage('menu_link_content')->loadByProperties(array('menu_name' => $menu_name));

b) Go through your menu items, foreach of them check if your menu link title matches one in your json/po file/config.

c) Check if you already have a translation on that menu item, then remove the old translation or skip.

if ($menu_item->hasTranslation('fr')) {

d) Finally add the translation that exists in your file.

  $menu_item_fr = $menu_item->addTranslation('fr');
  $menu_item_fr->title = $translation_json[$menu_name][$link_title];
  $menu_item_fr->description = '';
  $menu_item_fr->save();

This is essentially what my json looked like:

{"menu_name": {"english_link_title":"french_link_title"}}

Do hope this helps someone else, or someone can think up a better answer.


Can I use hook_css_alter inside of hook_form_alter Can I use hook_css_alter inside of hook_form_alter. I need to unset a css file only on certain forms and only to non-admins. This is what I have but it doesn't work.

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Session\UserSession;

function mymodule_form_alter(array &$form, FormStateInterface $form_state,  $form_id) {
  $user = \Drupal::currentUser()->getRoles();
    if(in_array("administrator", $user)) {

    function mymodule_css_alter(&$css) {
      unset($css['core/themes/stable/css/system/components/tabledrag.module.css']);
    }
  }
}

You can't use a hook function inside of a hook function. If you are in the css alter hook you have to get the information you need from where you are in code. For example you could check for the route name of the form because the current route match is available in a service. So this could work (not tested):

function mymodule_css_alter(&$css) {
  $user = \Drupal::currentUser()->getRoles();
  $route = \Drupal::service('current_route_match')->getRouteName();
  if (in_array('administrator', $user) && $route == 'entity.node.edit_form') {
    ...


Use another field value as condition in Entity Query I'm performing in Drupal 8 an entity query that searches for nodes that have not been changed since x days, where x is a numeric node field (node.field_days).
So I would like to perform a query like:

$query = \Drupal::entityQuery("node")
  ->condition('changed', strtotime('-node.field_days days'), '<=');

I know that condition takes as value a string and not a db column, but is it possible to use entity query with a dynamic value?

The entity query is a powerful and convenient tool to query for content and config entities that have certain properties/field values/field references.

Yet, it has its limitations. Comparing two fields is not possible using the generic entity query and its condition method.

For such a task, you may need to use the more low level dynamic (select) queries and its where method. An example for your use case:

$connection = \Drupal::database();
// Query node base field table.
$query = $connection->select('node_field_data', 'n');
// Join with the `field_days` field table.
$query->leftjoin('node__field_days', 'd', 'd.entity_id = n.nid');
// Query for the node ID.
$query->fields('n', ['nid']);
// Your condition (a day has 86400 seconds; we multiply them with
// the value of the field_days field, add them to the changed
// timestamp of the node and compare it against the current time).
$query->where('n.changed + (d.field_days_value * 86400) <= :now', [
  ':now' => \Drupal::time()->getCurrentTime(),
]);
// Optional sorting.
$query->orderBy('n.changed', 'DESC');
// Fetch results.
$result = $query->execute()->fetchAllKeyed(0, 0);

Above example assumes:

that you used a numeric field type for field_days, so its database stored value can be multiplied with seconds without any casting,
that the field_days field allows one value only, so we can safely ignore field deltas when joining,
that field_days is present on all nodes/bundles and has a valid value,
that you use one language only in your site/the field_days value is not translatable, so we can also ignore langcodes.

You may have to alter the query accordingly, if any of these assumptions is not true.


Drupal Redirect User Login Page Basically I need to redirect this page

http://website/?q=user
to
https://website/?q=user

I tried adding a redirect rule to the .htaccess file in /var/www/html/ but that didn't work. From what I know ?q=user is more of an argument then a page. How can I achieve this?

Any help would be greatly appreciated.

You might want to have a look a the Secure Pages module, which is:

  A small process which will redirect the required pages to a SSL version of the page.

You can easily set up the user/login path as an SSL-required page, and the redirect will be handled for you.

If you want to do it manually, a rule like this in .htaccess would probably work:

RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^user$ https://%{SERVER_NAME}/user [R=301,L]

That would need to go above Drupal's main rewrite rule for index.php.

It's worth bearing in mind you'll need to do this for the user/login path as well as that can be accessed directly.


Migrating Drupal 6 to pressflow? After a lot of mysql tunings, I intend to use Varnish as the last resort to improve my D6 site's performance which has become increasingly sluggish. I realized that Varnish will not work with D6. And due to lack of som contrib modules, I still can not migrate to Drupal 7 which, as I understand, makes migration to Pressflow pretty redundant.

I am using nginx + php-fpm as web server and try to avoid Apache at any cost. This approach has of course its downside, for example I could not make use of Boost module. Now my question is that whether pressflow works with my web server configuration? and whether migration is a good idea performance-wise? And Pressflow suites me, where can I find docs to make a smooth migration on Ubuntu server.

Thanks for your suggestions.

I have a client who takes deliveries in the form of the sites/ folder and a database backup, and installs them in Pressflow.  As long as the Pressflow version isn't older than the Drupal version, we have never had problems.

There is no real migration.  Just replace the files, run update.php, and move on.  Two minor gotchas, though.

Pressflow error reporting is different, and a lot (and I mean a lot) of E_NOTICE will end up in the dblog.  You may want to adust error_reporting to exclude these.

Pressflow is API compatible with Drupal, but I have run into situations with anonymous sessions.  Occasionally, I need to manually call drupal_start_session, which is in Pressflow 6, from a custom module before I start doing stuff with $_SESSION.

Personally, I would give Zend Server CE a shot, too.  The Pressflow 6 site that I am wrapping up really flies in this environment.


Omega theme node template renders outside any regions The node template should render within the content region or at least should be replaced by the node template. But I am finding that it is not rendering within any regions, but it does rend within the content zone.

Now to be fair, Omega works correctly on a different site that I am working on. Just not here. At first I thought it was the sub-theme that was jacked. But I created a brand new empty one and it had the same problem. I also tried using the Omega base theme as the theme and had the same problem. So now I am at a loss as to what is causing this.

On my other site I tried to add the Delta module to see if that affected it, but no dice. So either another module is breaking it or something else is wrong in the config.

Do you have any idea?

I had the same issue. It turned out I had the "main content" block visibility settings set to "Only the listed pages," but I had no pages listed in the box below.

So, (of course) it did not render.


Output form result after form_submit I have custom module, where after form_submit, i do some calculations, and get result of those calculations in a variable.

After i hit "submit", i can output those calculations with drupal_set_message , but i would like to format results (array), and print it bellow the submit button. How can i output resulting variable bellow the form or in the form, after submission ?

function mymodule_form_submit($form, &$form_state) {

$a=$b+$c;

// on submit, i would like to print/format $a on the reloaded form page

}

Thanks!

What you want to do is use something like $form_state['temporary'] in your myMod_submit function. Set $form_state['temporary'] = $someValue and rebuild your form. You also want your myMod_form function to have a place holder for your data. When the form is loaded, simply check to see if your temp holder is populated. if it is then you know you have a result and display it.

See code below.

function myMod_form($form, &$form_state) {

    ...

    if(!empty($form_state['temporary'])) {
        $form['results'] = array(
            '#type'     => 'item',
            '#markup'   => $form_state['temporary'],
        );
    }

    return $form;
}

function myMod_submit($form_id, &$form_state) {
     ...

     $results = callSomeFunctionToGetResults();

     $form_state['temporary']   = $results;
     $form_state['rebuild']     = TRUE;

     ...
 }

i omitted all my code that would populated $results but this should get you to where you need to go.

quick addition here.

I just realized that you wanted it to go to another page and not the same page. I believe in your myMod_submit function you can use drupal_goto(). pass it a url and also pass it some options. you can then parse out the options as your values in the other page. See drupal_goto. however, i haven't tested this option out.


Using the Drupal 7's Block "description" field as a CSS class field I need to add a css class to my blocks and I know I can install a module, but i rather not as it doesnt work with features. I was thinking of just using the block config's description field to hold my css classes and just output it in my block.tpl.php file or should i do a preprocess thing?

Now the question is what is the variable to output the block's "description"?

If I understood your question correctly, you have two options:

A) Use a _preprocess_block() function:

function THEME_preprocess_block(&$vars) {
  // Make sure that this is a custom block, and not a block that is provided by
  // a module.
  if ($vars['block']->module == 'block') {
    // Load the block information.
    $info = block_custom_block_get($vars['block']->delta);
    // Add block description to the list of classes.
    $vars['classes_array'][] = $info['info'];
  }
}

B) Use the Skinr module. Probably will require more work, but it's much more flexible and editors / non-tech staff will be able to define styles of blocks. From the project page:

  Skinr's main purpose is to allow the theme to define a set of reusable and modular CSS styles, and to make those styles available in Drupal's UI.


commerce_display_path is relative and doesn't work from Order page I'm trying to create a link from the Order view back to the product page so a customer can order it again. I've added a field to the view to load commerce_display_path (and set it as hidden) then another field that is some metadata about the original purchase (the line item is customised and I'll get the product page to read that url and repeat the customisation). That field uses rewrite rules for display like so

Reorder

However the commerce_display_path is relative so I end up with a URL like node/6?bundleId=71398558 and when used from the orders page the browser sees http://127.0.0.1:8080/drupal/user/142/orders/node/6?bundleId=71398558, which is useless.

If I manually put a / at the beginning of the a tag it will get the wrong url because in my test environment drupal is running as /drupal. I could put /drupal in but I think there should be a better way to get the sites base url into the rewrite rules.

I'm not sure where your second token is coming from, but assuming that's part of the View as well, why are you rewriting the link directly with HTML instead of using the "Output this field as a link" code that's designed to accept Drupal paths and generate appropriate absolute URLs from them? That's what I'd do or else I'd look into rewriting the commerce_display_path field as well to make it work.


How can I enable/disable programatically added fields from a custom module? I'm trying to create a custom module for payment. When installed, the module automatically adds two fields to the 'Article' content type.

I have 'enable/disable checkbox' in the form:

Enable: Should mean that people on my live website can use it

Disable: Should mean that no-one can use it (I don't want to remove the variables or the fields in the article content typ, I just want to hide everything in relation with the module)

Is there any hook or any thing that can do that?  Turn the module off?

You should try module_disable(array) function.
Here is the documentation for it.
Module Disable Programmatically

You should first check its existence by module_exists and you can also have a look at drupal_uninstall_modules.

I hope this will help you.


How can I set the site root page to a landing page instead of user login? I'm using a custom bootstrap 3 theme as my default theme which sets the user_login page. When I go to the root of my site, this is the page that appears. How do I change the root of my site to display a page other than user_login?

Specifically, we are trying to add a landing page and we would like https://oursite.com/ to display the landing page instead of the login page (which is also accessible thru https://oursite.com/user/login)

All the suggestions I've seen so far just say to create a node and redirect to something like https://oursite.com/landing, but we would like http://oursite.com/ to be the landing page instead of having to redirect to another page.

Under /admin/config/system/site-information simply set a default front page which can be a node /node/123 a Views page /my-view or any other custom page /foobar/landing-page.

If you leave this empty it falls back to /user/login (which when you are logged in redirects to your user page).

To have the "Promoted to front page" setting in nodes respected set the default front page under /admin/config/system/site-information to /node. This is the path to the front page View you can edit yourself. This view by default displays node teasers and respects the "Promoted to front page" and "Sticky at top of lists" flags. You can have multiple nodes at the same time to be promoted and/or sticky.


Override nodereference_autocomplete functionality I would like to edit the functionality contained in nodereference_autocomplete() so that it will only return a subset of all nodes. What would be the best way to override this default functionality?

This isn't exactly the same question, but I think this answer is just as valid.

  If I understand you right, you can use a View as the source for the nodereference widget, and give it appropriate filters to only show nodes of a certain type authored by the current user. Or have I got the wrong end of the stick?!