Sub-sub Theme Not Inheriting CSS I am trying to extend the Thunder Admin theme by creating a sub-theme in it. This is my first time making a sub-theme in Drupal 8 (other than from bootstrap starter kits).

I would have thought that a basic sub-theme would have inherited the css and js from its parent as is explained here

All I can see that I should need to do is to create a directory i.e. my_theme and create my_theme.info.yml and my_theme.libraries.yml.

The content of this file is as follows:

my_theme.info.yml

name: My Theme
type: theme
core: 8.x
base theme: thunder_admin
description: 'Extends Thunder Admin'

libraries:
  - thunder_admin/global-styling

regions:
  header: 'Header'
  pre_content: 'Pre-content'
  highlighted: Highlighted
  content: Content
  page_top: 'Page top'
  page_bottom: 'Page bottom'
  sidebar_first: 'First sidebar'
regions_hidden:
  - sidebar_first

my_theme.libraries.yml

global-styling:
  css:
    component:
      css/style.css: {}

Can any one please explain to me where I am going wrong please?
I have flushed every cache I can think of

Can any one please explain to me where I am going wrong please?

libraries:
  - thunder_admin/global-styling

There is no need to load the base theme's library, so this needs to be your theme's library.

libraries:
  - my_theme/global-styling


How do I fetch the user ID from the shipping profile? I'm trying to get the User ID from Shipping Profile in Drupal Commerce using the following code, but eventually, $entity->getOwnerId() is returning me NULL in any case, if it's an authenticated user or admin it's giving me 0 as the UID.

function mymodule_entity_insert(EntityInterface $entity) {
    if ($entity->getEntityTypeId() === 'profile') {
        /** @var \Drupal\user\Entity\User $user */
        $user = User::load($entity->getOwnerId());
    }
}

Shipping and billing profiles don't have a user ID, they are always anonymous because they belong to the parent entity (order/shipment), not the user.

Only address book profiles have user IDs.


How do I hide the download button on the audio player? I want to hide the "download" button on the audio player provided by the Media module in Drupal 8.  How can I do that?

Create a subtheme if you haven't already.
Find the file core/modules/file/templates/file-audio.html.twig and copy it to your subtheme's templates directory.
Edit the following line in the file.

Original line:

<audio {{ attributes }}>

Change it to this:

<audio {{ attributes }} controlsList="nodownload">


Where do I put configuration files for testing? Hopefully, this will be a simple question.

I am writing a kernel test for a class, called FooConfig, that reads from a configuration file. For the purpose of facilitating this test, I need a configuration YAML file that exists purely for testing.

So the question is: is it best practice for this configuration file to live under config/install, or should it exist within the /tests directory?

One way is to create a small testing module that contains specific config you need for a test, then have the test use it as a dependency. In my case, I put that module itself under the tests directory and marked it as hidden in its info file.

Although a drawback would be keeping these config files up to date when the system changes - but failing tests should point you in that direction too.

For Kernel tests be sure to call and install the test modules config.


Limiting Views diplays to a role — two displays are stuck together I have a View with two displays, one for role1 and one for role2. When I set the access control for the first display to role1 and save the View, then set the access control for the second display to role2, it changes the first display to only be accessible to role2 as well. Have I encountered a bug, or could there be some set of configuration options causing this?

When you set the persmissions for a display, the following popup box shows up

below the title, there's an option that allows you to change the access restrictions to "All displays" or "This page(override)"


User images slideshow: first slide from reference entity I wish to do a slideshow with a first slide of my node picture and then others slides with pictures submitted by users (affiliated to a node via entity reference).

What I want to do is (Node Entity Reference Image) (userA pic1) (userA pic2) (userA pic3) (userB pic3).

I edited a view template

content(image) goes here

    <?php foreach ($rows as $key => $row): ?>

        <?php print $row ?>

    <?php endforeach ?>

How can I output my "field_passager_image" defined by relationship to Content entity referenced from "field_passager_id" passed through an url argument (node id from url) ?

Found a solution here using view field views module by putting my user entity field view inside my node entity view.


How can I automatically flag new comments? I have a Drupal 8 site with Flag and Rules modules. How to flag a new comment ?
I want that when a user creates a comment, the comment should be automatically flagged.
I created a type of Flag on the comments and I created a rule with the event "When a new comment is posted".
What should I put in action ?

Flag ID should be the ID of the flag being set. If you go to /admin/structure/flags, and Edit the flag, the machine name/ID of the flag will be at the end of the URL -- so /admin/structure/flags/manage/{flag_id}.
I've not used Rules on D8, but for Entity ID, if you click "switch to data selection" and then click the field, I think it should give you some autocomplete options to help select the data you want. You'll likely end up with something like "comment:id".


Define node array id as parameter in routing Is that possible to send somehow an array of nids and automatically convert it into and array of nodes? Something like:

custom.custom_nodes:
  path: '/custom/{nodes}'
  defaults:
    _form: '\Drupal\custom\Form\CustomForm'
    _title_callback: '\Drupal\custom\Form\CustomForm::titleCallback'
    nodes: []
  requirements:
    _access: 'TRUE'

Then I call this: /custom/1+2+3

And I will get at the backend an array of loaded nodes, which id's is 1, 2, 3.

If yes, how do I need to separate the nids from eachother? (And what else do I need to do?) Are there any best practice right now for this? What do I need if I need just an array of ids?

A custom parameter converter would probably be the best solution.

It's quite easy to implement; + symbols tend to be quirky in URLs so this example uses commas instead:

MODULE/src/ParamConverter/NodesConverter.php

namespace Drupal\MODULE\ParamConverter;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\Routing\Route;
use Drupal\Core\ParamConverter\ParamConverterInterface;

class NodesConverter implements ParamConverterInterface {

  protected $entityTypeManager;

  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  public function convert($value, $definition, $name, array $defaults) {
    // Add whatever extra validation you feel is necessary here
    $nids = explode(',', $value);

    if (!empty($nids)) {
      return $this->entityTypeManager->getStorage('node')
        ->loadMultiple($nids);
    }
  }

  public function applies($definition, $name, Route $route) {
    return !empty($definition['type']) && $definition['type'] == 'nodes';
  }

}

MODULE/MODULE.services.yml:

services:
  module_nodes:
    class: Drupal\MODULE\ParamConverter\NodesConverter
    arguments: ['@entity_type.manager']
    tags:
      - { name: paramconverter }

MODULE/MODULE.routing.yml:

custom.custom_nodes:
  path: '/custom/{nodes}'
  defaults:
    _form: '\Drupal\custom\Form\CustomForm'
    _title_callback: '\Drupal\custom\Form\CustomForm::titleCallback'
    nodes: '[\d\,]+'
  requirements:
    _access: 'TRUE'
  options:
    parameters:
      nodes:
        type: 'nodes'

The regex for the route could probably be improved, the param could be made optional, etc; other than that it should work. The controller for the route at /custom/1,2,3 will receive an array of loaded nodes for the same IDs in the $nodes argument (or an empty/smaller array if none/only some were found).


Using the web interface or using Drush cause different result? What is the difference executing an upgrade from Drupal 6 or 7 to Drupal 8 using the web interface or it's better to use Drush?

If the database is heavy, using either of them would have different result?

From the technical perspective, the PHP configuration can be different for web server (Apache) and when running from CLI (drush), since different php.ini is loaded, therefore different limits are applied, sometimes your PHP could be different.

If you're non-technical person and it's one time (simple) process, it's better to use web interface, which is recommended way to upgrade your Drupal. The size of database doesn't make any difference, since the batch operation can perform long operations, but it may fail in the middle if you lost your connection.

On the other hand if you're repeating the process many times in order to test it properly, Drush may be a better solution, since you can test the process in more efficient and consistent way especially across multiple environments, this is especially useful if you've continuous integration in place (such as deployments).

So it's really depending on your needs.


Admin account has it's own log in form and should not be able to log in in default log in form I have this certain problem which I don't know how to start doing this thing.

In drupal we have a log in form (let's call it normal login form) which all users can log in including admin.

So what I want is, to create a log in form for admin only. Which I already made it.

But the problem lies here, the normal login form should not let the admin proceed if the admin log in at the normal log in form

Here's a screenshot for it.

As you can see, that's the normal log in form. If the admin logged in to that, it should not let them proceed since they have their own log in form. All I want is only normal users can access can log in in this form.

Any possible solution for this?

You could implement hook_form_alter or hook_user_login() to check the roles of the user logging in and deny if the user is an administrator. Check the Examples module for uses of hook_form_alter and other contrib modules like Legal and User Auth API are practical examples of extra validation and control during user authentication.


Delete workflows / individual states Strangly I seem not to be able to delete an existing workflow as a whole, nor a state within a workflow. The admin user has all the necessary permission. No content type is assigned with the workflow. What do I not see?

In Drupal 8 (at least), there is a "Clean up" tab in the main configuration screen of the module (/admin/config/workflow/workflow), where you can delete inactive states.

In my case, I suddenly stopped seeing the "Actions" buttons, so the only thing I could do was activate/disactivate the states.

That may solve someone's problem...It solved mine


Drupal 8 Webform Composite fieldset Is there a way to add fieldsets inside of a custom composite? Not looking to add anything repeatable, just simply group the fields together.

This get's the fieldset to show but I don't know how to add fields as children.

$elements['grouped_fields'] = [
  '#type' => 'fieldset',
  '#title' => t('Grouped Fields')
];

Place the fields inside of the fieldset:

$elements['grouped_fields']['field1'] = [
  '#type' => 'textfield',
  '#title' => t('Field 1'),
];
$elements['grouped_fields']['field2'] = [
  '#type' => 'textfield',
  '#title' => t('Field 2'),
];
// ...


Managing user disk space I need a mechanism for managing users' storage space.  I have multiple content types with file upload fields.  Admin should be able to set it globally, or per individual user.

My initial approach is to add a field in the admin configuration menu, for admin to set the default limit, and a field for users for individual space allocations.

When a user goes to create new content, I check their used space to see if they are maxed out.  Then when they are about to upload a file, I'll check the file size and see if it will put the user over the limit.  If not, I let the upload occur.

The Drupal API gives us a file_space_used() function, which gives the total file space used by a particular user, so that's pretty cool.

Am I on the right track?

EDIT AFTER ANSWER: syd asked me to post my script, and I forgot.

function mymod_file_validate($file)
{
    global $user;
    $ulimit = 0;    // user limit

    // get the limits per role (I had two to check against, and vals are
    // in megabytes (hence the *1000000))
    if (array_search(HL_ROLE_REG, $user->roles))
        $ulimit = variable_get(HL_VARKEY_REGSPACE) * 1000000;

    if (array_search(HL_ROLE_PREM, $user->roles))
        $ulimit = variable_get(HL_VARKEY_PREMSPACE) * 1000000;

    return (file_validate_size($file, 0, $ulimit));
}

Drupal does all the work.

I made a call to file_validate_size() in my hook_file_validate() handler.  I also made an admin form to modify each role's allowable space (using variable_get/set), and it works great.

Next step is to create a table containing non-default values (keyed by uid), and an admin tool to set individual users' allowable space.  I'll then update my hook_file_validate() handler to check for the user in that table.  If not, then check the default.


Is it good idea to install modules, which require server config, locally? How? There are few modules which require server side config to work. If you have a hosting and domain, it is not a big problem, but if you are developing locally, then I guess it is a problem.

If you somehow install and use these type of modules on local environment to test, you have to change the config once you move to production. For example Node.js integration, Twitter and other modules which require a setup before you can use them.

I am using acquia dev. I want to test some modules before going live as I mentioned above, but my question is how I can do that?

Note: Using such local environment is for me a way to reduce the cost of testing, since I wouldn't have to purchase hosting for that during a few months. In some cases, nobody would want to purchase a hosting and waste few months or a year for just testing.

The problem is having different configuration in in different environments (production, staging, local dev, etc).

Usually you have production. This is the main site. You have to move it to staging or development environment. Moving implies usually to get the production database with all new added content. But in dev environments you need some changes:

Enable development modules like devel, https://www.drupal.org/project/reroute_email, etc.
Change settings. For example, if your site uses a webservice you may change the endpoint URL to a dev webservice URL. Those settings sometimes are jsut Druipal variables but they may be custom settings stored in a module's custom tables.
Clean sensible data: user emails, user personal data like medical data, confidential content that should not be leaked, etc.

You can:

Override variable in settings.php

As @Jaypan said in comments override $conf['VARNAME'] in settings.php. This allows to easy variable override per environment.

To have more flexibility you can use Drupa 8 strategy: have  acommon settings.php in source code control  with all common config for all environments and at the end of the settings.php file load a settings.local.php wuth the per environment settings. Typically here you can a have BD config, config to access other service like your node.js, etc.

To do this add this code in your settigns.php.

# Load environment managed conf.
$conf_path = conf_path();
if (file_exists(DRUPAL_ROOT . '/' . $conf_path . '/settings.local.php')) {
  include DRUPAL_ROOT . '/' . $conf_path . '/settings.local.php';
}

Modify environment

Previous solution works but sometimes you need to change more than internal Drupal variables. In that case you should set up a mechanism to execute setup code in your environment. For example you may want to make sure that in your staging or local environment Stage File Proxy is enabled. You can't enable a module directly in settings.php. Also, you may need to execute a query to sanitize data.

In this case there are several options to change things according to environment:

Using hook_init implementation

hook_init is a Drupal hook that is called on every non-cached request. Here you can place code that checks some condition in your environment and changes it if needed. This solution is simple to implement, but because the hook implementation is called on every non-cached request the checks performed should be very also simple or you may hit a performance penalty.

Also, you can use hook_boot, that's executed on every request, cached or not. You have to be very carefully with this hook because of performance and because is called during Drupal bootstrap and before the theme, modules, or most include files are loaded into memory.

Creating a custom drush command

Drush allows to create custom commands. At the end, they are just PHP code executed in the Drupal context, so all Drupal functions are available. You can create a custom drush commands that performs the environment check. From here you can enable modules, perform sql queries or any other action Drupal allows.

This command should be executed when the database is loaded into the dev environment, just once. Because of this, there's no problem if the command is resource intensive as it's only executed once.

Extending drush sql-sanitize

This drush command sanitizes the database, setting same password for all users and modifying their address. You can extend it to make more tasks like executing SQL queries.

Script with drush commands

Write a custom sfript with drush commands that modifies the environment. This soltuions is simple but alloww you to make any modification done by a drush command.

For example:

drush en devel -y
drush vset myconf my_dev_value
drush sql-query "MY AWESOME QUERY"


Drupal 7 - Dynamic Allowed Values Field Widget I have a project I'm working on where each content manager/author would have a different set of allowed values on a select input for each node created.  Is hook_form_alter the best method for me to dynamically generate the options?  And what would the syntax kind of look like?

You might get it to work like so:

Use the Select (or other) module, and
Integrate it in a form or module using a Forms API element.

More details below ...

About this module

Here is an excerpt about the Select (or other) module from its project page.

  Provides a new Forms API element which is a select/radios/checkboxes element that has an 'other' option. When 'other' is selected a textfield appears for the user to provide a custom value.

So basically you could "start" from a few options (Option 1, Option 2, Option 3), and whenever somebody needs another one (not in the list yet), they just enter "Option 4". Here is a sample about it:

Integration in a form or module

By only using the module as delivered, you wouldn't have a different set of options yet for each author. But the Select (or other) module can be integrated in any form or module, as shown also in the usage example within the Community Documentation of this module.

By enhancing that usage example to make the values for value_1, value_2, value_3 depend on each user, you should get it to work.


Language pages are triplicated Our website was developed with Drupal and we only have a small set of Spanish language pages on a primarily English website.

My question is, I'm getting THREE pages generated for every one page:

.com/node/11
.com/espanol/node/11
.com/conveniences/gift-cards -- all of these use the same English content.

The dev team says this is working as intended as long as there is no Spanish content, we get a Spanish URL as well.

We apparently have 3x the pages now because of this.

Is there something we can do?

As already stated in comments, you have one page but more than one link/path to access it. From the SEO perspective it is something to consider, eventhough Drupal "knows" this is the same content.

The /node/11 is the base URI for your English content, you can't be without it, it's a Drupal internal.

/conveniences/gift-cards is the path alias of the /node/11. It is usually created with the help of Path or Pathauto modules to improve the URIs for better UX and better SEO. They're usually coupled with Global Redirect or Redirect modules that automatically and permanently redirect to the alias. This way search engines only ever see one URI for this content.

/espanol/node/11 This link comes from Multilingual features, actually the specific way you have them configured. It's important to distinguish two independent parts of the website that can be translated: Interface and Content. Roughly speaking, Content is what usually goes into a node, and Interface is everything else surrounding the node.

Multilingual sites need a way to determine which Interface language to display, and which Content exactly when a request is made (a link clicked). Usually this is done by constructing links that contain both information. The language prefix is being used to determine the Interface language, and what follows it is a normal path to some content.

The /espanol/ is the language prefix and is telling Drupal to display the interface in Spanish language. /node/11 is the content path and is telling Drupal to pull the contents of node 11 from the database. When you put that together you have Spanish interface, but you're looking at English content. This might be the case for a Spanish translator: they are using their native language as the default interface language, but they might want to edit the English content.

In D7 every translation is a new node, but in D8 all translations of the same node share the NID, so some configuration might differ there.

Multi-Language Link and Redirect (MultiLink) module can help with some multilingual link handling, automatically changing the output of links to point to the translation of the content based on the current interface language, so you don't mix interface and content languages, unless you create it like that on purpose in menus.

The way to correctly tell search engines about pages being translations of one another is through hreflang: Hreflang.


Cannot login to my Drupal site A while back I made a site for our Operettic society in Holland, after a while I transferred the maintenance to another person who came just recently back at me with a problem.

The site is stuck in maintenance mode, and also the /user/login doesn't work, I also tried the ?q=user possibility, but this also didn't work.

Also made the following query to the database:

UPDATE variable SET value = 's:1:"0";' WHERE name= 'site_offline';
DELETE FROM cache WHERE cid = 'variables';

Anyone some thoughts on this?

Thanks in advance!

If you can login with ssh on the server you could use drush to unset the maintenance mode±

drush vset maintenance_mode 0


Image style in views field template on image I'm struggling with a piece of code in my views field template.

A short overview of the situation:

Node product has a field with filename for an image
Images are added with filezilla in default/files/products

What is the best way to implement image styles on these images.
My code:

<?php
 print theme('image_style', array('style_name' => 'product_overzicht', 'path' => $img_url));
?>

Where $img_url is just a simple variable, like: img_filename.jpg

This doesn't work because the folder of that image style is empty. I know the easy way is to use an image field on my product node but this can't be done here. I use a excel import for all products and the image filename is a column in that excel file. Images are all together in a folder.

Does anybody know a way do this or a good workaround. CSS markup is not good because the image size needs to be as low as possible in the view but on de node details page I would like to show the entire image.

Any tips or advice is welcome!

Try something like this :

<img src="<?php print image_style_url('product_overzicht', $img_url);?>">

Where $img_url should be uri, which in your case can be : public://products/img_filename.jpg


How to change order of javascript files in Drupal 6? I would like to change the order of my javascript files, and specifically move the jwplayer.js file so that it gets included after the jquery_ui*.js files.  Does anyone know how to do this?  I see how to do this in Drupal 7, using hook_js_alter().  But I do not see how to do this in Drupal 6.

UPDATE:
Here is some more information on my setup, that might be relevant:
- I call drupal_add_js('jwplayer.js') from within a custom views template.  The template adds jwplayer.js conditionally, depending on whether the views data includes any videos.

If you look at drupal_add_js() and drupal_get_js(), you will see the details.  Unfortunately, module_invoke_all() or it's cousins, don't get called, which means there are no hooks.  Boo.  A related issue is that when you aggregate, you loose the ability to do string manipulation (eg, explode, reorder, implode).

The best way to handle this is to alter the weight of the JW Player Module.  One way to do this is to edit the {system} table and edit the weight column value.  With the weights, lower numbers run earlier, higher numbers later, and where there is a tie, they run alphabetically.  Make sure you clear cache when you do this.  See Change module's weight - by module or manualy for some more details.

If this doesn't fix the problem, then the JS files aren't being added by the same hook.  I am not sure what can be done it in this case w/o hacking the module.

A total sledgehammer approach would be to not include the your code, but to add it in the theme's .info file.  This should add it after all modules.


Using search_api and search_api_views how do I display images? Drupal-7. search_api_solr 7.x.1.4 search_api_views 7.x-1.11

I have an index of documents and associated commerce products. The commerce product has an image in it. I can get views to display an index of the image url, but not display the images.

The image is displayed fine with a sql backed (non-solr) view.

We updated ctools to 7.x-1.4 and it started working.


Does a twig template know in which region it is? Or: how do I output conditional classes depending on the region a twig template is being rendered?

No, it doesn't.

With render caching, it is even possible that the same template/thing is not rendered again and put into a different region (not directly a block, but for a example a rendered entity, in a view or so).

It's easy to do targetting in CSS based on a parent region class. I know there are some recommendations to avoid that, but that's not always possible, especially when working with a complex system like Drupal, where you don't have 100% control over the HTML output in every scenario.


How can I use Entity API to integrate my entities with views? I've set my entity up with a custom controller but I want views integration.  I tried to follow the entity_test.module example, but it's for one bundle.  I want to create 4 bundles for my entity.  When I check views it does not appear in the list.

Here is my code:

function module_entity_info() {
  $return['module_content'] = array(
    'label' => t('Module Content'),
    'module' => 'module',
    'entity class' => 'ModuleContentClass',
    'controller class' => 'EntityAPIController',
    'views controller class' => 'EntityDefaultViewsController',
    'base table' => 'module_content',
    'fieldable' => TRUE,
    'entity keys' => array(
      'id' => 'cid',
      'bundle' => 'type',
    ),
    // Make use of the class' label() and uri() implementation by default
    'label callback' => 'entity_class_label',
    'uri callback' => 'entity_class_uri',
    'static cache' => TRUE,
    'bundles' => array(),
    'bundle keys' => array(
      'bundle' => 'type',
    ),
    'view modes' => array(
      'full' => array(
        'label' => t('Full content'),
        'custom settings' => FALSE,
      ),
      'teaser' => array(
        'label' => t('Teaser'),
        'custom settings' => FALSE,
      ),
    ),
    'module_property' => array(
      'label' => t('Property'),

      'entity class' => 'Entity',
      'controller class' => 'EntityAPIControllerExportable',
      'fieldable' => TRUE,
      'bundle of' => 'module_content',
      'exportable' => TRUE,
    ),
    'module_agent' => array(
      'label' => t('Agent'),
      'entity class' => 'Entity',
      'controller class' => 'EntityAPIControllerExportable',
      'fieldable' => TRUE,
      'bundle of' => 'module_content',
      'exportable' => TRUE,
    ),
    'module_open_house' => array(
      'label' => t('Open House'),
      'entity class' => 'Entity',
      'controller class' => 'EntityAPIControllerExportable',
      'fieldable' => TRUE,
      'bundle of' => 'module_content',
      'exportable' => TRUE,
    ),
    'module_office' => array(
      'label' => t('Office'),
      'entity class' => 'Entity',
      'controller class' => 'EntityAPIControllerExportable',
      'fieldable' => TRUE,
      'bundle of' => 'module_content',
      'exportable' => TRUE,
    ),
  );

  return $return;
}

function module_entity_info_alter(&$entity_info) {
  foreach (module_content_get_types() as $type => $info) {
    $entity_info['module_content']['bundles'][$type] = array(
      'label' => $info->label,
    );
  }
}

function module_content_get_types($type = NULL) {
  $types = entity_load_multiple_by_name('module_content', isset($type) ? array($type) : FALSE);
  return isset($type) ? reset($types) : $types;
}

I think something is wrong with either module_content_get_types() or module_entity_info_alter because when I try to use dpm statements in those functions nothing is output.  Please advise on any changes that should be made to improve my entity definition.  If you need to see additional code I can provide that as well.

You dont create views integration for bundles but for entities. The reason is that each bundle by definition stores it's core data the same way.

Think of node types = bundles. When you create a view you select to use nodes (Content) not if you want to use articles, pages, blog posts etc.


Embed media in Ckeditor field for drupal 7 I'm looking for a plugin for the latest version of CKeditor (3.6.3) so that I can add youtube videos (and other embedded media) to a text area that uses ckeditor.

I found several proposed plugins but most of them are not on the drupal.org site or are simply very old and do not seem to work with drupal 7.

There are a lot of questions on this subject but none that are recent or deal with drupal 7.

I know I can just turn off the rich editor and then embed the code in full html mode but I'd like something simpler for my client. Does such a module exist?

I've also found the media module (that is listed on drupal.org - http://drupal.org/project/media_youtube) but I don't think it integrates with CKeditor.

To clarify I'm looking for something like this: http://www.fluidbyte.net/embed-youtube-vimeo-etc-into-ckeditor but that works with drupal 7. (This one doesn't seem to work?).

EDIT: I am using the standalone CKEditor module

The standalone version of ckeditor module comes with a plugin called media embed. Ensure you have:

Enabled the media embed plugin for Ckeditor
Added the media embed input filter to a text format that your uses have access to (and is not filtered or tag limited in anyway)
Added the media embed button to the toolbar for the above text format

And that is it. In order to embed a youtube video (or anything for that matter), you get the <iframe> embed code from youtube, and paste it into the media embed dialog popup.


Custom 'Who's Online' View - How to filter User View by whether logged in I have a User View that is trying to replicate the 'who's online' block. It currently has 3 filters:

A custom user_profile field (Must be False)
User: Active (Yes)
User: Current (Yes)

For some reason the filter works on when using the first two but when I introduce the User: Current filter it filters the entire view by the active user.

What I need to do is be able to filter the view by all current logged in users.

please check the dev version for drupal 7

  Provides commonly requested user statistics for themers, IP address tracking and Views integration. Statistics include if the user is on or offline.

https://drupal.org/project/user_stats


Cannot activate parameter cors.config I am using the RESTful Web Services that is included in core of Drupal 8.2.7.
I need to activate CORS to be able to call the API from another domain.

I put this configuration in this file: "core/lib/Drupal/Core/core.services.yml" but it didn't work. I don't have the header Access-Control-Allow-Origin.

cors.config:
  enabled: true
  allowedHeaders: ['*']
  allowedMethods: ['*']
  allowedOrigins: ['*']
  exposedHeaders: true
  maxAge: true
  supportsCredentials: true

I found also this configuration is present in "sites/default/default.services.yml".

What is the proper way to configure CORS ?

To override container variables you have to enable this line in sites/default/settings.php (is enabled by default)

$settings['container_yamls'][] = __DIR__ . '/services.yml';

and then copy sites/default/default.services.yml to sites/default/services.yml.

Now you can configure the variables in services.yml.


Do I need a cron task for processing a queue? I've got a task that takes about 45 minutes to complete and needs to happen every day (synching users to several external database, etc).

To handle the work, I've set up a cron queue with hook_cron_queue_info() as follows:

function mymodule_cron_queue_info() {
  $queues = array();
  $queues['update_users_queue'] = array(
    'worker callback' => '_mymodule_process_user_queue_item',
    'time' => 120,
  );
  return $queues;
}

I fill the queue using this function:

function mymodule_queue_all_users_for_synching() {
  //...query for users...

  $queue = DrupalQueue::get('update_users_queue');
  foreach($users as $user) {
    $queue->createItem($user);
  }
}

The queue-filling function gets called as a cron task. I use Elysia Cron, so my implementation of hook_cronapi() is:

function mymodule_cronapi($op, $job = NULL) {
  $items = array();
  $items['queue_users_for_synch'] = array(
    'description' => 'Queue all user accounts for synching.',
    'rule' => '0 3 * * *', // Run this job every day at 3am.
    'callback' => 'mymodule_queue_all_users_for_synching',
  );
  return $items;
}

The worker function for each queue item, defined in mymodule_cron_queue_info is like:

function _mymodule_process_user_queue_item($item) {
  //...synchronize user ($item)...
}

My question is, when is cron actually going to start processing the queue?

Say I fill the queue every day at 3am, and want to process it 120 seconds out of every 30 minutes until it's done--do I need to create another cron task?

When Drupal runs cron tasks, it automatically handles any cron queue defined from modules, in drupal_cron_run(); first hook_cron() implementations are invoked, and then the cron queues are emptied.

Inmplementing hook_cronapi(), you can add an entry for another function handling the cron queue of your module.

function mymodule_cronapi($op, $job = NULL) {
  $items = array();

  $items['queue_users_for_synch'] = array(
    'description' => 'Queue all user accounts for synching.',
    'rule' => '0 3 * * *', // Run this job every day at 3am.
    'callback' => 'mymodule_queue_all_users_for_synching',
  );

  $items['clean_queue'] = array(
    'description' => 'Clean the queue for the user synching.',
    'rule' => '0 4 * * *', // Run this job every day at 4 AM.
    'callback' => 'mymodule_clean_queue',
  );

  return $items;
}

function mymodule_clean_queue() {
  $queues = module_invoke('mymodule', 'cron_queue_info');
  drupal_alter('cron_queue_info', $queues);

  // Make sure every queue exists. There is no harm in trying to recreate an
  // existing queue.
  foreach ($queues as $queue_name => $info) {
    DrupalQueue::get($queue_name)->createQueue();
  }

  foreach ($queues as $queue_name => $info) {
    $function = $info['worker callback'];
    $end = time() + (isset($info['time']) ? $info['time'] : 15);
    $queue = DrupalQueue::get($queue_name);
    while (time() < $end && ($item = $queue->claimItem())) {
      $function($item->data);
      $queue->deleteItem($item);
    }
  }
}

The alternative is letting Drupal handle the cron queue for you, but that happens when Drupal cron tasks are executed. If you want to empty the cron queue of your module more frequently, you can only add a new cron task handled by the Elysia Cron module.

The Elysia Cron module handles the cron queues in elysia_cron_run(); this function is being invoked from elysia_cron_cron() (an implementation of hook_cron()), drush_elysia_cron_run_wrapper() (a Drush command callback), and from its own cron.php. If you followed the instructions in the INSTALL.txt file (in particular in "STEP B: CHANGE SYSTEM CRONTAB (OPTIONAL)"), and replaced any invocation of http://example.com/cron.php with http://example.com/sites/all/modules/elysia_cron/cron.php, the Elysia Cron module should be already handling the cron queues. The code I suggested could be used to speed up handling the cron queues used from your module, if there is effectively the need of doing so.

// This code is part of the code executed from modules/elysia_cron/cron.php.
define('DRUPAL_ROOT', getcwd());

include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_override_server_variables(array(
  'SCRIPT_NAME' => '/cron.php',
));
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if (!isset($_GET['cron_key']) || variable_get('cron_key', 'drupal') != $_GET['cron_key']) {
  watchdog('cron', 'Cron could not run because an invalid key was used.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
elseif (variable_get('maintenance_mode', 0)) {
  watchdog('cron', 'Cron could not run because the site is in maintenance mode.', array(), WATCHDOG_NOTICE);
  drupal_access_denied();
}
else {
  if (function_exists('elysia_cron_run')) {
    elysia_cron_run();
  }
  else {
    drupal_cron_run();
  }
}


Modules appear to install, but don't show up I'm trying to install new modules via the url installer and uploader. I supply my sftp credentials. It says everything is fine. Then it says my module was installed successfully. However the new module doesn't show in the listing and it isn't in the sites/all/modules folder. What could I be missing?

We had this problem recently with a Centos server. If this is your scenario try

# chcon -Rv --type=httpd_sys_content_t ./sites/all/modules

From man chcon change security context, recurse, verbose, type is web content.

Note. Probably a good idea to check what type the files that are working are first.

$ sudo ls --lcontext google_analytics/
-r--r--r--. 1 unconfined_u:object_r:httpd_sys_content_t:s0 apache apache 31504 Jan 15 14:41 googleanalytics.admin.inc


problem with drupal_http_build_query output am using drupal_http_build_query and have part of my code as follows:

$or = db_or();
$or->condition('cid',$fField1);
$or->condition('cid',$fField2);
$or->condition('cid',$fField3);
$or->condition('cid',$fField4);
$or->condition('cid',$fField5);
$or->condition('cid',$fField6);
$or->condition('cid',$fField7);
$or->condition('cid',$fField8);

$querydata  = db_select('webform_submitted_data', 'wsd')
  ->fields('wsd',array('data'))
  ->condition('nid', $nodeID, '=')
  ->condition('sid', $sID, '=')
  ->condition($or)
  ->execute()
  ->fetchAll();

$result = array();
$i = 1;
foreach ($querydata as $qvalue) {
    $key = 'mapField'.$i;
    $result[] = array($$key => $qvalue->data);
    $i++;
}

$post_data = drupal_http_build_query($result,'', '&');

When printing the $post_data variable value, am getting something like this:
name=john&1[address]=street1&2[phone]=123456789

Notice the 1[] and 2[] after the &in the printed value. Any fix to remove these so that I get name=john&address=street1&phone=123456789?

You are getting that result because you build $result as an array whose values are array. Since drupal_http_build_query() contains the following code, the result you obtain is by design.

  foreach ($query as $key => $value) {
    $key = ($parent ? $parent . '[' . rawurlencode($key) . ']' : rawurlencode($key));

    // Recurse into children.
    if (is_array($value)) {
      $params [] = drupal_http_build_query($value, $key);
    }
    // If a query parameter value is NULL, only append its key.
    elseif (!isset($value)) {
      $params [] = $key;
    }
    else {
      // For better readability of paths in query strings, we decode slashes.
      $params [] = $key . '=' . str_replace('%2F', '/', rawurlencode($value));
    }
  }

You should change the code to the following one.

foreach ($querydata as $qvalue) {
  $key = 'mapField' . $i;
    $result[$$key] = $qvalue->data;
    $i++;
}


Display a key from unserialized data field I really don't understand how the "User: Data" field works. Couldn't find any documentation of this.

I want to set the Display format to "A certain key" to output the identifier value from this serialized data (relevant snippet):

a:1:{s:10:"hybridauth";a:26:{s:10:"identifier";s:17:"76561198181833179";

When I enter identifier as key, I only get this notice and no output.

  Notice: Undefined index: identifier in views_handler_field_serialized->render() (line 60 of www/htdocs/****/sites/all/modules/views/handlers/views_handler_field_serialized.inc).

What do I have to enter in the "Which key should be displayed" field exactly, to display the identifier value?

You need to add an Global PHP field and put the following code in output value to get the identifier field value.

<?php
 $result = unserialize($row->data);
 print $result['identifier'];
?>

Note : You should exclude Data field from display.

Since you very cautious in not using PHP, did you try the following option, change the ckeditor_skin to identifier. But it will produce the output as 76561198181833179['identifier'].


Webform multiple conditions recipient I am on a Drupal 7 website and I have a webform with multiple fields, one field is a selectbox with :

1-10 employees
10-20 employees
20-30 empolyees
...

Another one is an open textfield Postcode.

Webform offers the possibility to choose the recipients (e-mail TO) based on a component but not on multiple components.

For example, I want the mail to be sent to john@doe.com if employees = 1-10 and Postcode = 75000 etc.. And one more thing, I want my client to be able to change and contribute these rules. So a solution with Webform Rules will be too difficult for them in my opinion. I hope to find a solution within the webform e-mail interface.

Have you any idea how is it possible to do that without building a new complete custom form and keep the power of Webform ?

Thanks.

I suggest you try to avoid using simple textfield for the Postcode. Then you can use 2 dependent fields. The first field will be the select of employees number range. The second will be one of postcode selects, depending on the first choice. Then you can use the standard functionality: using select field key as the email.

If for a fixed employee number range you have individual emails for different postcode values then it is straitforward.

If not, still you can do it if all postcode values could be grouped into ranges, so that each range gets its own email (define select values for postcode ranges same as you did for employees number).


How to get name, price and image of product using EntityFieldQuery() Right now i am using this which doen't give me the name of the product or the price or location of the product image.

    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'commerce_product');
    $query->fieldOrderBy('commerce_price', 'amount', 'ASC');
    $result = $query->execute();

which give this result

Array
(
    [commerce_product] => Array
        (
            [56] => stdClass Object
                (
                    [product_id] => 56
                    [revision_id] => 55
                    [type] => product
                )

            [50] => stdClass Object
                (
                    [product_id] => 50
                    [revision_id] => 49
                    [type] => testcamera
                )

            [28] => stdClass Object
                (
                    [product_id] => 28
                    [revision_id] => 28
                    [type] => cameras
                )

etc...

You can now load the product using commerce_product_load($product_id); Then you will see price, fields, etc. You could also put all the product_id's in an array, then load them all with commerce_product_load_multiple($product_ids);


Exclude users from users list in issue tracking I'm trying to implement an issue tracking application with Drupal.

I have 4 clients and I want that each one of them will be able to access the site and add an issue.
I filter the project ID so any client see only his project issues.

The only thing I don't get how to do is to assign an issue.

In the "Issue" content type I created a "user Reference" filed called "Assign To" (which cause to Rules to send an email to the assigned user).

I want to be able to assign an issue to any client, but I want a client to be able to assign an issue only to me.

How can I do that?
If I can't exclude some users from the list (say-by role) - do you have any idea about different way to achieve the "Assign To" functionality?

Since your needs are so specific, I think the easiest (and maybe most logical) way to do this is not to restrict the users on the list. Instead, hide the field for all users of a certain role and have the value default to you. And for you, just don't hide it.

You can achieve this in a few ways. It would be very simple to write a custom module to do this. Use hook_form_alter() to access your issue form. In that function, use the global $user object to check the role of the current user, and  if it's your clients' role, set the '#access' property to FALSE and the '#value' to your user id. That's all.

You can probably do this without custom code also. Every field already has a default value in Drupal core. Set the default value for that field to you. Then use a module like Field Permissions to hide the field from your clients.

This achieves what you want without actually messing with the user reference list. That is also an option, but seems like a worse option to me. To do that, you would need a custom hook_form_alter() that, depending on the current user's role, would loop through the #options for that field and remove any users that aren't you.


Filter node by custom_field in admin panel I'm using Drupal 7, Views and Panels. Created a content type and custom field (field_list) And showing contents by list on my site. Thanks Views :) But when i click find content in admin panel, many many contents in my area.

Can i add filter option by field_list in my admin panel? Is it possible?

You need to install Admin views module. It will replace administrative overview/listing pages with actual views for superior usability. Now, you can override your views for admin panel for filter content by field_list.


How to install multiple modules with composer at once? Let's say we need to install these 2 modules :

composer require 'drupal/redirect:^1.4'
composer require 'drupal/pathauto:^1.4'

I couldn't find the correct syntax so I've tried this but it doesn't work :

composer require 'drupal/redirect:^1.4'; 'drupal/pathauto:^1.4'
composer require 'drupal/redirect:^1.4', 'drupal/pathauto:^1.4'
composer require 'drupal/redirect:^1.4'/'drupal/pathauto:^1.4'

Actually I install 1st module "redirect " and after installation is completed, I install the 2nd one "pathauto".

I would like to create a script that will install all the necessary modules I need.

You can write the names of multiple packages separated by spaces. For example:

composer require drupal/adminimal_theme:^1.5 drupal/adminimal_admin_toolbar:^1.9


How to hide a field when its value is set to zero I want to hide a field on a node when its value is set to zero using a content type. Here is what I had done so far to achieve my goal.

function pay_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  global $user;

  if ($node->type=='salary_info' && $op=='presave') {
    $public_holiday = $node->field_sstru_public_holiday[0]['value']; // here I get the value that I set to 0(No) or 1(YES) using a select list.

    if ($public_holiday == 0) {
      $nid = node_load(207919); // load node where i want to unset this field
      unset($nid->field_pd_public_holiday[0]); // here iam wrong and confused
    }
    else {
      drupal_set_message("HOLIDAY");
    }
  }

what should I do to unset my field?

I'm not sure why you are using presave operation.

If you want to hide a field on node view you should use view operation.

So your code should be as the following code:

function pay_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($node->type=='salary_info' && $op=='view') {
    $public_holiday = $node->field_sstru_public_holiday[0]['value'];

    if ($public_holiday == 0) {
      // you don't need to load node again.
      unset($node->field_pd_public_holiday);
    } else {
      drupal_set_message("HOLIDAY");
    }
  }
}

Edit:

If you want to hide field on another content type or node using presave operation, then you need to load node and unset field value then save node again using node_save function

So your code should look as the following:

function pay_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  global $user;

  if ($node->type=='salary_info' && $op=='presave') {
    $public_holiday = $node->field_sstru_public_holiday[0]['value']; // here I get the value that I set to 0(No) or 1(YES) using a select list.

    if ($public_holiday == 0) {
      $node = node_load(207919); // load node by nid
      unset($node->field_pd_public_holiday[0]); // unset field from node object
      node_save($node); // save node after unsetting the unwanted field value.
    }
    else {
      drupal_set_message("HOLIDAY");
    }
  }
}


How to use views contextual filter default argument "Taxonomy term id in url" I am following the guide http://www.metachunk.com/blog/adding-related-content-view-drupal-7 to make a related content block.  I have 2 taxonomies that my content is tagged with.  But the contextual filters are not working.

I think it is because the path is node/[nid] and does not contain a taxonomy term id.  How can I fix this so that views can figure out what terms a node is tagged with?  Should I provide the default argument another way?

Have you figured this out? If so could you share your answer?

I do not think the problem is that the path follows any pattern.  As long as you create a path that identifies the location of a term and you configure the contextual filter correctly.  eg. example.com/whatever-you-want/any-term will work as long as the view path is example.com/whatever-you-want/%.  The 'any-term' must be a term in a vocabulary defined for the contextual filter and validation must be set to identify it.


How to return the whole entity referenced by a entity reference field with views I have content type A with a entity reference field that references a user (let's name it field_user_reference). The user has field_b and field_c field.
I've created a rest export view to return all nodes of type A with it's field which includes field_user_reference. My problem now is that the field_user_reference exported by views only contains the user's name. How do i also include the user's id, field_b and field_c?

The view returning something like this would be optimal:

[{"nid":"1","title":"title","field_user_reference":[{"uid":"1","name":"username","field_b":"valueb","field_c":"valuec"}]}]

You have to add a views relationship to the user.

The relationship is usually called something like, Entity referenced from FIELD_NAME in your case User referenced from field_user_reference.

When you have added the relationship, the user's fields will then appear in the fields list.

For more information about views relationships, look here add a relationship to a view.


How and where to use/place database queries when a webform is submitted? Let's say that I already created a webform with fields Customer Name, Customer Surname and Customer Address.

When the webform is submitted, I want to insert those values captured in a custom table "Customer" created in the database that Drupal is using.

How do I achieve this? Do I have to use a specific module to insert those values?

Is it feasible to do this by using the Rules module? If yes, can you give me a simple example on how to do this?

You can use hook_webform_submission_insert to insert data in custom table

ie :

function hook_webform_submission_insert($node, $submission) {
  // Insert a record into a 3rd-party module table when a submission is added.
  db_insert('mymodule_table')
    ->fields(array(
    'nid' => $node->nid,
    'sid' => $submission->sid,
    'foo' => 'foo_data',
  ))
    ->execute();
}

As mentioned in above example you will find all submitted data in

$submission

variable.


creating "live search" from database text field in Profile Content field Drupal 6 I'm new to Drupal development. I have inherited a Drupal 6 site. I would like to add to the content-profile fields a "live search" text field that will give the user options from a database based on the letters typed. I already have the following:

Database
Profile field with onkeyup function in the .js file.
Function that gets the correct values from the database
any number of tutorials that explain how to use ajax for connecting the onkeyup function and the database query.

What I don't understand is how to put the search results into the "allowed values" of the text field? All the examples define an additional < div > to put the results in. Here it's part of the text field. What code should be in the allowed values so that it will show the correct values? Where to put the retrieved values?

Any help would be appreciated!

You're asking how to make an Ajax search request from a textfield.

I'm not going to answer your exact question but you need some javascript to fill in the results from your sql query into the search field. Here is an example which fills in an HTML <options> list from a Drupal sql search:

jQuery(function($) {

  $('#edit-field-survey-program-und option:gt(0)').remove();
  $('#edit-field-survey-program-und').attr('disabled', 'disabled');

  // When a country is selected. Find the Academic Programs within that
  // country from an SQL lookup. Then fill in the options values and
  // make that options list enabled for the site visitor.
  $("#edit-field-survey-country-und").click(function() {
    var selected_country = $("#edit-field-survey-country-und").val();
    if (selected_country != '_none') {
      // Do our SQL lookup from a service enpoint with a search parameter.
      $.ajax({
        type:'GET',
        url: '/eap-ajax/eap-country-programs/' + selected_country,
        data: '',
          success:function(data){
          // Replace values of target form element with found results.
          // Enable for enduser.
          $('#edit-field-survey-program-und option:gt(0)').remove();
          $.each(data, function(key, value) {
            $('#edit-field-survey-program-und').append(
              '<option value="' + key + '">' + value + '</option>'
            );
          });
          $('#edit-field-survey-program-und').removeAttr('disabled');
        }
      });
    }
  });
});

The above example is the same 3 pieces for any AJAX thing.

Make a click event listener function
Do your SQL business logic
Inject your results somewhere back into the page

For a full writeup feel free to see my more complete writeup:
http://blog.arvixe.com/drupal-ajax-autocomplete-dependant-form-elements-using-jquery/

I suggest googling how to fill in results to an <input> text field using jQuery.


Full term path as product url Im using D7 and UC3. A product is multiple levels down:.

product list = cat1/sub2/sub-sub1/

Now using pathauto i'm trying to make the path of the product cat1/sub2/sub-sub1/product1 however i cant find the right tokens to do this. Best is can get is sub-sub1/product1 loosing the first two steps. In the breadcrum i do see the other levels, so the product knows its nested like that.But i cant seem to get the url to correspond.

Taxonomy reference of the content type must be set to 1. New tokens will become availible and differect ways to create a url like the above become possible


How to override a ctools plugin from another module I want to modify some logic of a ctools plugin defined in the entityqueue module.

The file that contains the ctools plugin definition I want to modify is: /entityqueue/plugins/entityreference/behavior/entityqueue.inclink to file

This file makes use of the class EntityReferenceBehavior_EntityQueue which is defined here. I want to modify the logic in the presave function.

Is there a way to hook into it without patching the file?

I am not entirely sure if this is the best solution but I ended up doing the following:

implemented hook_ctools_plugin_pre_alter()

function my_module_ctools_plugin_pre_alter(&$plugin, &$info) {
      if ($info['type'] == 'behavior' && $info['module'] == 'entityreference' && $plugin['class'] == 'EntityReferenceBehavior_EntityQueue') {
        $plugin['class'] = 'EntityReferenceBehavior_EntityQueue';
        $plugin['path'] = drupal_get_path('module', 'my_module')  . '/plugins/entityreference/behavior';
        $plugin['file'] = 'entityqueue.inc';
        module_load_include('php', 'my_module', '/plugins/entityreference/behavior/EntityReferenceBehavior_EntityQueue.class');
      }
    }

Then I copied the files ('/plugins/entityreference/behavior/EntityReferenceBehavior_EntityQueue.class' and '/plugins/entityreference/behavior/entityqueue.inc') in my module and modified the code of presave function.


Add Fields to Field Group programatically I have used "Field Group" module and created some groups in backend. Now i want to programatically add a field to the group.  How can I do that.

I am using Hook_form_alter, I have noticed that every field has an 'und'attribute in which the field group it belongs to is listed, but if a create and 'und' array and add a field group name to it, it does not work.

How should I do it?

This is a bit old, but I wanted to do the same thing and couldn't find an answer on the web. I ended up figuring it out by myself.

Let's suppose you created a field group through the CMS interface with the name "group_product_fields". You added some fields to that group.

Now you have a new field being included in the form programatically via hook_form_alter. You want to add that field to "group_product_fields". Here is an example of what the field could be:

$form['new_product_field'] = array(
  '#type' => 'textfield',
  '#title' => t('New product field'),
  '#description' => t('Description for this new product field'),
);

All you need to do now is to add that new field to the field group. To do that add the line below to the hook_form_alter. It can be placed anywhere inside it.

$form['#group_children']['new_product_field'] = 'group_product_fields';

That's all. You may wish to adjust the field weight for it to be positioned as you want. But in the end this is really simple. :)


Convert Drupal error message to JavaScript alert How I am able to do that?

I'd like to show the status/error messages in form of an alert using JavaScript instead of showing it on the screen.

It think the better messages module is for you.


How to add commas to numbers I have a text field. View select the text field. I entered three numeric values to the text field as 3321,33432 and 110343. In the view, I see the values without the commas. I like to see these numbers as 3,321, 33,432 and 110,343. Is there way I can rewrite the output using comma? Please provide some help.

What type of text field did you choose for your field? Regular text field?

If you want to be able to add comas. When you add a new field to your content type you need to select INTEGER as your field type, not text.

Then View's will detect that its an integer field (numbers only) and give you the comma option.


How to rebuild images using Imagemagick? I have switched the Image toolkit from GD2 to Imagemagick. It’s working great for new images, however previously uploaded images still show up with lowres quality.

How can I regenerate ALL images using Imagemagick?

I've followed up: Rebuild images from image style

drush: drush image-flush mystyle
rm -rf sites/default/files/styles
Clearing Caches a couple of times and hit save on all image styles.

However all images still show up with lowres quality. When I manually update a node, the image quality looks correct. Also, the file size changes. Looks like imagemagick isn’t triggered. What can I do?

This issue sometimes occurs when the original files are too large, causing memory exhaustion on the server during thumbnail creation.  Since the thumbnail creation on an image style cache flush is generated in a serial queue, just one high res image can prevent all the other image style thumbnails from being generated.

Steps to check and attempt to resolve this include:

After immediately trying to reset/flush the image style cache, check your apache and php logs on the server itself (as the memory exhaustion errors don't typically appear in the Drupal watchdog logs).
If you in fact encounter the memory exhaustion error, try increasing the server's memory limit.  See https://stackoverflow.com/questions/3534274/php-memory-exhausted
If after bumping the memory limit you continue to encounter this error, spot check some of the original images- determine the actual pixel dimensions of each image as well as the pixel density and/or dpi.  If either is significantly large, you may want to download the original images, batch process/resave at a more reasonable size, and upload back to the server; then trigger the image style flush/thumbnail regeneration again.
If #3 resolves the issue, you may want to apply max width/height to the image upload field config itself to prevent content managers from uploading enormous images in the future too. Note: Depending on your settings, this approach may result in saving a downsized version of the original image, if the original image exceeds maximum dimensions; or result in a warning to the content manager prompting them to upload a smaller image.
In conjunction with the max width & height options, you may also want to change the jpeg quality of the images generated for the image styles.  While signed in as an admin, go to Configuration > Media > Image Toolkit (/admin/config/media/image-toolkit)


Bootstrap sub-theme override CSS I just set up an new Drupal 8 website. I was used to use CSS injector on Drupal 7, but since the module is not ready yet, and I thought I'd better start with subthemes, I tried to create a new Boostrap subtheme. I used the CDN method, activated it in my admin panel, but when I try to override CSS by creating CSS styles in css/style.css, nothing work. In Drupal 7 with CSS injector, my main difficulty was to find the proper class.
So I tried a lot of different possibilities, copied/paste CSS from original files in Bootstrap. Nothing works.

Have anybody already tried to create a sub-theme with Bootstrap? Did overriding CSS work?

I looked at the CSS file link, it's loading lumen theme nicely. I tried to change h2 color in this file:  themes/bootstrap/css/3.3.5/overrides-lumen.min.css and it works...Clearly, seems that style.css is not used...

I'd wager that the stylesheet has not been added to the page. The documentation is pretty solid on this: Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme.

This page isn't likely to go anywhere, but I'll summarise here. Please go and read the full documentation page though, there is MUCH more there:

  The general steps for loading assets (CSS/JS) are:

  Save the CSS or JS to a file.
  Define a "library", which can contain
  both CSS and JS files.
  "Attach" the library to a render array in a
  hook.

  But in the case of themes, there is an alternative to step 3:
  themes can choose to load any number of asset libraries on all pages.

  Libraries

  [...] a library could just as well only contain CSS assets, or only contain JS assets. Most themes will probably want to have a global-styling asset library, for the stylesheets (CSS assets) that it wants to be loaded globally (i.e. on all pages where the theme is active — usually the whole site except the administration pages):

global-styling:
  version: 1.x
  css:
    theme:
      css/layout.css: {}
      css/style.css: {}
      css/colors.css: {}
      css/print.css: { media: print }

  Attaching a library to page(s)

  Attaching to all pages

  To attach a library to all the pages on the site that use your theme,
  declare it in your theme's *.info.yml file, under the libraries key:

name: Example
type: theme
core: 8.x
libraries:
  - fluffiness/cuddly-slider


Adding additional option under node publish options In add /edit node page under publish options there are four option available

Published
Promoted to front page
Sticky at top of lists
Create new revision

Is there a possibility to add a 5th one for example Active and can use that option in views so that only the nodes which are they appear other nodes must not.

I am a themer not a coder so, I would really appreciate if your answer can also contain the code or reference or descriptive how to steps.

Thanks in advance

I think you can do it without adding the 5th option, if you familiar to Views module, and Taxonomy module, you can simply add vocabulary(in Taxonomy configuration) and add Term - for example Active, next you can add field to your Content Type(Article or whatever) and now if you want to post an article you can chose - Active term.
Next step, create new view, add whatever you want(body, title, etc) and in Views/Contextual filters add new filter -> has Taxonomy term ID input the Active id, and now you are done.


How to secure Drupal website I have Drupal CMS and I need to protect it from sensitive data leak, which are the customer names, addresses, the payments and order information.

I am new to Drupal, so my question is, is it possible to run each module in separate security context, so if one module gets exploited, the other data is not compromised? Is Drupal OOP based? Has drupal administration separated from the frontend? Would be these two achievable at all? I saw the LDAP module, which helps, but it doesnt help with the customer data...

You should read the official security thread, if you want to go further I advice you to take a look at the cracking Drupal book. In chapter 1, which is available for free download, you will get an idea of the places to look at.

According to this book, most common vulnerabilities found in Drupal sites are :

    Vulnerability   | occurences as a percentage of the total

     XSS            |      44
     Access bypass  |      14
     CSRF           |      10
     SQL injection  |      10
     Code execution |      8
     ...

So you shouldn't be concerned by Drupal architecture but with the way you implement your website, like any other.
For instance, requiring administrator approval for users registration, making sure forms are safe and applying Drupal's updates should be a good start.

Also, if you choose to use the LDAP module for Drupal 7, keep an eye on its security related issues.


Render one Paragraphs Module field value inside another Paragraph field's .html.twig template This question is for the Paragraphs module for Drupal 8.

I've created a Paragraph Type with 4 fields: Title, URL, Image, and Description.

I want to take the value from the URL field, and use it with the Title and Image fields, so that my title and image have a link wrapped around it with the href getting the value from the URL field.

My idea was to use Twig template suggestions for the Title and Image fields, but I can't figure out how to render the value of the URL field in those .html.twig files....

For example, I have a twig suggestion template for the title, called:

field--paragraph--field-list-item-title.html.twig

My idea was to render the value of the URL paragraph field with this:

{{ paragraph.field_list_item_link_url }}

so that the code inside my field--paragraph--field-list-item-title.html.twig file looks like this:

  {% else %}
{% for item in items %}

{{ item.content }}

{% endfor %}{% endif %}

But its not rendering anything.

Is there a way to accomplish this? Is there another way instead?

You could try a template for the paragraph itself, rather than the individual fields. If you look in the modules/paragraphs/templates you'll see the default template used to render paragraphs. Copy this into your theme and rename it to paragraph--XXXXXX--default.html.twig replacing XXXXXX with the machine name of the paragraph.

You can then access the values of your fields using {{ content.XXXX }} where XXXX is the machine name of the field, e.g. {{ content.field_list_item_link_url }}


Drupal PHP views - how to reference nested braket array variables? I did a dpm() on the path variable i have and I'm running into the issue of figuring out how to reference this variable. When I do a print_r() on the variable it shows that its [[path]]

I'm not sure how to reference that. I thought it might be $var[['path']] but that doesnt work.

You're almost there, since the square brackets are part of the string they need to go inside the quotes, e.g.

$var['[path]']


drupal zen theme using sass - sub folder dont get regenerated i have followed these instructions to install ruby and compass and sass, everything is ok and works. However, do i need to do a 'compass watch' at a lower level for the component and layout folders in my zen theme folders as well? for example, if i change .../sass/layouts/fixed.scss it doesnt automatically regenerate the equivalent ...css/layouts/fixed.css

compass watch should only need to be run from your subtheme folder.  Files in the components and layout folders should use partials (files beginning with underscore).  Then you have to make sure to use @import "components/fixed"; inside your styles.scss for each partial you want to include.

When compass compiles the styles.scss file, the partials that you have @import's for will be automatically included in style.css


WYSIWYG edit view of text is below image in content but node view isnt. In my WYSIWYG edit view ive hit return to make some text apear below an image in the content. However when I save the text is alongside the image, half way down but below.

Why does the edit and node view look different? How can I solve this? Thanks

It is quite possible that the text format with which your field is being displayed is restrictive i.e. it only allows a subset of HTML tags.

I'm going to assume that you are talking about the Body field or more generally a text field attached to a Content type.

Ensure the field_ui module is enabled and go to the Manage display page for your content type. For the field in question, check if the formatter says Default.
Now, go to Administration > Configuration > Content Authoring > Text formats and inspect the first text format in the list.

If you are going to view as a different user, remember that Text formats are linked to permissions and an user's default text format is the first from the list in 2. that he has access to use.


What can I do with content types that I can't with taxonomies? I'm starting with Drupal and comparing taxonomies and content types and from what I see, they both:

offer a URL via the Name/Title field
have the same list of field types (images, double-field, text...)
can refer each other (with node/term reference)
have translation (with the proper translation modules enabled)

Therefore I seem able to create the same content via taxonomies as with content types.

However, taxonomies seem tightly integrated with views, offering categorization and filtering, unlike content types, which brings me to the following question:

What's the point of using content types at all, is there anything we can do with content types that we can't do with taxonomies?

Taxonomies allow hierarchical nesting of items in vocabularies, and each term can only be in one position and one vocabulary at a time.

Nodes, however, can be tagged with any number of terms from any number of vocabularies.

Tagging taxonomy terms with other terms from other taxonomies, or with other terms from within the same taxonomy could potentially have very different results than maintaining a separation between terms (descriptors) and nodes (content that can be described), especially when it comes to using something like Views to sort and separate content based on descriptors.

So it's not so much that content types can do things that terms can't, as it is that content types cannot do as many things that nodes ought not do.


How to target the "site name" within a css file How does one target the site name (the one that appears immediately below the site logo) within a css file? I would like to both change the color of the site name text in addition to centering the site name (for some reason it's by default confined to about a third of the header space on the left). Essentially, how can I style the space above the menu region if it is not part of the header region?

Any help would be much appreciated. If you find what I've written to be vague I can certainly try to clarify.

It depends on the theme that you're using.

As Patrick Ryan said " You should look into using firebug in firefox or inspect in chrome or developer tools in IE. These will all easily show you what css class you need to target to make these and any other changes."

I personally use Chrome so in order to do that, just right click on the site name. Here's a preview in chrome.

you can use #site-name or #name-and-slogan in this theme. But this will change per theme. The same process can be done if you want to align the text or make it wider.

The great thing about using these development tools is that they allow you to add CSS right on the browser. you'll see that on the right side. Just double click.

If you're using a subtheme of Zen, for example, check the templates in the zen folder to see the page.tpl.php file for the template of the page.

I touch on using templates in Zen subthemes in my slides here (slide 44 onwards): http://www.slideshare.net/japodomingo/theming-with-zen

If you know how to use templates, you can manipulate the display any way you want. :) Here's a brief overview of the templates. https://drupal.org/node/190815

I hope this helps.


How do I hide some fields to registered users? This is my use case:

If an anonymous user completes an order, the order shows profile type A. When user completes that order, the system creates a new user, and fulfill his profile with the profile2 type A order information.
If a registered user completes an order, it does not show any profile2 information.

I want to make my checkout process shorter for already registered users, and I want for the anonymous users to have a profile filled with the order information.
I get the first part of the use case working (the anonymous user workflow) with the excellent Commerce Order Profile2 Checkout Panes module, but I have no idea on what to do to avoid it appears for registered users. The problem is that the fiels in question are profile fields, so I need to grant registered users permission to view/edit them, and I can't hide them there with field permissions or CSS styles because they wouldn't be available to anonymous users too.

What could I do?

Though I haven't used profile2 for any commerce site, but the mechanism behind the checkout process for asking profile info for anonymous user is to create account for him on site.
If some information in the profile is mandatory then it will be asked on the time of checkout..& register user won't get those fields at time of checkout.

I use address-field for collecting address for shipping as well as billing, which always keep the old address and its possible to make some address default...so that registered user doesn't find it irritating..

If you must have to use profile2 field then please check whether its required field & if it is...then why some registered users profile is not filled with those information...


List related nodes through the same referenced node? I have two node types: book, author.

There is a node reference field in book which references a single author.

On a book node, I would like to display a list of the same author's books, which I don't know how.

It seems to me the solution will involve EVA, contextual filter and relationships.

I can list all the author's books in an author node using EVA and contextual filter. But it uses author's node ID, which is in the url. I don't think I can pass the referenced author's Nid in a book's url. Or can I?

I'm only 5 days into drupal, and don't know a thing about relationships, can someone help me get my head around this? thanks in advance!

[D7]

I can't believe I just did it myself, though not sure if it's the best way.

First add a relationship, Content: Author (field_reference_author), give it a name: field_reference_author

Then add a relationship, Content: Author (field_reference_author) - reverse, set RELATIONSHIP to the field_reference_author, give it a name: field_reference_author_reverse

Set each displaying field to use relationship: field_reference_author_reverse

Add contextual filter, Content: Nid , without any relationship, Provide default value :content ID from url.

To exclude the node that is containing the related nodes list, from the list, just add contextual filter:  Content: Nid , with relationship: field_reference_author_reverse, Provide default value :content ID from url.

And it's done!


How to get text before the title? I suppose this is something about theming, but I haven't found a way to do this. I'm using the Pixtures Reloaded subtheme of Adaptive Themes.

I have a group of pages that need to have the structure:

     Pretitle
     Title
     Subtitle
     Body

that should come out looking like this:

A true story:
               The Amazing Thing
              And Why it's Amazing
This is the story of...

The title and subtitle are centered.

When I create a "Basic page", I have to specify a title for the page, and that title is displayed at the top-left of the page. I tried two ways to get something to be shown before the title.

First I defined a block called "Pretitle" and placed it in the theme's region called "Secondary content", which in the "Block region demonstration" is shown as being above the title. But when I displayed the page, the pretitle was exhibited under a big banner that said "Pretitle". That's not okay.

Next, I deleted that and defined a text field called "Pretitle" and placed that above the title in the Field Manager. When I displayed the page, the pretitle appeared at the very bottom of the page, under a line that said "Pretitle:". Again, not okay.

Aside from not seeing how to get a line of text to appear before the title (without a banner saying that it's a pretitle), I also have not a seen a way to get the title to be centered horizontally on the page.

I'm guessing this problem is because there's something really simple about composing pages in Drupal that I don't know about. Can you tell me what I'm missing?

Please don't give an answer that requires writing my own module because I'm not nearly ready to do that yet.

Thank you.

to center the title: find the appropriate css file, and change:

.title, #page-title
{
...
}

to include

.title, #page-title
{
  text-align:center;
}

It could be listed as either the class title, or id, depending on the theme. This is basic CSS.

to include the other fields:

1) you can alter the page.tpl.php file for theme, but if modules are out,  I assume most any php is out, so this is probably not suitable.

2) reassign your block if it otherwise worked, but in the block set up, change the Block Title to <none>


Create pager from db_query This my SQL query to fetch the details.

$query = "SELECT DISTINCT TITLE, PID, TYPE, SUM(DAYCOUNT) AS tot, ROUND(SUM(DAYCOUNT)/(
        SELECT SUM(DAYCOUNT) FROM REPORT_LIST_VIEW), 4) AS per
        FROM REPORT_LIST_VIEW
        WHERE DAYCOUNT > '0'
        GROUP BY TITLE, PID, TYPE
        ORDER BY TITLE ASC";
        $res = db_query($query);

I am displaying out put like this

foreach ($res as $row) {
$i++; ?>

<a href="/page-file-views-user?id=<?php echo $row->pid ;?>&type=<?php echo $row->type; ?>" >

<?php echo ucfirst($row->title); ?>

<?php echo $row->per * 100; ?>%

<?php echo $row->tot; ?>

<?php $sum+= $row->tot; } ?>

How can I add a pagination (mini pager) at top & bottom of the result?

<?php
function pager_array_splice($data, $limit = 9, $element = 0) {
  global $pager_page_array, $pager_total, $pager_total_items;
  $page = isset($_GET['page']) ? $_GET['page'] : '';
 // Convert comma-separated $page to an array, used by other functions.
  $pager_page_array = explode(',', $page); // outs puts empty array
  // We calculate the total of pages as ceil(items / limit).
  $pager_total_items[$element] = count($data); // output 1
  $pager_total[$element] = ceil($pager_total_items[$element] / $limit); // output 1
  $pager_page_array[$element] = max(0, min((int)$pager_page_array[$element], ((int)$pager_total[$element]) - 1));  // no output
  return array_slice($data, $pager_page_array[$element] * $limit, $limit, TRUE);
}
?>

And in my pagination div

$output = '';
$customArr = pager_array_splice($data, 1);
$output .= theme('views_mini_pager', array('quantity' => 1));
print $output;

But no result is printing. Any error in my logic.

You want to take advantage of the PagerDefault class.

Write your query as a db_select query which I'll leave as an exercise for the reader because, frankly, I'm not sure if it's possible to create a db_select query with a subquery as part of an expression like that :).  Assuming you build up your select query in a variable called $query, you'd have code along these lines:

$query = db_select('REPORT_LIST_VIEW')->extend('PagerDefault');
...build up $query object here...
$res = $query->execute();

$pager = drupal_render(array('#theme' => 'pager'));

Then just output $pager wherever you want it.

Also, in general, I'd recommend placing this in a block rather than hard-coding it into your theme so that it's more reusable.


Is it possible to login to Drupal with a custom user field, instead of username/pass? I have two websites - One of them is Drupal 7, and the other is a different site (Site #2). In Site #2, within the user tables, is a field called "customid". Each user on Site #2 has a unique, randomly generated 30 character alphanumeric string within their respective "customid" field.

I can pull the value of the "customid" field for the user on Site #2, and use it as an input value in a form post to the Drupal 7 site.

In the Drupal 7 site, I created a custom user field "customid" as well.

Is it possible to make a form post from Site #2 to Drupal 7 - with the "customid" value as an input, and if it matches the "customid" field in the Drupal user table, log them in, else - redirect to the registration page?

We're essentially bypassing the username/password to log them in - I'm trying to log them in via custom user field.

I searched everywhere, and just couldn't find anything where something like this had been discussed. Thanks anyone for your time and help!

UPDATE:
I've tried implementing W.M.'s solution below, however upon attempting to enable the module, I get the white screen of death. Nothing shows up in the logs for the error.

For my custom module, I have two files:
ra_login.module
ra_login.info

Info file:

name = RA Login
description = Check ID and Login if there is a match, else go to Registration Page.
core = 7.x

; Information added by Drupal.org packaging script on 2013-12-16
version = "7.x-1.0"
core = "7.x"
project = "ra_login"
datestamp = "1387203506"

Module File:

<?php

function ra_login_menu()
{
    $items['authenticate-by'] = array( // or any other custom path you choose
        'title' => 'Login by SSO',
        'access callback' => true, // no point in authenticating at this point in code execution
        'page callback' => 'ra_login_function',
        'type' => MENU_CALLBACK,
        );
    return $items;
}

function ra_login_function($CONTACTID)
{
    // post the data to /authenticate-by as json with a parameter / property named CONTACTID holding the CONTACTID
    $postData = file_get_contents('php://input');

    $Data = json_decode($postData);

    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'user')
        ->propertyCondition('uid', 1, '<>')
        // User number 1 should not be able to log in using this method
        ->fieldCondition('field_contactid', 'value', $Data->CONTACTID, '=')
        ->range(0,1);

    $result = $query->execute();

    if (isset($result['user'])) {
        $uid = array_keys($result['user'])[0];
        $account = user_load($uid);
        global $user;
        $user->uid = $uid;
        $user->name = $account->name;
        $user->timezone = $account->timezone;
        user_login_finalize(); // Log user in
        drupal_goto('/user'); // or any other path to redirect logged in users to
    } else {
        drupal_goto('/user/register');
    }

}

Again, for some reason when I try to enable the module, I get a white screen.
Thanks for anyone who can help!
UPDATE:
I turned on errors in php.ini - now instead of the white screen, it shows me the following error:

Parse error: syntax error, unexpected '[' in C:\inetpub\wwwroot\sites\all\modules\ra_login\ra_login.module on line 31

Line 31 is:

$uid = array_keys($result['user'])[0];

Any help is greatly appreciated!

This is the code you need. In the Drupal site create the following module:

Update:

function my_special_login_menu()
{
    $items['authinticate-by-customerid'] = array( // or any other custom path you choose
        'title' => 'Login by customerid',
        'access callback' => true, // no point in authenticating at this point in code execution
        'page callback' => 'my_special_login_function',
        'type' => MENU_CALLBACK,
        );
    return $items;
}

function my_special_login_function($customerid)
{
    // post the data to /authinticate-by-customerid as json with a parameter / property named customerid holding the customerid
    $postData = file_get_contents('php://input');

    $Data = json_decode($postData);

    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'user')
        ->propertyCondition('uid', 1, '<>')
        // User number 1 should not be able to log in using this method
        ->fieldCondition('field_customerid', 'value', $Data->customerid, '=')
        ->range(0,1);

    $result = $query->execute();

    if (isset($result['user'])) {
        $uid = array_keys($result['user'])[0];
        $account = user_load($uid);
        global $user;
        $user->uid = $uid;
        $user->name = $account->name;
        $user->timezone = $account->timezone;
        user_login_finalize(); // Log user in
        drupal_goto('/user'); // or any other path to redirect logged in users to
    } else {
        drupal_goto('/user/register');
    }

}

For this code to work you need Entity API module and you should serve the site over SSL in order to encrypt the data transferred between the two sites.


What does cron error "exit status 4" mean in syslog? (Ubuntu) I've never seen this before, my Status Report page says the last cron run was 35 minutes ago at 10:35 today. So I went to watchdog logs and could see that Cron run completed at 10:30.

I've set the cron to run on 0 and 30th minutes of every hour, so twice per hour using sudo crontab -e so it's using the root user's crontab with the following command (cron key intentionally removed):

0,30    * *   *   *     wget -O - -q -t 1 http://localhost/cron.php?cron_key=

I'm not using the cron.module aka poormanscron in D6

I've manually run the cron and it updated the Status Report page after that.

What could cause this weird behavior? I'll admit that I haven't tried flushing the caches, but could caching be the cause of this? Or is there something more sinister?

I've dug around in syslog and found an error relating to the cron, but I have no idea what this means (cron key intentionally removed):

Aug 16 10:30:01 drupal-1 CRON[31372]: (root) CMD (wget -O - -q -t 1 http://localhost/cron.php?cron_key=)
Aug 16 10:30:01 drupal-1 CRON[31370]: (CRON) error (grandchild #31372 failed with exit status 4)

I can see the grandchild #31372 is referring to the first line CRON[31372] but what does exit status 4 mean?

I just wanted to also let people know that the cron has run without any problems so far afaik. But it could be that this is the first time I've noticed this as well.

Ok, I'm such an idiot sometimes.

I've edited the .htaccess file this morning to redirect without www. to www.domain.com and that has caused my cron going to localhost to be redirected to www.localhost which caused the cron to fail. /facepalm

But to answer exit status 4's meaning for wget according to this page it means Network failure (Kudos to @Clive)


What's wrong with the fetch rss feed code? The hook_block() code is the following.

   // …
   case 'view':
      $url = 'http://example.com/feed'; //the site's rss url
      $blocks['subject'] = t('on the bookshelf');
      $blocks['content'] = _mymodule_fetch_feed($url);
      return $blocks;
   // …

function _mymodule_fetch_feed($url,$num_itmes=3){
  $http_result = drupal_http_request($url);

  if ($http_result->code == 200) {
      $doc = simplexml_load_string($http_result->data);
      if ($doc === FALSE) {
        $msg = "error parsing booksheld xml for %url: %msg.";
        $vars = array('%url'=>$url,'%msg'=>$e->getMessage());
        watchdog('goodreads', $msg, $vars, WATCHDOG_WARNING);
        return t("Getting the bookshelf resulted in an error.");
      }

      return _mymodule_block_content($doc, $num_items);
    }
    else {
      $msg = 'No content from %url.';
      $vars = array('%url' => $url);
      watchdog('goodreads', $msg, $vars, WATCHDOG_WARNING);

      return t("The bookshelf is not accessible.");
    }
  }
}

function _mymodule_block_content($doc, $num_items = 3) {
  $items = $doc->channel->item;
  $count_items = count($items);
  $len = ($count_items < $num_items) ? $count_items : $num_items;
  $template = '
'.'
%s
by%s
'; // Default image: 'no cover'.
  $default_img = 'http://www.example.com/images/nocover-60x80.jpg';
  $default_link = 'http://example.com/feed';
  $out = '';
  foreach ($items as $item) {
    $author = check_plain($item->author_name);
    $title = strip_tags($item->title);
    $link = check_url(trim($item->link));
    $img = check_url(trim($item->book_image_url));

    if (empty($author)) {
      $author = '';
    }

    if (empty($title)) {
      $title = '';
    }
    if (empty($link)!== 0) {
      $link = $default_link;
    }
    if (empty($img)) {
      $img = $default_img;
    }

    $book_link = l($title, $link);
    $out .= sprintf($template, $img, $book_link, $author);
  }

  $out .= '

'. l('Goodreads.com', http://example.com').'
';
  return $out;
}

I put this code in my module; it can get the data, but the links are all the same.(http://example.com). How can I make it work?

if (empty($link)!== 0) {
  $link = $default_link;
}

That condition makes no sense. empty() never returns 0, it return TRUE or FALSE. Just use if (empty($link)) {.

Also, you probably want to use the Aggregator, or Feeds module.


Module for keeping records I am trying to develop a site with a listing for Merits and each one has a different set of requirements to be completed.  I would like to have someone that is a guest/not logged into just see a readonly version of the page and then when they log in they can see how far they are into completing it as well as seeing other users progress.  Is there a module for this already?

Not really a module there does all those things you want.

However, you might be interested in Achievements module.

"The Achievements module offers the ability to create achievements and badges similar to systems seen on Xbox 360, Playstation 3, Foursquare, Gowalla, GetGlue, and more. For a Drupal site, this could mean commenting a certain number of times, starting a forum topic, visiting the site every day of the week, or anything else that can be tracked and coded."


Redirect to a custom page after a node has been added or edited Using hook_form_alter, how can I redirect a user to a a custom page after creating or editing a node instead of the  node that was created or edited?

The current code for hook_form_alter() is the following one:

function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'custom-node-form') {
    $form['actions']['submit']['#value'] = t('Add Entry');
    $form['field_custom_email']['und'][0]['value']['#element_validate'] = array('_custom_form_validate_email');
  }
}

function custom_form_node_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node']->type == 'custom') {
    $form['actions']['submit']['#value'] = t('Add Entry');
    $form['field_custom_email']['und'][0]['value']['#element_validate'] = array('_custom_form_validate_email');
    $form['#submit'][] = 'custom_node_submit';
  }
}

function custom_node_submit($form, &$form_state) {
  $form_state['redirect'] = 'choose/your/path';
}

The code redirects the form independently from the button clicked to submit the form. If you want to redirect a form only when a specific submission button is clicked, then you should used the following code.

function custom_form_node_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node']->type == 'custom') {
    $form['actions']['submit']['#value'] = t('Add Entry');
    $form['field_custom_email']['und'][0]['value']['#element_validate'] = array('_custom_form_validate_email');
    $form['actions']['submit']['#submit'][] = 'custom_node_submit';
  }
}

function custom_node_submit($form, &$form_state) {
  $form_state['redirect'] = 'choose/your/path';
}

The form ID doesn't contain hyphens. The form ID is the name of the PHP function that generates the form (a.k.a. the form builder), and a PHP function cannot contain hyphens in its name.
The form ID is passed to the implementations of hook_form_alter(), hook_form_BASE_FORM_ID_alter(), and hook_form_FORM_ID_alter(). hook_form_FORM_ID_alter() doesn't really need it, as it is called for a specific form, while the other two hooks are invoked for more than one form.
The first function is the implementation of hook_form_BASE_FORM_ID_alter(); in this case, the base form ID is "node_form" that is the base form for the node edit form.
The node edit form contains $form['#node'], which is the node object for the object being edited; "custom" is the short ID for the content type you want to redirect the users once they edit a node.
Altering $form_state['redirect'] from hook_form_alter() doesn't have any effect; it needs to be set from a submission handler.


Redirect using a path My question seems to be obvious but I really don't find the solution.
Well, I want to redirect to my view just after connexion.
I try to use $form_state->setRedirect,but It's seems it needs the route name.
I don't find the route name of my view!
How to get a route name from a path? Or to redirect using the path?

You can also use setRedirectUrl(), which needs a URL object. There are many ways to create one, for example for an arbitrary path: Url::fromUri('base:some/path')


Check for IE8 in theme_preprocess_page function I'm trying to use inline svgs for a number of logos and icons, and I was considering adding the inline svg code in a preprocess function. This seems like a good place to check for svg support (namely, whether or not it's IE8) and provide a png if needed.

Are there any native Drupal functions available to check for this in a preprocess function? Or should I instead rely on a regex match using $_SERVER['HTTP_USER_AGENT']?

I tried to search here - https://api.drupal.org/api/drupal/functions - but didn't have any luck, so any suggestions or links to other resources would be much appreciated!

Edit: To clarify on what I mean by 'inline svg code' - I want to use actual <svg> and <path> tags, not <img src="example.svg" /> to allow for greater styling control with CSS.

@AyeshK -
I agree that there are many pitfalls in user-agent and feature detection, mainly related to keeping an up-to-date library of user-agents and features. In this specific case, SVG seems to have broad support moving forward, and I'd like to only serve the png version of images to those few browsers (within our support matrix) who don't support it, avoiding additional HTTP requests for the many browsers that do. The idea of putting this on the server side comes from Adaptive Web Design / Responsive Design on Server Side (RESS).

No there is no reliable way to detect browsers. Furthermore, you should not check browser compatibility from the server-side.

You have a few alternatives:

In your module or theme, add IE-specific styles (hide the SVG, show an image instead, likewise). This is well covered in the handbook page.
If you do not need to add the stylesheet to every page, then you can add the stylesheet in your preprocess hook (#attached is recommended. See this and this.)
Javascript workaround. Again, checking the user agent is not that easy and fool-proof. You can check SVG compatibility either by using a library available, or just by trying to create an SVG element and see if it work. This and this covers it well.