Display and edit user info When a user logs in, I'd like him to see his profile info (name, address) with a link to a form to edit that info.
I thought this should be a trivial task, because it is something needed on almost every site that allows users to register. Yet, I failed to get anywhere after a couple of hours of trying and searching.

What I have now is a view (using the views module) that displays a list of all users where each one has a link to the edit page. But I only want a user to see and edit his own stuff ...

You may put template for user page like  user-profile.tpl.php
This template is used when viewing a registered member's profile page,

e.g., example.com/user/123. 123 being the users ID.

Available variables:

$user_profile: An array of profile items. Use render() to print them.
Field variables: for each field instance attached to the user a corresponding variable is defined; e.g., $user->field_example has a variable $field_example defined. When needing to access a field's raw values, developers/themers are strongly encouraged to use these variables. Otherwise they will have to explicitly specify the desired field language, e.g. $user->field_example['en'], thus overriding any language negotiation rule that was previously applied.

OR

use hook_menu_link_alter

function hook_menu_link_alter(&$item) {
  // Make all new admin links hidden (a.k.a disabled).
  if (strpos($item['link_path'], 'admin') === 0 && empty($item['mlid'])) {
    $item['hidden'] = 1;
  }
  // Flag a link to be altered by hook_translated_menu_link_alter().
  if ($item['link_path'] == 'devel/cache/clear') {
    $item['options']['alter'] = TRUE;
  }
  // Flag a link to be altered by hook_translated_menu_link_alter(), but only
  // if it is derived from a menu router item; i.e., do not alter a custom
  // menu link pointing to the same path that has been created by a user.
  if ($item['link_path'] == 'user' && $item['module'] == 'system') {
    $item['options']['alter'] = TRUE;
  }
}


How do I prevent an entity to be saved on update depending on conditions? I use content moderation, recently present in drupal 8 core, for editorial workflow.

I'd like to prevent the entity from being saved in an update if the current user is the author of the document.

how could I achieve that ?

this does a redirection but the entity saves still does happen

 function hook_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {

 if ($entity->getEntityTypeId() !== 'content_moderation_state' ) {
    return;
}

$article_id=$entity->get('content_entity_id')->getString();
$article = \Drupal\node\Entity\Node::load($article_id);
 if($article->bundle()=='article') {

    $author_name=$article->getOwner()->getAccountName();
    $current_user_name=\Drupal::currentUser()->getAccountName();

    $moderation_state = $entity->get('moderation_state')->getString();

    switch ($moderation_state) {
        case 'peer-reviewing':

           $author=$article->getOwner();
           $current_user=\Drupal::currentUser();

            //$entity= $entity->original;
             //if author same as current user:
            drupal_set_message(t('original author cannot be reviewer.'), 'error');
            $url = $base_url.\Drupal::service('path.current')->getPath();
            $response = new Symfony\Component\HttpFoundation\RedirectResponse($url);
            $response->send();
            return;

 }

Could you not instead implement a hook_form_alter and do your condition checks, and hide/remove the submit button if it is the same user trying to review?

You could set the same message at the top of the form and not have to do any redirects.


How to set an action to unpublish a comment with rules? The rules modules has default actions setup to unpublish nodes but not comments.
Do I need to use PHP to unpublish a comment?

If you choose the action "Set a data value" and a comment is visible to the action (e.g. because the triggering event is "After saving a new comment") then the data selector will let you choose

comment:status

which you can then choose to set to "Published" or "Unpublished", or (via a data selection) to another available value.


Is it posible to use taxonomy terms in Context module? We are developing a Drupal 8 site and we need to create an specific sidebar with Context module using Taxonomy Term. In D7 module version is very easy: you can select an specific taxonomy term... but in Context for D8 we cannot find this option. We only find Vocabulary.

Is it not possible in D8? Or in other words... how we can do it?

Take a look at
Using Block Visibility Groups to Create Conditional Layouts in Drupal 8 about solution,
and the
Term condition module,

it works for me.


How do you rename the machine name of a content type? I have this content-type that i created titled: "Engineering".
1500 hundred nodes later management wants me to rename it : "Staff". I can easily rename the label but how do i rename the machine name? Does anyone have any success renaming a content-type machine name that is loaded with content/revision and relationships?
It is sometimes impossible to predict these kind of changes. How do we rename the machine name a a content-type.
i have tried the instructions from this article below : https://medium.com/@philw_/how-to-change-a-content-type-s-machine-name-in-drupal-8-33fc3c0520dc with no success.

Error: bundle name cannot be changed.

I will be trying the following:
export the database out.
find and replace the old content-type machine name with the new name
I will also rename any tables named after the content type in the process
re-import the db
I will see how that works out.

I disagree with most of the comments above simply stating: don't change the bundle machine name. These don't answer the poster's question.
This was a simple task in Drupal 7; but due to the added complexities in Drupal 8 it was decided to attempt to remove this ability. See this issue for history:
#2172843 Remove ability to update entity bundle machine names.
That being said, if you do a database search/replace on the machine name this should do what you are looking for - BUT beware, some of those machine names are embedded in serialized data (e.g. key_value table) and you will need to modify the json string size if the machine name you are replacing is a different length than the new name.


How to add Chosen JS library to theme? We are attempting to figure out how to properly add Chosen library to our custom theme. The main reason for doing this is to be able to add the Chosen JS files, but use a custom css file where we can control the output.

After reviewing Chosen Module we found that it adds a lot of bloat that we don't necessarily need and have found it difficult to override the css that is used.

Here is what we tried, but cannot get it to use the chosen.min.css and need help to see how it can be done.

mytheme.libraries.yml file

chosenjs:
    version: 1.x
    css:
       theme:
          css/chosen.min.css: { minified:true }
    js:
      js/chosen.min.js: { minified:true }

The chosen.min.js has the necessary settings to get the functionality we needed.

If the code posted above is correct, the indentation is off. It should look something like this:

search:
  version: VERSION
  js:
    extras/js/drupal/search/sort.js: {}
    extras/js/drupal/search/filter.js: {}

See how js is not indented under version?

The second part of it is you have to tell Drupal to load it either sitewide, or on demand:

Sitewide, you need to declare this in your theme info yaml:

libraries:
  - mytheme/search

If you want to do it on demand, something like:

/**
 * Implements hook_page_attachments_alter().
 */
function mytheme_page_attachments_alter(array &$attachments) {
  $current_path = \Drupal::service('path.current')->getPath();

  // We really want to minimize the loading of these two libraries
  // for anonymous users. so far, we only need it on any /search* path.
  if (preg_match('/\/search+/', $current_path)) {
    $attachments['#attached']['library'][] = 'core/drupal';
    $attachments['#attached']['library'][] = 'core/jquery';
    $attachments['#attached']['library'][] = 'mytheme/search';
  }
}

Or you can put it in a specific twig template i.e. node.html.twig like this

{{ attach_library('mytheme/search') }}


How do you create a block of fields to a second Profile2 using views? I can create a list of profiles of a specific type. That works great. But what's stumping me is I need a view that has fields that pertain to a specific person. Say for instance you are on Bob's "personal" profile and there is a block that has information for bob's second "business" profile (or any other member's other profiles for that matter). How do I create a block for this profile with relative fields that only populates on demand?....

Using Configuration

You can use the Views module to access the Profile2 fields.

Below is a quote from ltiong on Drupal.org regarding accessing fields from multiple profile types.  The same process applies to accessing a single Profile2 type.

  5.1 create View (Show:User)
  5.2 add relationship, (User:Profile); give the Identifier a unique name ie 'MainProfile'; select a single checkbox for 'Profile type',
  in my case 'Main profile';
  5.3 add another relationship, (User:Profile); give the Identifier a unique name ie 'EducationProfile'; select the other checkbox for
  'Profile type', in my case 'Education profile';
  5.4 add Fields to view; select Profile2 field items; use Relationship dropdown in 'Configure field' to associate w/ correct
  relationship;

You can output as a Block, and use the Page URL to retrieve the correct user ID to load. (For your views context)

Using Code

You can use the profile2_load_by_user(); function to programmatically retrieve Profile2 data.

$profile_data = profile2_load_by_user($user->uid);

See also: profile2_load_multiple()


Within a node, how can I reference the value of a field of a node associated to the current user through a node-reference? I'm creating a customer extranet for my client. The users are my client's customers. Within the body of a page node, I need to display the ID of the customer (company) to which the current user belongs.

Here's how I've set it up so far:

Drupal 7
I have a Customer content type that has a field called customer_id (among other things).
I have added a node-reference field to the User fields that references one Customer node. (In other words, each user is associated with one Customer.)

So in his profile, the current user has a node-reference value pointing to a Customer node, and I need to retrieve and display (in a page node or block) the value of one field (customer_id) in the Customer node being referenced in the current user's profile.

I've been going through several Drupal books and whatever module documentation I can find, and I've been experimenting with various views using the the Views module, but I'm still pretty stymied. Can somebody point me in the direction of a good way to implement this?

Thank you for your help!

Chris

You should be able to do this through Views arguments, with the nid of the customer node as the argument. Then that node's fields should be available to you from there.


Drupal does not recognize GD and PDO sorry if this has been answered already, but my searches brought me to nowhere.

I have just installed LAMP environment on Amazon EC2 instance. It runs on:

Ubuntu precise 12.04 amd64 server
PHP Version 5.3.10-1ubuntu3.4
MySQL 5.5.28
Apache/2.2.22 (Ubuntu)
Drupal 7-18

Drupal installation tells me that I have not GD enabled and PDO extension are disabled. However, looking at phpinfo() I have :

GD Support  enabled
GD Version  2.0
FreeType Support    enabled
FreeType Linkage    with freetype
FreeType Version    2.4.8
T1Lib Support   enabled
GIF Read Support    enabled
GIF Create Support  enabled
JPEG Support    enabled
libJPEG Version unknown
PNG Support enabled
libPNG Version  1.2.46
WBMP Support    enabled

Directive   Local Value Master Value
gd.jpeg_ignore_warning  0   0

and

PDO

PDO support enabled
PDO drivers mysql

pdo_mysql

PDO Driver for MySQL    enabled
Client API version  5.5.28

Directive   Local Value Master Value
pdo_mysql.default_socket    /var/run/mysqld/mysqld.sock /var/run/mysqld/mysqld.sock

So, in theory everything must work, why does Drupal not recognize them? I haven't changed anything at all from the clean install of LAMP. May I be missing something then?

Thanks in advance,
maxim

Just to be sure the install is all good, try

sudo apt-get install --reinstall php5-gd php5-mysql

Also, make sure you don't have any odd php.ini file in your drupal root.


Which configuration settings should be used to prevent "No statistics available" in the Admin Reports? When I view the Admin Reports like Top Referrers, Top Pages, Top Users, etc (by navigating to /admin/reports), those pages simply say "No statistics available". I am using Drupal version 7 with an admin account with all permissions.

Google Analytics is successfully collecting this data, so I don't understand why Drupal is not. I can't find any configuration setting to enable these reports. Could this be an issue with my webhost?

I apologize if this post is vague. I just don't know how to go about diagnosing this problem.

This has nothing to do with Google Analytics or your Provider. Check /admin/config/system/statistics. This will populate your /admin/reports/hits.


Adding autocomplete for text-field I tried to implement an autocomplete in text-field for drupal 8 in my custom module

all I wanted was to fetch and display the likely title I typed via autocomplete
so declared a public function autocomplete within a class  in DefaultController.php
in folder directory -->mymodule/src/Controller/DefaultController.php

<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;

class DefaultController extends ControllerBase
{
    public function autocomplete($string)
    {
        $matches = array();
        $db = \Drupal::database();
        $result = $db->select('node_field_data', 'n')
        ->fields('n', array('title', 'nid'))
        ->condition('title', '%'.db_like($string).'%', 'LIKE')
        ->addTag('node_access')
        ->execute();

        foreach ($result as $row) {
            $matches[$row->nid] = check_plain($row->title);
        }

        return new JsonResponse($matches);
    }
}

then created an EditForm.php in
folder directory -->mymodule/src/Form/EditForm.php

<?php

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class EditForm extends FormBase
{
    public function getFormId()
    {
        return 'mymodule_edit_form';
    }

    public function buildForm(array $form, FormStateInterface $form_state)
    {
        $form = array();

  $form['input_fields']['nid'] = array(
    '#type' => 'textfield',
    '#title' => t('Name of the referenced node'),
    '#autocomplete_route_name' => 'mymodule.autocomplete',
    '#description' => t('Node Add/Edit type block'),
    '#default' => ($form_state->isValueEmpty('nid')) ? null : ($form_state->getValue('nid')),
    '#required' => true,
  );

        $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Create'),
  );

        return $form;
    }
}

also created mymodule.routing.yml

  mymodule.autocomplete:
  path: '/mymodule/autocomplete'
  defaults:
    _controller: '\Drupal\mymodule\Controller\DefaultController::autocomplete'
  requirements:
    _permission: 'access content'

still autocomplete functionality not getting implemented ?
Can anybody point me what am i missing ??

If you want to select an entity, then there is a way easier way to do that. Drupal 8 has a standard entity_autocomplete field type, just specify your form element like this:

$form['node'] = [
  '#type' => 'entity_autocomplete',
  '#target_type' => 'node',
];

See Custom autocomplete field for more information.

Also, never do database queries against node/entity tables. Use \Drupal::entityQuery() for that.


View to filter a list of nodes which has TWO taxonomy terms I have a content type - 'video post'.
This content type has several taxonomy terms associated with it, 'star rating' and 'warm up'.

The 'star rating' taxonomy is a list of numbers: 1, 2, 3, 4

The 'warm up' taxonomy has 3 options: warm up, long, cool down.

What I've been trying to do is to create a view block to display on the content type 'video post' so that it displays a list of nodes which have the exact same set of taxonomy terms as the one currently being viewed.

So if I go to node/1 and this has these two taxonomies as follows:

star rating - 2

warm up - long

I only want nodes to display which also have this same combination of terms.

It would also be great if I could exclude the current node from the list too, as this is obviously not required.

I've tried just about everything that I know, but I always seem to get results that I don't want.

Any help is greatly appreciated.

Download the Views PHP module:

  This module allows the admin account (user 1) to add fields, filters
  and sorts to views which use PHP code. It also supports additional
  accounts when the core PHP Filter module is enabled.

In Views:

create a new View of 'video post' content type, as a block and set it up to show all entries for now, in the format and layout you desire
add a contextual filter for the star rating field (you will need to adjust the field names appropriately):

Provide a default value, PHP code:

$node = menu_get_object();
return $node->field_star_rating['und'][0]['tid'];

add another contextual filter for the warm up field:

Provide a default value, PHP code:

$node = menu_get_object();
return $node->field_warm_up['und'][0]['tid'];

The first line retrieves the page object (which should only ever be a video post node if the block is set up properly), then returns the term ID associated to the current node as a contextual filter to the view. This assumes a single language site.

add a regular filter, Global PHP code:

$node = menu_get_object();
if($data->nid == $node->nid) return true;
else return false;

The first line again retrieves the page object, and compares its node ID with the node ID of the current entry, filtering it if they match. It may appear backwards, but that's how the Global PHP works for some reason. Returning true excludes the row.

under admin/structure/block, set the view-block to show where you want on the page, restrict it to show only on the content type video post.


Add field to vocabulary itself I have a situation where I would like to add a field to a vocabulary itself.  In other words, I need an editable field on the form that normally appears at /admin/structure/taxonomy/my_vocabulary/edit and not a field that appears each term in the vocabulary.  Unfortunately, the description column in {taxonomy_vocabulary} is too limited for what I need.

What is the best way to go about this?  If possible I would like to avoid making a custom module with a custom table, form-alters for the vocabulary edit page, etc.

Thanks.

So the basic problem is that a vocabulary is not fieldable. In theory this is easy to fix, but I don't know if they lack this functionality because it would cause technical difficulties, or to avoid confusion users.

To make a vocabulary fieldable, implement hook_entity_info_alter:

function hook_entity_info_alter(&$entity_info) {
  $entity_info['taxonomy_vocabulary']['fieldable'] = TRUE;
}


Is there any way to force blocks created by views to display even when there is no result? I have similar question with "Display a block even if it is empty" about blocks generated with views 3.5.

Views has a somewhat hidden feature for setting the behavior when you have no results.

If you edit the view and click on Advanced, you will see some new settings:

Click on add next to NO RESULTS BEHAVIOR.  You will then get a modal with a ton of choices.  You should be able to use the textarea or markup options to plop in a &nbsp;  This should force the block to not be "empty".  You could also set a message, etc.

You can also always show the advanced options if you visit admin/structure/views/settings

I typically always set "Always show the master display" and "Always show advanced display settings".  There are some other useful settings on admin/structure/views/settings/advanced


How to run a drupal application in github? I am trying to setup Drupal Application in Github and was able to  successfully setup the instance and moved the project to github.

Can anyone help me with as how to execute a drupal application in github,as I am finding tools to run html files but executing a drupal files seems to be a tedious task.

You can not execute Drupal in Github, just because Drupal requires a server running PHP, which isn't supported by github.

  Github Pages is not a full-featured web host. It will not execute PHP, or any other arbitrary code.
  Source

You could convert your Drupal site into a static site and upload it on github, but the website would not be dynamic anymore. If you decide to do this, you could host it using Github pages, but you would not be executing Drupal; instead, you would be going to show a static version of your Drupal website.

If you wish to add a static version of your website for Drupal 7, you can look at the Static Generator module. If you are running Drupal 8, you can use wget --mirror http://example.com and this will provide copy of your site's HTML.


Saving form data of forms modified with form_alter hook I understand how to add stuff like checkboxes and fieldsets to existing forms (e.g. the form displayed on the node edit page) using _form_alter. But what I don't understand is how to collect the input and store it in a database table of my choosing (ideally with db_insert). Let's say I've added a checkbox to the fieldsets at the bottom of article_node_form (the form which appears when editing content type article):

$form["Email Notifications"] = array(
    '#type' => 'fieldset',
    '#title' => 'Email Notifications',
    '#collapsible' => 'true',
    '#group' => 'additional_settings',
    '#required' => FALSE,
    'email_notify' => array (
        '#type' => 'checkbox',
        '#title' => 'Notify users of changes to this page',
        '#default_value' => 0,
        '#required' => FALSE,
)

How do I collect this data an store it in a database?

Exactly like you alter a form to add custom fields, you alter it to add custom validation and submit handlers.

It should be:

$form['#validate][] = 'custom_validate';
$form['#submit'][] = 'custom_submit';

use those function to control the additional user input and store them later.


Naming conventions in Media entity vs File entity The Media Library experimental module in core introduces a generic media type "file",  while File entity calls the same thing "document". For comparison, the other bundle names are consistent between the two: image, audio, video.

Why did Media Library in core decide to change the naming and precedence set by the File entity module in contrib? I'm trying to wrap my head around the domain model here, to ensure I'm thinking about a Media Library in the correct way.  From an end-user perspective, an image and a video are both files whereas a document is neither an image or video, so the delineation in File entity aligns better with reality.

This decision affects modules in the contrib space that want to build features around the emerging Media functionality in core, so an understanding of the domain model and intended usage will help build things up correctly, instead of taking things in parallel and incorrect directions.

After a bit of reading around, it seems that the core Media module was never adapted/updated from the File Entity module; it was a port of the Media Entity module (which didn't have its origins in File Entity either). See Bring Media entity module to core as Media module for the full details.

The "file" media type did have its origins in a plugin named "Document", provided by the Media entity document module, which provided the same basic functionality as File Entity's "document". So there may have been some crossover in their evolutions somewhere along the line.

But even so, reading through the proposal to Add "File" MediaSource plugin, it becomes clear that there was no intention to port the "document" type over in its previous form, rather just to use it as a starting point for the generic file type. From comment 24 on that issue, in response to a previous query of I'm wondering whether file should be document instead? File seems really generic as image is also a file:

  26-1: As commented with @dawehner on the sprint, the idea is that the Image handler extends this plugin, so this name is probably the most appropriate in this case. A "Document" plugin can be created also extending "File", if needed to expose specific UI improvements for documents.


Why authenticate request returned 403 after successful login? I have front-end with AngularJS and its connected to drupal backend. I am using drupal services module for rest api.
I have an angularjs web app in subdomain [admin.example.com].
My authentication subdomain [account.example.com] developed with drupal 7.
I can login successfully to account.example.com from admin.example.com using http request from angularjs, so I stored newly generated token. But when i try to collect user data from [account.example.com] using previously stored token, i get 403 status. I'm sure my token is correct.
This work well with chrome disable-web-security mode, when i try from regular mode its response me 403. but i did not get any cors error.
Someone please help me, i'm stack on this stage...
My Apache Conf file [account.example.com]:

<VirtualHost *:80>
    ServerName account.example.com
    ServerAlias account.example.com
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/example_account

    <Directory "/var/www/example_account">
        AllowOverride All
        Require all granted
        Header always set Access-Control-Allow-Origin "*"
        Header always set Access-Control-Allow-Headers "Content-Type, Accept, Authorization, X-CSRF-Token"
        Header always set Access-Control-Allow-Methods "GET,POST"
        Header always set Access-Control-Allow-Credentials true
    </Directory>

        #RewriteEngine On
        #RewriteCond %{REQUEST_METHOD} OPTIONS
        #RewriteRule ^(.*)$ $1 [R=200,L]

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

Here is header requests:

Try to be specific with the ACAO header, like
Access-Control-Allow-Origin: admin.example.com

The wildcard is not really appreciated, browsers may treat this as high security risk and block the request.


What is the datatype? The data I need are reported by Devel to be objects of stdClass.
What is that class? Is it a $node, $term or $page? Without guessing, how do I determine what that object is, in order to extract data?

So, you have a variable. Lets say $object, and you call dsm, dpm, dvm or one of devel's other debugging functions to inspect it:

$node = node_load(1);
dpm($node);

Devel gives you something back like this:

object(stdClass)[79]
  public 'nid' => string '1' (length=1)
  public 'type' => string 'profile' (length=7)
  public 'language' => string '' (length=0)
  ...

The stdClass part just means that its a generic empty class, not any particular type of object. So, you can access all of its properties using standard object notation, but there are no object specific functions that you can call from the object.

So, for example, you can call:

$nid = $node->nid;
$type = $node->type;

But you can't do anything like this:

$result = $node->some_special_node_function();

Because there are no special node functions.

In Drupal, most things that get retuned as objects are just generic objects without any type special attributes or functions.


Entity field query condition to match multi-value field Using EFQ, I want to add a fieldCondition that has to match both values in a multi-value field (fixed at two values). The following doesn't seem to work:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
       ->entityCondition('bundle', 'node_type')
       ->fieldCondition('field_myfield', 'target_id', array(
          $id_1,
          $id_2
        ), '=');

This returns the error:

  PDOException: SQLSTATE[21000]: Cardinality violation: 1241 Operand
  should contain 1 column(s):

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
       ->entityCondition('bundle', 'node_type')
       ->fieldCondition('field_myfield', 'target_id', array(
          $id_1,
          $id_2
        ), 'IN');

For reference see https://www.drupal.org/docs/7/creating-custom-modules/howtos/how-to-use-entityfieldquery-for-drupal-7


Get an image from an article/entity How do I easiest get an image (its path) from the article content type included in Drupal 8?

What I have is an entity. Using $image = $node->fields['field_image'] gives me a hell of a structure, though.

Is there no easier way to get the image path? Also I cannot find the URL in this, what I get is some sort of target_id (the file ID?).

Didn't see this before.

The shortest way to get the referenced entity for a single-value field is this:

$node->field_image->entity->url()

You can also specify the delta explicitly:

$node->field_image[0]->entity->url()

This works with a lot of ArrayAccess and __get() magic.

See also the great cheat sheet at http://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet. and https://www.drupal.org/node/1795854 and the other documentation pages there for more information (still very much work in progress).


How to create separate user types? I want to create separate user types. By "type", I don't mean just roles. Let me explain by an example.

User comes to my website and he wants to register either as "User" or "Editor". Both these profiles will have very different fields and different permissions.

Now, I can use profile2 module to create different profiles and restrict them to different roles. Furthermore, I can use Autoassignrole module to assign the desired role to the user during registration. This is all fine.

Now, what I want is separate links for registration for both roles. When user clicks on any one of them, only the relevant "profile2" profile should be shown in the form. The problem is that on the default registration form, both profiles are shown.

One could say that I could just uncheck the option in the "profile2" profiles and not show them during registration, and user can enter his profile after registration. But here is the thing: I want some of the profile fields to be entered during registration itself. This is required for my case.

So, now you get what I mean by "type"? It is surprising there is no straightforward solution to this basic functionality. How are you achieving this?

This should work (at least it did for me). Put this code in your template.php and adjust accordingly.

I created a user field called 'type' as a select list (for future consideration). You could just as easily use a hidden field or a text field if you don't want the user to be aware of a difference (NOT FOR SECURITY PURPOSES - THIS IS VERY INSECURE).
Make it mandatory.

given a url of mysite.com/user/register?type=one  this will assign the field named 'type' to 'one', otherwise
it will assign it 'two' by default.

I added some comments to help with the code, but you can remove that later. Obviously you will need to adapt this to the profile selection - I don't profile2 setup on my test site so I can't really get into that, but this is the basics, and I can help guide through the rest.

function theme_form_alter(&$form, &$form_state, $form_id) // change theme to your theme name
{
    if($form_id == 'user_register_form')  // only check on user registration form
    {
      $urlGet = drupal_get_query_parameters(); // get URL parameters ?type=one, etc
      if($urlGet['type'] == 'one') // check ?type= against expected
      {
        $form['field_type']['und']['#options'] = array('One' => 'One'); // set select list option(s)
        //$form['field_type']['und']['#options'] = array('One' => 'One', 'Three' => 'Three'); // for multiple values
      } else
      {
        $form['field_type']['und']['#options'] = array('Two' => 'Two'); // default value
      }
    }
}


Make the user avatar picture mandatory In Drupal 7 is it please possible to enforce all new users to upload an avatar picture during the registration process? I.e. how to make the user picture field mandatory?

When I try to edit the registration form fields at /admin/config/people/accounts/fields there are no settings for the user picture, I only see it being an account widget:

Sounds like you need the register with picture module


How to position javascript file as the last one to load? In Drupal 8 the weight for javascript files in libraries is not supported, or at least only negative values are allowed, which means I am only able to position them at the top of the list (i.e. load it first) but not at the end of the list.

I have a library for the Zurb Foundation and its initialization has to be loaded last. It is a requirement for my theme and I don't want to override a template to fix this problem.

How is one supposed to do this?

I was surprised hear that "only negative values are allowed" as JS weights, so I had to hunt that down.  And it's true... https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Asset%21LibraryDiscoveryParser.php/function/LibraryDiscoveryParser%3A%3AbuildByExtension/8.2.x There is an exception error message that says, "The $extension/$id library defines a positive weight for '$source'. Only negative weights are allowed (but should be avoided). Instead of a positive weight, specify accurate dependencies for this library."

This of course reminded me that, yes indeed, dependencies were added/improved in Drupal 8 so that we didn't have to worry about this.  Oddly enough, there are several core JS files that define weight, so I guess we are only part way there.

So, this is just a long-winded way of saying, what scripts does the Zurb Foudation depend on?  And can you list those dependencies in your libraries file under the Zurb script?  See https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module for more info.


Asserting a failed login attempt on Simpletest I want to test a module that adds an additional login validation clause. Only users whitelisted somewhere else are allowed to log in to the system.

In order to test this behaviour with Simpletest, I would like to assert that a random user has no access to the system.

I have tried to create this random user and then to call drupalLogin(). Unfortunately, my test fails because drupalLogin() is checking whether the log in succeeded, by calling assertLink() internally.

This is what I have tried:

    $user = $this->drupalCreateUser(array());
    $user->roles[] = 'authenticated user';
    user_save($user);

    // Try to login with it
    // It fails, because of the additional validation performed by my custom module
    $this->drupalLogin($user);

    // I would like to assert it here instead:
    $this->assertFalse(isset($this->loggedInUser->uid));

What should I do in order to avoid the assertion to fail at drupalLogin(), so that I can assert it myself?

Any help will be appreciated.

In case someone else wonders about this... It wasn't difficult, but I didn't realise at first that it can be done by copying part of the DrupalWebTestCase::drupalLogin() source code:

$edit = array(
  'name' => $user->name,
  'pass' => $user->pass_raw,
);
$this->drupalPost('user', $edit, t('Log in'));

And then asserting that the user could not log in:

// Assert that the user is not logged in
$this->assertNoLink(t('Log out'), 0, t('User not logged in.'), t('User login'));


Why can 'Others' read settings.php by default? By default, settings.php has its permissions set to 404, which means 'Others' can read the file. Why not set it to 400, so that only the user can read the file? Thanks.

The reason for this default, I believe, is because on some hos plans (e.g. bargain basement shared hosting), the web server user is not by default the owner of the file.  On some hosting plans, it may not even be an option to use commands such as chown and chmod to set up things exactly the way you want.

The web server user must be able to read this file to get access to DB credentials, and on such hosting plans, allowing "Other" to read is the only way to achieve that.  (Having 400 as the default would most certainly create a deluge of support requests from people unable to figure out why Drupal can't access their database.)

If you know what you're doing, it is OK to 1) make sure the file is owned by the web server user, and 2) set permissions to 400.


Enforce unique constraint on a field For a content type (place), on creation, as the user is entering the name field, I would like to check the previous records for that field. If there is a match, I will present it to the user to prevent duplicate entries. is there way to do this?

Check out the Unique field module.

  This module performs additional validation when a node is created or updated by a user to require that a node's title, author, language, and CCK fields are unique within a given context.


Insert *whatever* every nth row in Views I am looking for a solution to insert "something" every nth row in a view.  Technically, that "something" will be an Ad, but in Drupal terms it could be a block, a node, an entity, custom html row...really anything that can point me in the right direction.

In under Theme: Information you'll find Style output: views-view-table.tpl.php .... Override that. I selected the Theming info as opposed to other template overrides available because that is the one that has a foreach for rows. In your override you can add a counter to the foreach() along with an if($counter%10 == 0) { ... } with some markup or call to a block or something like that.


Create theme file for content type? In Drupal 6, if you had a content type with the system name "stock-photo", you could override it using:

node-stock-photo.tpl.php

How do you do this in Drupal 7?

I think MYTHEME_preprocess_page() function doesn't need for it.

The node--[node-type].tpl.php is only enough for it.


setup multisite into multi server I developed multi site using Drupal 7.

example.com
site1.example.com
site2.example.com

All subdomains are using the same codebase in /sites/site1 and /sites/site2.

Is it possible to host SITE1 in a different hosting server with the same codebase?

You need to read this article:
Multi-site - Sharing the same code base
https://www.drupal.org/docs/7/multisite-drupal/multi-site-sharing-the-same-code-base

Create directories for your each site
Copy config files to each directory
Create a database for each site
Make a symbolic link for each site:

$ ln -s . site1
$ ln -s . site2


Addresses Module - Province (State) Used to Be a Drop-Down I am having trouble with the addresses module (version 6.x-1.12) running on my Drupal 6.28 site. Recently the addresses module stopped showing a drop-down menu for the Province (State) field on my custom content type. I am not certain when this happened, or what caused this change. I did some major upgrades to the site, tested everything, and thought this was working after the upgrade.

This above image shows what I'm talking about. This is from my profile, in case anyone cares about the confidential data I am showing the world.

The above image shows the configuration options for the addresses module I have installed. I don't see any options to make it so that the province is a drop-down, despite the fact that the module info page says it has all the provinces for all the countries it supports...?

The above image shows the address field configuration options for my custom content type using the address field. It's called a uprofile or user profile, and stores additional information about the user.

Thank you very much for taking the time to look at my question. I tried to be as complete as possible. If you want to try to create an account to see what I am talking about (or to be an extra in a movie filmed in New Mexico!) the site is here.

A quick look suggests that you put in a patch to the module that didn't get re-rolled into the module after your update as when I installed the module on a testbed it didn't work until I did :)

Anyways, if you look at https://drupal.org/node/244471 and scroll on down to comment #63 you'll see the patch.

If you want to just edit up the code directly, you want to change

  // Invoke addressfieldapi to allow modules to add their own addresses fields.
  // Then update these fields with the global settings for each field instance.
  $extra = module_invoke_all('addressesfieldapi', 'form', $fields, $values);
  foreach (element_children($extra) as $ename) {
    if (isset($settings[$ename . '_label'])) {
      $extra[$ename]['#title'] = t($settings[$ename . '_label']);
    }
    if (isset($settings[$ename . '_desc'])) {
      $extra[$ename]['#description'] = t($settings[$ename . '_desc']);
    }
    if ('textfield' == $extra[$ename]['#type'] && isset($settings[$ename . '_size'])) {
      $extra[$ename]['#size'] = $settings[$ename . '_size'];
      // $extra[$ename]['#attributes'] = array('class' => 'text');  // REMOVE OR COMMENT THIS LINE OUT

      // ADD THE FOLLOWING:

      if (isset($extra[$ename]['#attributes']['class'])) {
        $extra[$ename]['#attributes']['class'] .= ' text';
      }
      else {
        $extra[$ename]['#attributes'] = array('class' => 'text');
      }

      // THIS IS THE END OF THE NEW CODE

    }
  }

around line 253 in addresses.module.  That made it work for me anyway.

Oh, if you are interested, the reason it didn't work is AJAX couldn't find the class of the province field, as further on up the chain it was being added, but then overwritten here.


Add a span/class to a field I've found a way to add a style to a region. The link is /admin/structure/ds/styles.

I've found a way to specify a style for my Title. We can choose the "class" attribute of  title property.

Howe can I add a specific class/span to my "publish date" field?

How can I do that with Display Suite?

Enable the module display suite extras
Define a display suite layout. Once the layout is specified you get the 'custom classes tab'.
Enable Field Templates in the display suite configuration screen admin > structure > Display Suite. Then select "Field Templates". Check "Enable Field Templates. URL is admin/structure/ds/list/extras
Define some classes. Using the "CSS classes" tab in the display suite settings define some "CSS classes for fields". URL is admin/structure/ds/classes
Ensure that the view mode that you are using is managed by display suite. Under "Manage display" accessed either via the node editing screen or admin > structure > content types check the box next to the view mode being used. In the format column the 'Field template' text should now be shown.
Using the cog icon on the right, edit the field template setting. Select the CSS style chosen in #4

With images the process is
1. enable display suite extras
2. Define a display suite layout

Enable field templates

Define classes

Manage the view mode

Select the classes


Should we use Drupal Commerce for a real estate site? we are about to build a real estate website for a property agency. The site allows visitors to look for apartment for rent/sale.

Property search is actually the first main functionality. Users can search real estate with its attributes such as: price, land area, building area, number of room, facilities, etc. Second main functionality is they can also filter the property list (search result), sort or paginate it.

The visitors can make a contact too, just a simple form with anonymous user information and an ID of real_estate content type maybe. Users don't have to login to contact.

The following features is not needed: User authentication, Checkout Progress, Payment, Cart, Order, Comment, Discount, Shipping, Taxing.

We wonder if we can use Drupal Commerce to get quickly some out-of-the-box features (advanced search, filterable/sortable list) or it's better to build things from scratch.

PS: We've found "A Real Estate Website Using Drupal" but we still wonder if the Drupal RETS Real Estate Framework (dRealty) module can fulfill our requirements and if the first answer is still consistent as it has 6 years old.

I think you should definitely consider Drupal Commerce or Commerce Kickstart for this, because it seems to have everything you're looking for.

About the facilities you don't need, like "Checkout, Payment, Discount, Shipping, Taxing, etc": that's a matter of NOT enabling the corresponding modules you get with it.


How to display term images instead of term names in the term selection process? I have a content type with a term reference field (check boxes widget, vocabulary: Category) from which every user has to choose one term to be attached to his node.

I have also added an image field to the Category vocabulary to attach a default image to each term.

How can i display the term images and the term names instead of only the term names in the term selection process when creating the node? Is there a module out there?

Or maybe using hook form alter. Any guidelines?

Looks like the Taxonomy Term Reference Tree Widget module gives you the ability to add images to term references. Here is a quote about it (from the module's project page):

  ... provides an expandable tree widget for the Taxonomy Term Reference field in Drupal 7. This widget is intended to serve as a replacement for Drupal's core Taxonomy Term Reference widget, which is a flat list of radio buttons or checkboxes and not necessarily fit for medium to large taxonomy trees.


How do I change the node title when saving it? For a content type (Article), when I create a new node and save it, I want to append a field value (for example, Location) to the node title.
There seems to be great answers using custom plugins (Modify the node title with the node ID before saving it) and even modules (How do I build the node title from field values when saving the node?), but they're not applicable to Drupal 9.
If the suggested solution requires creating custom module and overriding a function, then please direct me to some implementation guide and specify files locations as I'm a newbie in writing Drupal code.

To do this without writing code, the module you want for Drupal 9 is Automatic Entity Label.  Nodes are entities, so you can use this to set the label (title).


How can I require multi-user approval for a node? I have a created a "Team" node type, and I'd like a single user to "invite" people onto the team, but require each team member's approval.

I currently have workflow states of "Approved" and "Unapproved" linked to the "Team" type, and an unlimited "User Reference" field attached to the "Team" type, but I'm not sure how to use Drupal's built-in approval mechanism appropriately. I could create an intermediary node type ("RSVP", maybe) with an "Approved/Unapproved" boolean field (or Workflow status, I suppose) and a "User Reference" with limit 1, and then link the RSVPs to the "team" type., but this seems a little kludgey.

Maybe write your own module

#1 push message for each team member

#2 for each member approval check if this it's all, if yes then push invite to new member/user

#2b if new member accept invite then add her/him to the group (you can do it with og API e.g.)

#3 if someone from group disapprove then remove invite from awaiting list

#x you can add some settings page so e.g. if 50% of team members agree with invitation then proceed to #2 and invite new user


How to get escaped file description from node? I enabled file description for node and I want to display descriptions close to the download links.
I would like the description be secure. I tried

$items = field_get_items('node', $node, 'field_files');
foreach ($items as $item) {
  echo $item['description'];
}

but there is html code parsed.

I can use just check_plain() function on the description, but is there any way to do it better?

As stated in the comments to official documentation:

  It is worth noting that field_get_items() returns raw values the use of which can be a security risk. Passing the raw values through field_view_value() handles the sanitizing of the values.

Links added by me.


Parsing json with jquery Wrapping one's head around the json/ajax/jquery relationship is quite a battle for someone new to it. But what a fun puzzle! One of the most confusing parts has been how to frame this question.

Using php in my module file, utilizing db_query function, the database query has been made, and now we're going to loop through the results, create json data and encode it and send it back to jquery for re-inclusion into our website.

$json = array();
        foreach ($query as $row) {

      $fid = $row->thefid;
      $file = file_load($fid);

      $jsonelement=array(

         'title' => $row->title,
         'path' => $file->uri,
         'style_name' => 'swatch'

        );
          array_push($json,$jsonelement);
    }

        // encode to json
        $jsonstring = drupal_json_encode($json);

        //output the json string
        drupal_json_output($jsonstring);

This returns this json string:

[{"title":"Test Swatch 5","path":"4DS_AB_BrittanyBeige_CAT.jpg","style_name":"swatch"},{"title":"Test Swatch 6","path":"4DS_AB_ArdennesGray_CAT.jpg","style_name":"swatch"}]

Where I am having trouble, is figuring out how to access each element.

A simple side example to illustrate the issue without an array :

var data = jQuery.parseJSON('{"title":"Test Swatch 5","path":"4DS_AB_BrittanyBeige_CAT.jpg","style_name":"swatch"}');

alert (data.title);
data.title returns the string Test Swatch 5, which is what I expect.

However, in the output I have (back at the top of the question) the json object(s) has an extra set of brackets around it suggesting another array that I am not sure how to access, but for now I will call it x.

My question is 2 parts and any one of the solutions will get me to where I need to be.

1) Is there a way to get the key value pairs out of the current output I have already created? Any example would be helpful.

2) Is there a way to frame the output in a way to utilize x as the name of the array so that the values can be accessed via myjson.x.title or myjson.x.path or myjson.x.style_name, etc..?

I noticed a very similar question here with no answer as well
https://stackoverflow.com/questions/1607937/how-to-parse-json-array-in-jquery

You should be able to access the JSON response objects by saying data[0] and data[1]. These will be the swatches. So instead of namespacing the objects (swatches) by name, as in "myjson.x.path" you will be able to access them by index, as in "myjson[#].path". Does it imply any limitation for your setup?

As per getting the key/value pairs, you should be able to use either jQuery.each function, or native js for (item in coll) traversal.


Login form using lightbox2 I wanted to create a site which should display an registration form in lightbox view. I tried to alter the page--front.tpl.php to get this effect but i didnt succed. The lightbox effect of the display should happen when ever the site is viewed.

jQuery(document).ready(function() {
  jQuery(".menu-item-694").triggerHandler("click");
});

can any one say how to get this effect with lightbox or whats wrong in my code displayed above.
Thanks in advance.

Try the Colorbox module, this offers this functionality.


Commerce Product listing View with category contextual filter, How to show items of (selected term and its child terms) I have a the view 'Browse Products by Category'

with the path: /taxonomy/term/%

and a contextual filter: Product: Category (field_category)

and let's say I have these categories:

Sensors

--- Accelerometers

--- Current Sensors

--- Direction Sensors

Robotics & Motors

--- Dc Geared Motors

--- Digital Servo

--- Motor Drivers

then if I selected 'Sensors', I get no products, although there are products tagged with 'Accelerometers'

Is there anyway that I can configure view to show products in sub categories.

That could be done easily when showing contents but not commerce products, case content offers a contextual filter that supports depth out-of-box.

There are two approaches to solving this problem:

Use the product_taxonomy_filter module to add the missing filter. Note that the performance impact of this module is unclear (it adds a subquery since it can't rely on the taxonomy_index table).
Build your product catalog the recommended way, using Search API. The official docs cover this use case (via adding the "Index hierarchy") processor.


Webform select option list from another submission data I have a webform (webform 1) to record data. In another webform (webform 2) I would like to use the submitted data from webform 1 in select options (Load a pre-built option list). How can I do this? Is there any module that already available to do this?

You could try the sandbox project Webform Views Select.


Export menu configuration Looking for a way to export menu configuration. The Configuration management system will export the menu itself, but not the menu links configuration. I am looking for a way to put one of those mega menus into version control to import/export through multiple environments.

If anyone has found a good way to do this. I would be greatly appreciative.

Menu links can come from 3 sources:

Views module (these can be exported when the view config is exported)
.links.yml file in a module (not possible to export)
Created menu links (Is content entities, like nodes, users, etc and is not possible to export)

I'm guessing you are creating menu links via interface, which is content. The config system can't export content, which is by design. If you wanted to synchronize content, you would need to look at the Deploy module suite. I'm not sure how well this is working atm, since it's still in alpha.


TWIG if/else to filter through templates I am trying to write a TWIG else/if statement that loops through four different templates based on the number of customers are chosen from a list. So if a designer chooses 1 customer a certain template is used to create that view, and if they choose 3 customers a different template is used.

{% if content.field_featured_customers|length == 1 %}
{% include "node--customer--featured-full.hmtl.twig" with content.field_featured_customers %}
{% elseif content.field_featured_customers|length == 2 %}
{% include "node--customer--featured-split.html.twig" with content.field_featured_customers %}
{% elseif content.field_featured_customers|length == 3 %}
{% include "node--customer--featured-3block.html.twig" with content.field_featured_customers %}
{% else %}
{% include "node--customer--featured-carousel.html.twig" with content.field_featured_customers %}
{% endif %}

This is what I have tried so far, but nothing is rendered. I have created templates for all of the different views I am trying to display. Here is an example for the featured-full.html.twig

{{ content.field_logo }}

{{ content.field_comapny_name }}

{{ content.field_description }}

Learn More

Am I doing something wrong in the if/else statement, do I need to create different views, or is there something in the theme that I need to include?

If not rendered at all, for sure, Twig not found your template file.

There is a var that store the base dir of your theme, just use it to define where is your template file.

Twig file:

{% include "#{directory}/templates/node/node--customer--featured-full.hmtl.twig" %}


How to print image url in foreach I successfully print the image url for a individual images by the following:

$file = file_load($node->field_hp_slideshow_image['und'][0]['fid']);
                print file_create_url($file->uri);

How can I do something similar but display the url of multiple images in a for or for each loop? Below I have this but it doesn't work:

<?php $slide_image = $node->field_hp_slideshow_image['und'];
    $slide_url = $node->field_hp_slideshow_link['und'];
    $file = file_load($node->field_hp_slideshow_image['und'][0]['fid']);
    print $field_hp_slideshow_image['und'][0]['filename'];
    print file_create_url($file->uri);
?>
<?php for ($i = 0; $i < count($slide_image); ++$i): ?>

        <a href="<?php print $slide_url[$i]['url']; ?>">
        <img src="<?php print $base_url . "/" . $path . "/" . $slide_image['filename']; ?>" alt="" />

<?php endfor; ?>

Install Image URL Formatter and change the format to its url. To do so create a view of set of nodes, select the image as the field and change its format to URL. You can also change the format to URL in the manage display of the content type.


Newbie: Using css to style fields in a content type I created a content type using html elements as fields and groups. The content type configuration page allows me to add classes (and id attributes) to the elements; however, they don't show up in the generated html when I view page source in a browser.

I gather from Add a CSS class to field in content type that I must modify php functions to actually include the classes in the output css; however, I'm a newbie and don't really understand the post.  It refers to a blog post which is no longer available.

I can't find the function ( theme_field ) in any of my template.php files.  Can someone help clarify this for me.  How can I get my own classes into drupal output.

Thanks.

There is a much easier way, but is still complicated if you're a newbie. Install the Display Suite module and enable Display Suite & Display Suite UI

Go to Structure -> Display Suite -> CSS classes. Add as many CSS classes for fields as necessary. Go to Structure -> Content types -> [xxx] -> Manage Display and you should be able to put the classes you have defined against each of the fields.


How do I schedule a reminder email with Rules to users that have flagged an event? I have a content type: event
It has a single date field: date
It has a flag on it: reminder

When the user flags the node, I want to schedule a rule to send them an email the day of the event.

Can someone walk me through the steps on how to do this?

Edit: I have now gotten as far as being able to schedule the email

This is what I have so far.

Add new component
 - Type: Action set
 - Name: Send reminder email
 - Data Type: User
 - Data Type: Node

Add action
 - Send reminder mail
 - To: 'user:mail'
 - Subject: Don't forget about [node:title]
 - Body:
 - Don't forget about [node:title] tomorrow!

Create new Rule
 - Name: Schedule reminder email
 - React on Event: A node has been flagged, under "Remind"

Condition: Entity has field Data Selector flagged-node  Field: Date

Action: Schedule component evaluation Action set: Send reminder email

Sounds like you know how to set up the Flag. Triggering a Rule with Flag is piece of cake and NodeOne has an create 15min tutorial covering all the details. They also have all the needed training on Rules if your fuzzy about Rules in general. Once your ready to set up your rule and you have the event to trigger it, you can set up the email action following a recipe similar to this other answer. In your case you have the future event. Lullabot has a tutorial specifically on the Rules Scheduler.


Boost not caching anything. is_cacheable always set to false I have the problem that my installed and correctly (I hope so) set up boost module isn't caching anything.
Turning on the debug mode, it always says is_cacheable = FALSE for every page - which would explain the behaviour.

There is no "is_cacheable_reason" flag set, but I found the part of the boost.module file where is_cacheable is set to false for me:

...
elseif (!drupal_page_is_cacheable()) {
$_boost['is_cacheable'] = FALSE;
return;

}

Its line 276 from the boost.module file - right in the function boost_exit().
drupal_page_is_cacheable() seems to be a native drupal function, but I don't know where drupal decides that no page should be cached.

Looking at drupal_page_is_cacheable, it appears that there are 4 functions that use the cacheable flag.  drupal_page_get_cache and drupal_page_set_cache are to be expected, and use it simply as a flag.  Unfortunatley, drupal_session_initialze and drupal_set_message set cacheable to false.

In session initialize, if a user has visited your site at all and has a session cookie and any session variables are set then the page will not be cached.  Similarly, if you set any messages during the page generation, it will also not be cached.  While the former may have benefit, the later (IMO) is completely ridiculous.

Also, this issue on Drupal.org, but that really only addresses the first issue of session variables and cookies.

... commenting out the 'return' fixed the issue for me.  404 and 403 still not cached and you can specify other pages to be excluded in the boost settings page.


How can I extend Commerce Discount to apply discount on custom price field? I have products with 2 prices, the Commerce default one commerce_price, and a custom field field_price_with_flight. In some cases, depending on the node display term value of a taxonomy,  I need to calculate and display the discount prices onto the custom price instead of default Commerce price.

If it can be achieved with rules, I'd appreciate a detailed answer because I'm not very comfortable with the use of rules, especially commerce ones.

How could I achieve that ?

EDIT :

I need to make it possible through discount module UI. I'll try to expose why with the business model below.

The site sells travels. Anytime, depending on sales, the owner decides to create new discounts, with parameters such as:

Limited time
A different discount value usually fixed amount but could be % sometimes
Applied on a selection of travels, choosed across discount UI whether per product or per category, with the help of Commerce Discount Product Category

The flexibility of Commerce Discount  does the job most of the time.
I could setup rules for one case, but this is just impossible to teach the site owner and sellers how to setup discount rules for each new one.

Now whenever you create a discount like that, The module creates a dedicated rule. Basic one exported below.

The challenge is that by default it will apply on commerce_price. I need to extend Discount module so that :

Or it detects the travel type has a field_price_with_flight value
Or we tell the module it is that case with a checkbox in the discount form for instance

and applies then the discount to field_price_with_flight.

Or, last, if possible, create a global rule that will overwrite each discount rule whenever necessary?

Basic rule created by discount

{ "commerce_discount_rule_discount_discount_example" : {
    "LABEL" : "Discount example",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "-1",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Discount", "R\u00e9duction par produit" ],
    "REQUIRES" : [
      "commerce_discount",
      "commerce_discount_date",
      "commerce_product_reference"
    ],
    "ON" : { "commerce_product_calculate_sell_price" : [] },
    "IF" : [
      { "commerce_discount_compatibility_check" : {
          "commerce_order" : [ "commerce-line-item:order" ],
          "commerce_discount" : "discount_discount_example"
        }
      },
      { "commerce_discount_date_condition" : { "commerce_discount" : "discount_discount_example" } },
      { "commerce_product_contains_products" : { "sku" : "VE1201#2556#09-05-2016" } }
    ],
    "DO" : [
      { "commerce_discount_fixed_amount" : {
          "entity" : [ "commerce_line_item" ],
          "commerce_discount" : "discount_discount_example"
        }
      }
    ]
  }
}

All you need is Rules :)

You can start with next steps:

Visit Product pricing rules page: /admin/commerce/config/product-pricing
Click + Add a pricing rule
Enter Name. E.g. "Custom discount calculation"
Click "Save"

After that you can program logic of "some cases, depending on the node display term value of a taxonomy" via rules. If you provide more details I can explain steps more precise.

From this point you should only add conditions and actions. There is a good module rules_conditional which allows you to add conditions in any place of your rule.

Some hints on Rules:

When you want to do some actions and check with field values, you have to check if the field exists first (that's a tricky part of rules).

E.g. if you want to check the value of the field_price_with_flight, you have to add 2 conditions before:

Entity has field: Entity commerce-line-item, Field: commerce_product
Entity has field: Entity commerce-line-item:commerce-product, Field: field_price_with_flight.

After these 2 actions you can do things with the field.

P.S. An alternative way for checking fields is to check the bundle of the entity.

If you need to do some price calculations you can use actions:

Data > Add variavle
Data > Calculate a value

Once you have finished your calculations, you can apply your price. Check the `Commerce line item' actions for unit price. You can multiply, divide, set unit price.

That is basically it. In this case you do not need the discount module.

Advanced

If you need some very custom calculations you can code a custom action for price calculation. There is a lot of examples if you try to search it. E.g. How To Create A Custom Rules Action

Useful links, videos:

Product Pricing Rules (with screencasts) - a very detailed explanation of using pricing rules with steps, videos, examples.
Drupal Commerce Basic Discount on Vimeo
Drupal Commerce Complex Pricing Rules


Adding help text to drupal comment form using Drupal 7, I'd like to add some help text underneath each field for the user who is filling out the comment for a node.

For example, under 'your name' I'd like it to say, possibly in smaller font, "only give your name if you want it published with your comment".

Anyone know how to do this (maybe with hook_form_alter)?

Or just edit comment.tpl.php in your template files. Copy comment.tpl.php to your template folder and if not present in the code, add $author name and desired text.


Can Rules create a node reference that is empty except for a title? Is it possible to automatically create a reference node or entity with Rules? The idea is to have a node with information and an image Gallery reference. If the image gallery is clicked on the node view then it just shows the images with a link back to the original node. This way the original node can have one author while several different users can add photos. There isn't a need to populate the gallery on the original node creation since it will be an obvious second step view the node to add images or wait till later. I just think that it would make sense to have it available from the beginning even when empty.

The solution is to use the URL Node Reference widget.


Infinite Scroll - Issue with first load I created a view that displays all the products of my website's database.

First of all, my view looks like this. As you can see I am using Responsive Grid as my layout format.

Because of the fact that I chose to work with Responsive Grid, I implemented some code to identify the content selectors to Infinite Scroll.

  case 'responsive_grid':
    $content_selector = '.view-content > div';
    $items_selector = '.views-row';
    break;

I am overriding the output of this view using a template file. The reason is that for every 12 blocks of content I have to display a banner for a product category. You can see the snippet bellow.

<?php if (!empty($title)) : ?>

<?php print $title; ?>

<?php endif; ?>
  <div class="<?php print $classes; ?>">
<?php if ($options['alignment'] == 'vertical') : ?>
<?php foreach ($columns as $column_id => $column) : ?>
  <div class="<?php print trim($column_classes[$column_id]); ?>">
  <?php foreach ($column as $item_id => $item) : ?>
    <div class="<?php print trim($item['classes']); ?>">
      <?php print $item['content']; ?>

  <?php endforeach; ?>

<?php endforeach; ?>
<?php else : ?>
  <?php foreach ($rows as $row_id => $row) : ?>
    <div class="<?php print trim($row_classes[$row_id]); ?>">
  <?php foreach ($row as $item_id => $item) : ?>
    <div class="<?php print trim($item['classes']); ?>">
      <?php print $item['content']; ?>

  <?php endforeach; ?>

  <?php endforeach; ?>
<?php endif; ?>

<?php if ($row_id % 1 == 0 && $row_id !=0): ?>

        <?php print views_embed_view('display_random_snippet_home_1', 'block'); ?>

<?php endif; ?>

Although everything appears to be working as designed I have an issue when the Infinite Scroll module loads the first page (always counting from 0.) As you are able to see bellow, when the pager is initiated it loads 12 products pushing down the category block and creating a mess. Also, you can notice that after the first initiation everything works as planned.

You can see the issue reproduced here: http://giphy.com/gifs/l0Ex99XrcsBjynBcY

Or you can reproduce it yourself: mygadgeto.com/infinite

Hope we find a way out of this.

It seems like it is a pure markup error. I should have the statement placed in my main markup. Updated template looks like the snippet bellow.

<?php if (!empty($title)) : ?>

<?php print $title; ?>

<?php endif; ?>
  <div class="<?php print $classes; ?>">
<?php if ($options['alignment'] == 'vertical') : ?>
<?php foreach ($columns as $column_id => $column) : ?>
  <div class="<?php print trim($column_classes[$column_id]); ?>">
  <?php foreach ($column as $item_id => $item) : ?>
    <div class="<?php print trim($item['classes']); ?>">
      <?php print $item['content']; ?>

  <?php endforeach; ?>

<?php endforeach; ?>
<?php else : ?>
  <?php foreach ($rows as $row_id => $row) : ?>
    <div class="<?php print trim($row_classes[$row_id]); ?>">
  <?php foreach ($row as $item_id => $item) : ?>
    <div class="<?php print trim($item['classes']); ?>">
      <?php print $item['content']; ?>

  <?php endforeach; ?>

  <?php endforeach; ?>
<?php endif; ?>
<?php if ($row_id % 2 == 0 && $row_id !=0): ?>

        <?php print views_embed_view('display_random_snippet_home_1', 'block'); ?>

<?php endif; ?>


Customizing Drupal 6 MP3 Player I'm going to use MP3 Player module to play some audio files on drupal 6. as you know it uses Wordpress MP3 Player as standalone player and it only has one skin, so how can I obtain more skins or maybe a flash API explaining how to build one?

I have never used that particular module, but I used to use the standalone version of the WordPress Audio Player a lot.  The player isn't really skinnable in the same way you can skin other Flash components.  There are some JS properties that you can set to change colors and dimenstions.

The documentation for the module claims

  Player can be styled and changed through Drupal admin interface.

so you should visit the settings page to see what you can do.

That said, there are other options you can explore

jPlayer
Flowplayer
MediaElement (Drupal 7 only, though)


Add an anchor to the redirect URL I have a website with some news. I create a view that shows them and filter  by category. When I use the filter, it reloads the page and goes at the top of the page. I want it doesn't move on the top of the page.

I added an anchor to the page, but I can't add it to the view redirect link. I tried implementing hook_view_form_alter() to add a custom submission handler, but it breaks the entire form and the news are not filtered.

I also looked at hook_views_query_alter(), but it doesn't seem it allow to do what I am trying to achieve.

Is there any way to do this?

Here is a simple solution to scroll to top of the views results using jquery scrollTop

THEMENAME/js/views-scroll-top.js

(function ($, Drupal) {
  Drupal.behaviors.viewsScrollTop = {
    attach: function (context, settings) {
      //var scrollto = ".view-content"; // top of results
      var scrollto = ".view-filters"; // top of filters
      var url = window.location.href.split('?');
      if (url.length > 1 && $(scrollto).length) {
        $("html, body").animate({ scrollTop: $(scrollto).offset().top }, "slow");
      }
    }
  };
})(jQuery, Drupal);

THEMENAME/THEMENAME.libraries.yml

views-scroll-top:
  js:
    js/views-scroll-top.js: {}

THEMENAME/THEMENAME.theme

function THEMENAME_preprocess_page(&$variables) {
  // attach library only on specific view
  $route_name = \Drupal::routeMatch()->getRouteName();
  if ($route_name === "view.article.page_1") {
    $variables['#attached']['library'][] = 'THEMENAME/views-scroll-top';
  }
}

Change THEMENAME to your theme's name


SimplePie library is required for Feeds SimplePie Parser The Feeds module is reporting a warning about needing a SimplePie parser and prompts the user download a compiled version of it, but it isn't clear how/where to do this.

Where can I find the compiled version of the required library?

You can pull a compiled version of the parse from http://simplepie.org/downloads/simplepie_1.3.1.compiled.php. Rename this file simplepie.compiled.php and copy it in the  directory sites/all/libraries/simplepie/; the module should stop reporting the error.


How to enable boolean fields? I installed the minimal setup when installing Drupal, and I want a boolean field in one of my Content Types. But this is not enabled. I found this Boolean module, but it only has 859 installs (as of 6th Jan, 2014), so I doubt I need to install that. So how can I enable 'Boolean' as one of the field types?

You need to enable the List module, which also gives you the List, List (numeric) and List (text) field types.


Fields on images, displayed on edit page I'm trying to implement a way for users to add a "caption" and "credit" (name of the photographer) to photos which are attached to an article. The user should be able to upload an image and assign a caption and credit, preferably from the edit page for the article.

I've installed the media module and added "caption" and "credit" fields to the image file type, but I can't figure out where the user can edit those fields. Is there any way to show those fields somewhere on the edit page?

I did similar with creating photo albums connected to a content type using the field_collection module. This way you can easily customise whats added very quickly as you are essentially creating a new type of entity (think of it as having an article entity and attaching a new photograph entity which has its own image, caption and credit fields).


"Time ago" from "date end" in views How to print Date Field in Views in format "time ago" for "end dates"?
If I config field in views like:
Display: End date only,
Formatter: Time ago.
I get duration form Start date :(

Example for today (7 jun 2014).
date field values: start 1 jan 2013, end 1 jan 2014.
I wanna get: Expired - 5 mounths and 7 days.
But views printing: Expired - 1 year, 5 mounths and 7 days.

You can write this in javascript to avoid caching issues and use the users machine time.

https://drupal.org/project/timeago

http://momentjs.com/

http://timeago.yarp.com/

otherwise there is a patch here: https://drupal.org/node/2026545


Grouping fields into Drupal block to appear in its node I have a content type with several fields. I need to group some fields of each node into a block. The block will contain the fields values of that particular node only.

In this layout, AAA is a photo slider displaying some photos of that node. On the right, BBB is a block containing some fields. I am trying to create this BBB as a block.

Initially I thought this could be done with the fieldgroup module, just only a matter of configuring the fieldgroup setting for < div >? And in that form, this question is similar to earlier ones, and has also been well answered.

But on further research, this doesn't work. In the diagram, AAA and BBB are siblings. If the fields in BBB have a < div > but still under the larger container and not in their own block, then it can't float with the other AAA block since they are not siblings.

Therefore, I need not only to group with < div > for the fields but indeed must wrap these fields into a Drupal block. How to do that? Thanks.

Go to display settings for your content type and select div under format and save it. The contents are then wrapped in a div.

see here in firebug

Note: You can also use a template (.tpl) file for your content type and there you can wrap your desired contents inside a div.


Drupal site not loading any CSS/JS/Images I've been trying to migrate my site from my local to GoDaddy server. I've done it so many times before and it's worked fine but this time I can't quite figure out what's wrong.

My steps on migrating the site:

Clear cache
Export DB
Create DB on server and import local DB
Upload Files (tar zip)
Change settings file

As I say, that's worked for me this whole time but now the site and content loads up fine but no styles, no images, no js. If I inspect the page it seems all of those files have a 403 forbidden error.

I noticed that even the Drupal menu and other Drupal CMS styles aren't loading up either so maybe that could be important in finding a solution?

Ok found the problem, it was all to do with file/folder permissions. So I did some reading and I learnt that it's recommended that folders are 755 and files are 644 (with the exception of htacces)

So I went and made those changes to files/folders and it all seems to work fine.


Submit handler is not getting called inside theme function I have created a draggable table and add a submit button below it. I am able to view the submit button but submit handler is not working. Below is the code.

function form_content_reorder($form, &$form_state)
{
$form = array();
$form['items'] = array();
$form['items']['#tree'] = TRUE;
$form['#theme'] = 'usercontentranking_reorder_form';
$form['name'] = array(
 '#type' => 'item',
 '#markup' => 'Hello  '.get_genderval($user_data['gender']).$user_data['user_name'],);
$form['submit'] = array(
 '#type' => 'submit',
 '#value' => t('Save Preferences'),
 '#submit' => array('user_content_ranking_save'),);
 return $form;
 }

function usercontentranking_theme($existing, $type, $theme, $path) {
$themes = array(
'usercontentranking_reorder_form' => array(
  'render element' => 'element'
),
);
return $themes;
}

function theme_usercontentranking_reorder_form($vars) {
$element = $vars['element'];
drupal_add_tabledrag('draggable_table', 'order', 'sibling', 'weight-group');
$header = array(
 'label' => t(''),
 'label2' => t(''),
 'weight' => t('Weight'),
 'operations' => t('Operations'),
);
$rows = array();

foreach (element_children($element['items']) as $key) {
$row = array();
$row['data'] = array();
$row['data'][] = drupal_render($element['items'][$key]['title']);
$row['data'][] = drupal_render($element['items'][$key]['user_fields']);
$row['data'][] = drupal_render($element['items'][$key]['weight']);
$row['data'][] = drupal_render($element['items'][$key]['operation']);
$row['class'] = array('draggable');
$rows[] = $row;

$themes = drupal_render($element['name']);

$themes .=theme('table', array(
  'header' => $header,
  'rows' => $rows,
  'attributes' => array('id' => 'draggable_table'),
));

$themes .= drupal_render($element['submit']);

return $themes;
}

function user_content_ranking_save($form, &$form_state)
{
  print "text";
}

The line
 $themes .= drupal_render($element['submit']);
able to show up the button but the function user_content_ranking_save is not getting called.
Please help me in this.

It looks like you are declaring your submit button's submit handler correctly. Rather than debugging with print(), try using drupal_set_message() or the Devel module's dpm().

Example with drupal_set_message():

function user_content_ranking_save($form, &$form_state) {
  drupal_set_message('Submit handler was called.');
}

Edit:

Also, if you are constantly refreshing the same form, Drupal may have cached it. Try clearing your cache and see if your submit handler is now being called.

Answer:

Are you sure the whole form is being rendered when using your theme function? It may be that the form is not being validated because the rendered output of the form does not contain the form_id, form_build_id, and/or form_token.


What are the potential security issues when importing an entity type? I'm working on a module.

If the module is enabled, there would be an overview page showing the field structure of different content types. The visitor could then click a button to get a copy of the bundle's field structure (JSON encoded) and then use the code to create that content type on their site. Basically, like a feature except copy and paste rather than download.

What would potential security issues be? Is there any way to ensure that the hosting site (the site the content type is copied from) won't be able to do anything malicious?

Who would you expose this feature to?

If it's users with one of the permissions listed on http://drupal.org/security-advisory-policy then you shouldn't really worry about the security implications because those users can already do a lot of malicious things to the site.

I believe that all field names and field values should be filtered appropriately already and Drupal handles filtering on output, so I don't see a need for something like xss filter during import.

The fact that you want to use JSON instead of a PHP array as the method to represent the code seems great: copy/pasting PHP arrays around is an easy way to create an arbitrary code execution problem.

There is more discussion about safe ways to offer this feature in an issue in the Views queue.

If this doesn't answer your question please leave a comment and I'll do my best to expand.


Drupal 7 Ckeditor cannot edit profiles (picture added) Recently I must have done something that changed something with my ckeditor.
I can no longer edit my profiles.
The strange thing is that I have multisite setup and only 3 sites are affected.
The 3 sites have a different theme, looked everywhere there but I cannot seem to find it.
Normally you see drop-down (clickable) buttons and then you can edit the options.
This is what I have now:

Anyone have an idea of what I might have done wrong?
The picture shows just plan text instead of buttons... I'm useing Omega 3.

Broken unclickable fieldsets are almost always a symptom of JS not being run to build the links & click events to trigger expansion.

If the JS console is reporting errors, try to disable JS caching/aggregation, if possible, and look for offending JS errors that would stop execution. That should give you a good idea where it's coming from.

Most likely, the 3 affected sites have a similar configuration that is injecting JS which breaks further JS execution. Look for similar modules across the 3 sites. Good places to look are any custom modules, JQuery update (is it overriding the default jQuery from Drupal core?), custom blocks with JS, or any modules designed to inject ad-hoc JS snippets (I've come across sites using JS snippets despite its alpha status).


How to render a view as a entity field on form edit? I'm looking for a module (or alternative solution) to render view in the field.

Similar to Viewfield, but it should be rendered when filling the form (Entityform or node edit).

The purpose for that is to include Commerce views in the entity form (such as commerce_cart_form, commerce_cart_summary, commerce_payment_order) which are actually views.

Use EVA  module. It will provide the view as field. So in display settings you can assign views the region you would like. Quite simple and useful module


Referencing CSS file from theme library inside Embedded Widget Paragraph type I have an article page in Drupal 8 that contains a chart (inserted into the page using Text paragraph). The chart uses CSS classes that I have created inside the global stylesheet. It works, but I don't want these CSS classes to be loaded on every single page on my website.
I'm thinking that I would move the CSS classes into a separate file. Then I would move the HTML code for the chart into an Embedded paragraph and reference the theme library.
I'm new to Drupal 8 theming so I'm not sure how I would go about doing that. Can someone give me the general steps?
I think need to do the following.

Move CSS classes to a new file
create a library refencing the new CSS file that is not loaded by default
Add the CSS file URL to the embedded widget "Javascript Source" field

I'm not sure how to add the library refence to my theme or to make it not load by default.

Your thought process is correct. To implement below script tag is to be referenced inside the embedded widget
Like: Js
<script type="text/javascript" src="/custom.js"></script>

Like : Css
<link href="/custom.css" rel="stylesheet" />

Thanks


Clone nodes and change fields with Rules and VBO I' trying to create a rule component that clones selected nodes and then changes some fields, using Rules, VBO and Node Clone.

VBO and Node clone work fine, but I can't change values of every field in the clones afterwards.
After the action "Clone node", I can add a "set data to value" action to change just core node fields (like status, sticky...), but the selector doesn't show me my other fields defined in the content type (like cloned-node:field_xyz).

I also tried to use Rules Bonus Pack  instead of Node clone to duplicate nodes, but with no luck: same issue.

After some researches, I tried to force a save entity action on the cloned node and then tried to load entity from cloned-nid, but I cannot choose my content type's fields to change them.

I also added a condition on top like "Content is type | entity has a field | entity is bundle", but nothing happens.

Probably I miss something.
Any idea?

Thanx in advance

I solved using custom PHP code in my component instead of the node clone action, so I'd like to share this with you:

// load the original node
$node = node_load($node_parameter->nid);
$node->nid = null;
$node->vid = null;
// park the new node
node_object_prepare($node);
// reset fields
$node->uid = 1;
$node->status = 1;
$node->path = null;
$node->created = 1432072800;
$node->title = $site->current_date;
$node->field_one['und'][0]['target_id']= 11530;
$node->field_two['und'][0]['value']= 'my text';
unset($node->field_three);
// save the new node
node_save($node);
// flush
unset($node);

Probably the key is that when you use the action "node clone", Rules alone can't determine the cloned node type and access to its fields directly, even if you are cloning a node already verified by the condition at the beginning of the component. Probably it could if putting another condition after the clone action, but I don't know how to.

So another solution I tried is to create a component that just clones the VBO passed node. And then create a separated rule that reacts on event "after cloning a node" and put in there the condition "content is type of" and all the "set data value" actions I needed.

And it works.

Anyway I prefer the first solution, so I can keep all I need in just one place and avoid using Node Clone module. I was worried about performance executing PHP and node_load() in Rules, but in just few minutes I successfully cloned and updated 2260 nodes.

Thanx all


Is it possible to create a hierarchical exposed filter in views using the Data module? I'm using Data module to adopt tables from the same DB as 'native' Drupal tables and Views module to present the data.

I added two dropdown exposed filters with Selective filter module. It takes all values from fields and puts them to the selective list. It works fine.

However I would like to configure my exposed filters the way that the second filter will show values according to the chosen value in the first one. E.g. if you choose a specific academic department in the first filter, the second one will offer you the list of this department's staff members.

Is it possible to achieve such a behavior? If so, do I need any extra modules (taxonomy?) or should I create a module myself?

First Install Hierarchical Select Module for display taxonomy of parent/child relations then add that taxonomy as a field to your content type then add this field to your exposed filter. it's working..


How can I get a list of content types? Is there any way to get a list of some of many content types?

I am not asking to list nodes of content type(s).

List of content types

In code you can have the list of all node content types, using the node_type_get_names() method :

foreach (node_type_get_names() as $name => $type) {
     // Do something
}

After, you'll have to sort them if you do not want to use them all.

Template override

It is not a good practice to hack any files of the Drupal installation.

But you can easily override any template files provided by the core or a module, directly in your theme folder.

Have a look at this subject : Drupal 7 Template (Theme Hook) Suggestions.

To have a custom content type template, just take the default "node.tpl.php" file, and copy it in your template theme folder, with a name like "node--[type-machine-name].tpl.php" (you'll have to replace the "_" in the type_name by "-").

Custom node add form

And finally I already saw some website using a override node form page using page manager module. But I cannot say how they've done it.


Execute jQuery after form submit I have a non-ajax form for which I'm trying to execute a jQuery function after the form has been submitted and processed.

I don't need ajax for the form, but I do need to wait until 600 odd form fields have been processed before executing my jQuery function.

There are a lot of answers out there, but I can't quite figure them out.

Should I do this via ajax (even though not required for the form) or is there a better way to do it?

Given the form takes a good few seconds (10 or so) to process (more on mobile, etc.) how should I go about it?

EDIT:

Another go at explaining exactly what I'm trying to do.

I have a form that collects 600+ pieces of data
After the form has been submitted and processed, I need to open a new window that processes the data, displaying it graphically (via canvas) and then saves that canvas as an image to the user profile.

Because there is so much data that needs to be processed, I've elected to run everything in a new window, so if the user navigates away from the main window, their canvas is drawn and saved, etc. in the background.

It appears that jQuery is the only way to open this new window, and I have to execute this after the form submission (otherwise the canvas is drawn with pre-submitted data)

Of course, there could be a better end to end way to do it, but jQuery post form submit seems to be it.

You can use Drupal.behaviors, which is fired upon page load.

function doSomething()
{
  // Do something
}

Drupal.behaviors.myModule = {
  attach:function() {
    doSomething();
  }
};


Is there any built in function to render image file extension like jpg, png etc? Is there any built in function in Drupal 7 to render image file extension like jpg, png etc on node load.

I have tried image_get_info etc.

image_get_info() should do the trick.

//if you want to get the extension of image1.jpg
$filepath = "sites/default/files/images/image1.jpg";
$info_var = image_get_info($filepath, FALSE);
echo "the image extension is ".$info_var['extension'];


Which are the most effective methods of optimizing a drupal 7 site? Is there any module which would help in optimizing drupal 7 site ?
The drupal site (used for bank both for transactions as well and for non transactions as well without using drupal commerce) becomes very slow in terms of loading pages or any nodes..
So which are different ways in which we can optimize the Drupal 7 site to work smoothly and efficiently?

Boost module is the best option for performance issues, even it will works great in shared hosting. It will not hit the server for every request, instead it cache the pages and deliver them and Boost will cache & gzip compress html, xml, ajax, css, & javascript. Boosts cache expiration logic is very advanced; it's fairly simple to have different cache lifetimes for different parts of your site.

  Boost provides static page caching for Drupal enabling a very
  significant performance and scalability boost for sites that receive
  mostly anonymous traffic. For shared hosting this is your best option
  in terms of improving performance.


Dynamic form fields using #states array on empty select field Trying to make the second field only visible when there is a value in the first controller field. If nothing is selected in the initial load of the screen, the second field should be hidden.

Because the controller api_title is a sub array I'm not sure how to set the comparison value in condition name='api_title'

$form['api_title_filter_widget'] = array('#tree' => true, '#weight' => '10');
$form['api_title_filter_widget']['api_title'] = array(
        '#type' => 'select',
        '#title' => 'API Title',
        '#default_value' => $api,
        '#options' => ["" => "- Select -"] + $published_api_proxies,
        '#ajax' => array(
            'event' => 'change',
            'callback' => 'callback_api_product_filter',
            'method' => 'replace',
            'wrapper' => 'api_products_controlled_by_filter',
        ),
    );

$form['api_product']['#states'] = array(
                                   'visible' => array(
                                        '**select[name="api_title"]' =>**
                                          array('!value' => ''),
                                            ),
                                         );

Maybe you can try to add an id to your select field

$form['api_title_filter_widget']['api_title'] = [
  '#type' => 'select',
  '#title' => 'API Title',
  '#default_value' => $api,
  '#options' => ["" => "- Select -"] + $published_api_proxies,
  '#ajax' => [
    'event' => 'change',
    'callback' => 'callback_api_product_filter',
    'method' => 'replace',
    'wrapper' => 'api_products_controlled_by_filter',
  ],
  '#attributes' => [
    'id' => 'my_api_title'
  ],
];

Then you should be able to target it through its id :

$form['api_product']['#states'] = [
  'visible' => [
    ':select[id="my_api_title"]' => ['filled' => TRUE],
  ],
];


Programmatically change webform confirmation page I've looked at the other similar questions but they don't answer this precise issue.

In my use case, a webform is displayed on an arbitrary entity page (such as "activity/xx"). (This is not a 'node' entity type.)

When completed I want the user to be returned to this page with no message, but we don't know what the value of "xx" is going to be when the webform is created, and the work is going to be done by non-technical staff.

It's possible to:

Create the webform;
Build the entity and select the webform;
Note the entity ID created;
Go back and modify the webform confirmation page;

But this is not good for non-techies. It's easier if they're told to go to the settings page and add a handler.

I just need to force the confirmation redirect to reload the current page.

I could probably manage if I could use tokens in the confirmation page URL, or in the settings handler but I see nothing that says I can and my testing hasn't worked.

I know I can get the source entity in a handler in the back end, so I ought to be able to jump there. I just don't want to break anything...

When completed I want the user to be returned to this page with no message

  I just need to force the confirmation redirect to reload the current
  page.

The following should do the trick:

Better yet:


CSS Class of a multi-lingual front-page In Drupal 7, in the body tag of my English home page, I see the following CSS classes (among others): html, front.

I added a French translation for this home page by clicking on the "translate" link. The body tag of my French home page has the following CSS classes (among others): html, not-front.

For the French version, how do I substitute the CSS class "not-front" with "front"?

You could do this in the preprocess_html function.

You should take a look at the i18n module, which allows you to have different frontages for each language, which could be an alternative (and better) way of solving the problem.


How to display custom fields of taxonomy in field twig In my content type for Event, I have an entity reference called Speakers which refers to a taxonomy called Team Members.   It's set to multiple so I can say which speakers belong to my event.    On the event detail page, I want to list the speakers out with all of their fields.

I have a field hook called field-field-speakers.html which lists all of the speakers.   I can't seem to get any of the fields within the taxonomy.  (ex: item.content.field_job_title ).   It doesn't display any content.

  {% for item in items %}

                 {{ item.content }}

{{ item.content.field_job_title }}

  {% endfor %}

How do I do this?   I think the answer might be in a View but not sure how to map it dynamically based on which event I am in.

You can use item.content['#options'].entity.field_job_title.value to get the value of the job_titlefield value, I don't know if this is the best way to do it.
So your code will be something like:

{% for item in items %}

        {{ item.content }}

{{ item.content['#options'].entity.field_job_title.value }}

{% endfor %}


Hide a CCK fieldgroup using #states in hook_form_alter()? I have a custom module, and I am trying to hide a CCK fieldgroup using "#states" when a certain item is selected in a drop-down select list.

I have tried using states from within hook_form_alter(), like so:

$form['group_mygroup']['#states']['invisible'] = array(
  ':input[name="field_trigger[' . LANGUAGE_NONE. ']"]' => array( 'value' => 'hide' ),
);

This doesn't seem to do anything.

I have looked at changing the weight of my module as per various sites like http://proofgroup.com/blog/2008/dec/modifying_cck_fieldgroups_hook_form_alter.

but still to no avail. I can hide all the form elements within the fieldgroup using states but not the field group itself. Does anyone have any idea?

/**
 * Implements hook_field_group_build_pre_render_alter.
 */
function mymodule_field_group_build_pre_render_alter(&$element) {
  if (isset($element['#form_id'])) {
    if ($element['#form_id'] == 'mynodetype_node_form') {
      $element['group_myfieldgroup']['#states'] = array(
        'visible' => array(
          ':input[name="field_myfield[und]"]' => array('checked' => TRUE),
        )
      );
      $element['group_myfieldgroup']['#id'] = 'group_myfieldgroup';
    }
  }
}

I use this hook to hide my field group. It's visible only if the checkbox field_myfield is checked.

To explore $element variable in this hook I used

die('<pre>'.print_r($element, 1).'</pre>');

instead of dpm().

Hope it helped :)