How to force users to re-authenticate on specific pages? Is there any possibility to Re-Authenticate user especially on specific pages like we see in some websites?

Background: for some of the websites like banking sites, when you are initiated fund transfer it will ask you to re-authenticate your account. Main moto is here, user will be logged in a long back ago using "Remember me", so for visiting few pages I want to re-authenticate user.

I think this module suits to my requirement: Protected Pages. Some details about it (from its project page):

  ... allows the administrator to secure any page in your website by password. You just need to go to configuration page of this module and add path, password. After that the added path will be password protected. This module also allows you to send the details of this protected page to multiple users by email.


How to run entityfieldquery on all fields in node that reference users Is there a way to run EntityFieldQuery on all fields of a node that reference a user?

Thanks!

Can you try rephrasing your question? It is not clear what you are trying to accomplish. Do you want to load all nodes that use the same field to reference a user?

If so, you would use the fieldCondition() method. Something like

->fieldCondition('field_name', 'target_id', $uid)

See https://api.drupal.org/api/drupal/includes!entity.inc/function/EntityFieldQuery%3A%3AfieldCondition/7 for more information.


Filter nodes by paragraph user reference Say you have a content type Exercise which has a Related Users paragraph field. In turn, Related Users has a user reference field:

(content type) exercise --> (paragraph) related_users --> (user) user

I want to filter all Exercises with a certain related user:

/api/node/exercise?filter[field_related_users.field_user.name]=some_user

But it returns empty data: "data": [],. Same if tried with user id.

I'm sending a request with admin user, so there are no permission issues. Also, I did a similar filtering on a referenced content type (with a user reference) and it does return data.

I couldn't find anything related to this in JSON:API open issues. Does filtering by paragraph reference work differently? Or maybe there are limitations on this?

According to this issue, Unable to filter on columns of entity reference fields. It seems like you need to add .entity after the field name to the entity reference fields.

Try to use this URL instead:

/api/node/exercise?filter[field_related_users.entity.field_user.entity.name]=some_user

Or if field_related_users can contain multiple values, you might want to do like this instead:

/api/node/exercise?filter[field_related_users.0.entity.field_user.entity.name]=some_user


Add class to term-reference output I'm trying to add a simple class to a link outputted via print render($content['field_tags']). I'm using the Bootstrap theme. These are the approaches I've tried so far:

Hooking into template_preprocess_node - no luck here as the html isn't generated yet.
Hooking into template_field - this contains exactly what I expect but the links being generated don't obey the classes set here.
Hacking node.tpl.php and manually outputting the terms - this sort of works but it's not the best solution.

This is the output as it is at the moment:

drupal

I don't want to add any more modules as there has to be a code solution to this, I'm not sure what I'm missing here. How do I add a class to link outputted in field_tags?

One option would be to preprocess the field:

function MYTHEME_preprocess_field(&$vars) {
  if ($vars['element']['#field_name'] == 'field_tags') {
    array_walk($vars['items'], function(&$el) { $el['#options']['attributes']['class'][] = 'some-class'; } );
  }
}


HTTP Basic auth on specific Drupal paths? I want to use HTTP Basic authentication on a group of paths in my Drupal site (e.g. /folder/*). The paths are all menu callbacks that don't have actual page content.

I tried to use Secure Site but I don't see a way to specify the restricted pages. It seems to just assume that /admin is the only restricted path you would want, unless you wanted to force authentication on your whole site.

How would I go about forcing HTTP Basic auth on particular paths that don't have nodes aliased to them and that aren't admin pages?

I think you are looking for Sharing authentication with HTTP-Auth which describes using the Drupal user tables to supports Apaches http auth system. You will probably have to hard-code the paths in your menu, or within your page content. Then set up Apache to use http auth on the particular directories.

EDIT:

To use this technique in the Drupal environment, you would define http auth for individual directories in the apache Auth.conf file like:

<Directory /usr/local/webroot/d7.example.com/folder>
...Auth directives ...
</Directory>

where /usr/local/webroot/d7.example.com is your drupal root. This allows you to protect individual directories, while maintaining drupal authentication for your site.


How to make a Data Selector a negative value in a rule action? I create a rule and inside it I added a action, this action involves a data selector: node:field-labpoints. I need to make this data selector a negative value.

I tried with -node:field-labpoints and -[node:field-labpoints] but it is not accepted.

look my capture:

You have two ways to do this.

Either you use PhP filter, which will add under "data selector" and "add offset" a new option, "php evaluation", which will allow you to post-treat this value. Then you'll just have to set return intval(- $value);

Or you can use whole Rules, by :

Action: Add a value, and select your [node:field-labpoints]
Action: Calculate a value, and make it negative
In your action, use this value instead of the one you selected with the selected.


How to create a module that shows some fields of profile2 type? I want to create a module that shows some fields of profile2 type, in fact I want to show some information about any user in profile page of theme.
Profile2 type is "stores", field machine name is "field_store_name" and my module name is "profile_header".
I put below code in profile_header.module

 <?php
function profile_header_block_info() {
  return array(
    'profile_header' => array(
      'info' => 'profile stores header',
      'cache' => DRUPAL_NO_CACHE
    )
  );
}

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

    global $user;
    $account = user_load($user->uid);
    $user_fields = user_load($uid);
    $profile = profile2_load_by_user($account, $stores = NULL);
    $field_store_name = field_get_items('profile2', $profile2['stores'], 'field_store_name');
    $block['subject'] = 'profile stores header ';
    $block['content'] =  theme(
          'profile_header',
          array(
            'field_store_name' => $field_store_name,
          )
        );
     return $block;
}

function profile_header_theme($existing, $type, $theme, $path) {
  return array(
    'profile_header' => array(
      'template' => 'profile_header',
      'path' => $path . '/theme',
      'variable' => array(
        'user_fields' => NULL,
      ),
    ),

  );
}

and put below code in profile_header.tpl.php, and clearly I put this file in profile_header/theme directory.

<?php
?>

            <?php print $field_store_name ; ?>

But unfortunately this module doesn't show anything.

Your hook_theme() implementation is returning an array with missing details; the key should be variables and its value array should contain keys that matches the variable names in your template.

function profile_header_theme($existing, $type, $theme, $path) {
  return array(
    'profile_header' => array(
      'template' => 'profile_header',
      'path' => $path . '/theme',
      'variables' => array(
        'field_store_name' => NULL,
      ),
    ),
  );
}


Need for Complex Sort Criteria Views I have a challenging task of making an HTML List into a View within Drupal.

The original list is alphabetical EXCEPT for the first 40 entries which are organized essentially in chronological order as well as most popular items on top.

I believe i took care of the most popular items (5 of them) buy utilizing the sticky option within Drupal.

The next 35 items... 30 of them need to be organized by the release date, in this case a "special event #" in the node title is what is used to signify its chronological order.

Example:

 Cool Party - Special Event 1
 Fun Shindig - Special Event 2
 Quiet Gathering - Special Event 3
 Funny Picnic - Special Event 4

I want to know how i can sort the list within Views to get the special event listings in order from 1-30 at the top of my list (just after the sticky top 5)

You are able to create a single block or page in views with different sort criteria using attachments in views

So create a view with some criteria and add an attachment like above and override the sort criteria as you need
Then add your attachment to your page or block as below

Here is a post which explains this in detail.


Views Arguments Title I have a view which has an argument passed to it. I provide a default argument of "User ID from URL". I then use %1's content in the Title. This returns username's content.

I have a content profile associated with a user. I want to get the field_first_name from the content profile and display it in the title. So I would get Lucy's content. How can this be achieved?

Edit your argument for configuration
Add validator options for your argument by selecting PHP Code from the select box
Add following code in it

 $usr = user_load(array(uid => (int)arg(2))) //Check the appropriate position of uid
 $view->display['page_2']->handler->handlers['argument']['date_argument']->options['title'] = $usr->field_first_name . "'s content";

Here page_2 is views identifier and date_argument is argument identifier.


D8: Best way to implement terms of use acceptance requirement AFTER log in, and gate content if they don't accept? Currently I have a Drupal 8 site utilizing saml authentication to create user accounts and log in. I've seen some modules that have required terms of use acceptance during registration, but that's a non-starter for my implementation.

I'm looking for recommendations on how to:

Present Terms of Use & Acceptance input to newly logged in users
Gate content behind this acceptance

Thank you for any recommendations.

Specifically, the issue here is that the common Terms of Use modules out there happen during registration rather than after first log in. The problem scenario can arise if you are using a SSO implementation with your Drupal install.

My solution involved creating a module that, as a kernel event, redirected users that had not accepted the terms of use to the terms of use page until they had done so. Once they accepted the terms of use, I gave them a role - "Accepted Terms" - that let me know they were free to go.


Are URLs UTF-8 encoded? I want to use special characters (like üßä) in my clean URL alias's and google says they must be UTF8 encoded.

I have no idea if this is the case by default, or how to check. Are URLs UTF-8 encoded?

Everything in Drupal is UTF-8 encoded, yes.

Be aware that various tools still don't properly support such characters in URLs and might display it encoded.


How should I use hook_field_extra_fields()? I just found out about hook_field_extra_fields(), but the documentation doesn't really tell me how to use it.

Where is the extra-fields output generated?

I tried hard to understand the Node and Poll modules, but I can't figure it out. I also tried to add a custom field formatter.

This is a simple example showing how to add an additional field to the Field UI and provides an example of one way of inserting the field onto a node.

/**
 * Implements hook_field_extra_fields().
 */
function MODULE_field_extra_fields() {
  $extra['node']['article']['display']['extended_submitted_by'] = array(
    'label' => t('Extended Submitted By'),
    'description' => t('Provides Jumper Menu for Version Selection'),
    'weight' => 0,
  );
  return $extra;
}

/**
 * Implements hook_node_view().
 */
function MODULE_node_view($node, $view_mode, $langcode) {
  // Only add if the view mode is for a full view, although we
  // could control this via the Field UI too using 'hidden'.
  if ($view_mode == 'full' && $node->type == 'article') {
    $node->content['extended_submitted_by'] = array(
      '#markup' => '
This is inserted unless hidden in the field ui.
',
    );
  }
}


Sort on Custom field in views I am using views 3 in D7 and have added custom field of percentage on students result listing. I want to sort on the percentage field, how can I add sort on custom field?

Thanks for your help.

Your custom field is added after the query is performed by views, and a the sort is done as part of the query, therefore your sort doesn't know about your custom field.

I'd probably try to store the percentage in a field on the content type and then you'll be able to sort using the normal views sort handlers.


Drupal 8 always editing a translation, never the original I have a website with 4 languages, while English is the default. Each language has its own directory (mydomain.com/contact, mydomain.com/jp/contact, etc.). I have the following languages:

English
Czech
Japanese
Russian

For the record, my language detection is configured with these priorities:

URL
Session
Selected Language
Browser

When I try to edit a translation of a content page (let's say Japanese), it works just fine, but when I try to open an edit page (mydomain.com/node/6/edit) of the orignal, english node, I'm always getting "Edit Basic Page Nobg Kontakty [Czech translation]", with the Czech content and can't access the edit page for the english original. What to do?

If you want to use English as default without URL prefix you have to disable

Session
Browser

in the language detection list, so that only URL and Selected Language (which can't be removed) is enabled.

Then configure in

Selected Language

the site's default language (English).


Webforms with subheadings that have their own fields I realise what field sets are as they can group parts of your webform together. What I am looking for though is to have subheadings within those fieldsets.

I've been trying to find tutorials about this but all I can find is tutorials on how to build a simple webform with just a title, description and then label-field pairs.

Edit: Say I want a form that calculates taxes for someone and I want to start off with a fieldset that has a couple of radiobuttons like male/female, I live rural/I live in the city and whatnot. Then I want some label/textfield pairs like name address phone, etc...
Then within the same fieldset I would have a title that says 'do you have a secondary address?' and have that be the title for a subset of fields with again address and zipcode, etc..

Basically I got away with just putting up a markup title. I thought it was really necessary to have field groups in order to make a valid web form since it was suggested to me. I guess like Andy said, nested fieldsets might have worked as well.


Is putting content in the codebase or the database better for performance? I recently created a website footer using a block template. Some of the footer's content was entered through the block's wysiwyg (stored in the database), but other code-heavy elements were placed in the block template file (stored in code). I've noticed that the footer block loads slow at times. Other times, the content inserted through the wysiwyg loads a few seconds before the content that was inserted in the the block template.

I'm curious, is storing html content in the database better for performance than storing html content in template files?

EDIT: After I posted this, I also realized that the footer is being rendered with Blocks whereas the rest of the page is being render with Panels. I'm not sure if that would have any effects of its performance.

Quick answer is that the DB should be slower. In reality the only way to know for sure is to profile the PHP code and get a cache grind of it. One being rendered by panels and the other by core blocks is the main reason most likely in this case.


How to define the site to be used in BrowserTestBase on a multisite? I am working on a multi site where there is no database defined in the default directory, so whenever I run a Functional test extending BrowserTestBase I get the following error:

copy(/var/www/drupal-int/docroot/sites/default/default.settings.php): failed to open stream: No such file or directory

I'm not really sure why the files were removed in the first place and I don't want to add them back in there in case there was a good reason for removing them. Is there a way to define the site to use for the test?

My simple test:

<?php

namespace Drupal\Tests\my_module\Functional;

use Drupal\Core\Url;
use Drupal\Tests\BrowserTestBase;

/**
 * Simple test to ensure that main page loads with module enabled.
 *
 * @group dnsw_scheduler_workbench_integration
 */
class LoadTest extends BrowserTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = ['my_module'];

  /**
   * A user with permission to administer site configuration.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $user;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->user = $this->drupalCreateUser(['administer site configuration']);
    $this->drupalLogin($this->user);
  }

  /**
   * Tests that the home page loads with a 200 response.
   */
  public function testLoad() {
    $this->drupalGet(Url::fromRoute('<front>'));
    $this->assertResponse(200);
  }

}

None of your existing sites are used during a fonctionnal test, drupal creates a fresh install defined by your static attribute $modules and the setUp() method.

So, you should get the default.settings.php file back (and create a /sites/simpletest folder)


Add html to a node's title I have a Drupal 7 site and I'd like to be able to add an HTML link to part of the title of a node. By default Drupal has this as plain text. Is there any way that I can allow HMTL?

Example:

This is a title

That happens because template_process_page() contains the following code.

if (!isset($variables['title'])) {
  $variables['title'] = drupal_get_title();
}

drupal_get_title() calls check_plain().

// During a bootstrap, menu.inc is not included and thus we cannot provide a title.
if (!isset($title) && function_exists('menu_get_active_title')) {
  $title = check_plain(menu_get_active_title());
}

The only way you have to add HTML to the title is using hook_preprocess_page() and set $variables['title'].

Keep in mind that $variables['title'] is also used as value for the <title> tag, and browsers should not expect HTML tags inside that tag.

  Titles may contain character entities (for accented characters, special characters, etc.), but may not contain other markup (including comments).

To change just the node title, you should implement hook_preprocess_node() and set $variables['title']. By default, template_preprocess_node() sets it using $variables['title'] = check_plain($node->title);.
As side note, for the node title, Drupal 8 uses $variables['label'], not $variables['title'].


Creating an API via module routing files that includes csrf verification headers I am working on migrating a custom API from D7 to D8 and am doing so by using module routing. I have a routing.yml file that looks like so:
ytp_user.api.login:
  path: "/api/v1/user/login"
  defaults:
    _title: "User API Login"
    _controller: '\Drupal\ytp_user\Controller\UserAPIController::login'
  methods: [POST]
  requirements:
    _csrf_request_header_token: "TRUE"
ytp_user.api.get_current_user:
  path: "/api/v2/user/me"
  defaults:
    _title: "User API Get Current User"
    _controller: '\Drupal\ytp_user\Controller\UserAPIController::getCurrentUser'
  methods: [GET]
  requirements:
    _custom_access: '\Drupal\ytp_user\Controller\UserAPIController::authorize'

In the first route, I am trying to validate a csrf token provided in the headers, via the requirement _csrf_request_header_token: "TRUE", however, this does absolutely nothing. It doesn't validate or even check that the header exists as the documentation suggests it should.
I've tried replacing this with _csrf_token: 'TRUE' which at least checks that the token exists in the query, but I can't get a valid token!!! If I grab a token from /session/token and then pass it along in the query as ?token=<token-from-session/token> then I just get an error saying the CSRF token is invalid.
Am I missing another step or is the documentation just straight up incorrect? I have been searching for hours and everything suggests that what I have should work, so why is the CSRF token not being validated properly?

The requirement _csrf_request_header_token: "TRUE" works only if user is connected because CsrfRequestHeaderAccessCheck use session informations.
If you look at CsrfRequestHeaderAccessCheck in the access method there is:
 if ($account
      ->isAuthenticated() && $this->sessionConfiguration
      ->hasSession($request)) {

To check if the user is connected and it there is a session identifier in the request if it's not it will go directly to:
// Let other access checkers decide if the request is legit.
    return AccessResult::allowed()->setCacheMaxAge(0);

so it will not check if X-CSRF-Token is in the headers or not even if you set the route requirement _csrf_request_header_token: "TRUE".
Code
MODULE.routing.yml
MODULE.login:
  path: "/api/v1/user/login"
  defaults:
    _title: "User API Login"
    _controller: '\Drupal\MODULE\Controller\UserAPIController::login'
  methods: 'POST'
  requirements:
    _csrf_request_header_token: 'TRUE'

UserAPIController.php
class UserAPIController extends ControllerBase {

  public function login(Request $request) {
    $response['data'] = 'Some test data to return';
    $response['method'] = 'POST';

    return new JsonResponse( $response );
  }

}

Test

With Connected user

with anonymous user


How do I override the default sorting when filtering a view by Taxonomy terms? My current settings …

In Drupal 6, I currently have a view that filters and sorts nodes by the following criteria:

The taxonomy term is very general, and nodes can either be assigned to "Referenzen" only, or any of its sub-nodes. This is done for the basic structuring of the site. Here, in this view though, I only want to "load all nodes with 'Referenzen' assigned", regardless of their sub-term.

The problem …

"Wichtig" ("important") is an integer value that defines the primary sort criteria for me. I do not care whether a reference is filed under "Media" or "Consulting", or any other sub-term.

However, the nodes are finally displayed like this:

Node 1   Important:  100   Taxonomy: Referenzen
Node 2   Important:    0   Taxonomy: Referenzen
Node 3   Important: -100   Taxonomy: Referenzen
Node 4   Important:  100   Taxonomy: Referenzen – Media
Node 5   Important:   80   Taxonomy: Referenzen – Media

As you can see, the "Important" factor comes second when sorting the nodes, and the taxonomy grouping comes first.

How can I change this behavior, so the following is achieved:

Node 1   Important:  100   Taxonomy: Referenzen
Node 4   Important:  100   Taxonomy: Referenzen – Media
Node 5   Important:   80   Taxonomy: Referenzen – Media
Node 2   Important:    0   Taxonomy: Referenzen
Node 3   Important: -100   Taxonomy: Referenzen

The executed query

SELECT node.nid AS nid, node.title AS node_title, node.language AS node_language, node_data_field_image.field_image_fid AS node_data_field_image_field_image_fid, node_data_field_image.field_image_list AS node_data_field_image_field_image_list, node_data_field_image.field_image_data AS node_data_field_image_field_image_data, node.type AS node_type, node.vid AS node_vid, node_revisions.teaser AS node_revisions_teaser, node_revisions.format AS node_revisions_format, node_data_field_important.field_important_value AS node_data_field_important_field_important_value, node_data_field_date.field_date_value AS node_data_field_date_field_date_value
FROM node node
INNER JOIN term_node term_node ON node.vid = term_node.vid
LEFT JOIN content_field_image node_data_field_image ON node.vid = node_data_field_image.vid
LEFT JOIN node_revisions node_revisions ON node.vid = node_revisions.vid
LEFT JOIN content_field_important node_data_field_important ON node.vid = node_data_field_important.vid
LEFT JOIN content_type_story node_data_field_date ON node.vid = node_data_field_date.vid
WHERE (term_node.tid = 2) AND (node.language in ('***CURRENT_LANGUAGE***')) AND (node.status <> 0)
ORDER BY node_data_field_important_field_important_value DESC, node_data_field_date_field_date_value DESC

The exported view

… can be downloaded here:

  http://cl.ly/1c2c0X3f1Q2L3Y3x3l3w

MySQL Query Browser

… however tells me that those that have the "Wichtig" field not set have the value NULL and therefore are sorted last. All newly created nodes get "Wichtig" set as 0, however all old ones still have NULL.

So what can I do to make those with NULL have the value 0 instead and how can I prevent this for new articles in the future?

Maybe the MySQL IFNULL() function could be the solution. It allows you to check the selected field value and give it a custom one when null.
In your SQL statement, instead of

node_data_field_important.field_important_value AS node_data_field_important_field_important_value

you should have:

IFNULL(node_data_field_important.field_important_value,0)  AS node_data_field_important_field_important_value

Try the modified SQL statement in your MySQL Query Browser and see if it works.

I'm an old database administrator, but a Drupal beginner, so I don't really know how to put this function in a View using the web interface. Do you?

I'm searching a way to add custom SQL to views (because as a beginner I'm interested too) and found something about hook_views_query_alter(). It belongs to Views 2 API.
You should use that hook to change the corresponding array value using your exported view code as reference for array indexes. I have no time to try it, but probably this is the right way.

IMHO another way should be taking the exported view code, modify it manually adding the IFNULL() MySQL function on the field name and then reimport it into a new view. I'm not sure that Drupal will write a correct SQL query or that it won't discard some SQL it doesn't expect... This should be the same as using the hook above, but in a rude and not to so elegant manner...

Hope it helps.


field output dependend on mime type of another field I have a node type with 2 fields: preview_image and file (multivalue).

I can upload image and video files.

For the output I need the following:

The preview_image should only be displayed when the first file of the file field (multivalue) has a specific mime type (in my case any video mime type).

Is there a solution for that?

UPDATE:

Now we have a change in field structure. We use 2 mime types, images and videos. But for the images we need a cropping function. And we need an easy possibility to arrange the files within node editor.

Now we would like to create 2 new node types - for example 'image' and 'video'. In both node types we create the file fields - in 'image' with the cropping function.

In the main node type we now create 2 fields as entity references to get the files.

Now we need a solution to display the preview image only when the referenced node is of type 'video'.

Show preview image:

media element (referencing field)

entity of type 'video' (referenced entity)
entity of type 'image' (referenced entity)
entity of type 'image' (referenced entity)
entity of type 'video' (referenced entity)

Don't show preview image

entity of type 'image' (referenced entity)
entity of type 'image' (referenced entity)
entity of type 'video' (referenced entity)
entity of type 'image' (referenced entity)

This can be done with a template preprocess added to the template.php file in your theme. You would need to test for the video mime type on the correct node and then use Drupal's hide function, to tell Drupal to skip the field on render.

    /**
     * Override or insert variables into the node templates.
     *
     * @param $variables
     *   An array of variables to pass to the theme template.
     * @param $hook
     *   The name of the template being rendered ("node" in this case.)
     */
    function THEMENAME_preprocess_node(&$variables, $hook) {
      $type = $variables['type'];

      switch ($type) {

          case 'NODE_TYPE_MACHINE_NAME':

            if (isset($variables['FILE_FIELD_MACHINE_NAME'][0])) {
              $mime_type = $variables['FILE_FIELD_MACHINE_NAME'][0]['filemime'];
              $mime_regex = '/^video/';
              // We have to check the string for the presence of "video", because it could be any of 18 video mime types.
              $is_video = preg_match($mime_regex, $mime_type);

              if ($is_video) {
                hide($variables['content']['IMAGE_FIELD_MACHINE_NAME']);
              }

            }
          break;
      }
    }


Create a new user in LDAP, not wherever Drupal normally creates it We have an already existing LDAP of users, that we wish to use for our new site. Amazingly, the login seems to be only finding the users we want it to, and not the users we don't. We have to figure out why, because we'll probably want to change this in the future. (I mention, in case it's related to my main issue.)

However, the more important problem is that, when we create a new user, we want it to be created in the LDAP, not wherever Drupal creates it. As I understand, when it authenticates against LDAP, it simply copies the user to it's own database, and uses that from then on, which is also not what we want, in case the user changes their data. However, we'd still like the admin user to work, even if the LDAP dies or something. The documentation isn't much help with this.

So, how do I make Drupal (I'm using 7, but I don't know if it's 7 specific) use the LDAP for the creation of new users, and for existing LDAP users? (Hopefully, without totally removing the ability to use the users already in the Drupal db.)

You will never be able to use Drupal's core user module without using the database's user table (and many others), without seriously modifying core Drupal.

It sounds like the only reason you want Drupal to not use it's own user + roles + permissions management (and all of the other contributed Drupal modules that depend on the user module) is so that if a user updates some data in LDAP it's also updated in Drupal. If this is the case, find a method for synchronizing your LDAP user info with Drupal's user info.

You can use the hook_user_ functions in Drupal to perform whatever actions you want to happen when a user account is created, updated, etc., in Drupal. For example, if a new user account is created in the Drupal user registration form you'd be performing whatever logic you need (via PHP, or potentially something else) to insert a new record into your LDAP server.


Form value not submitting for a function called from ajax I have created a form for creating some beaches. In that I have to give the value of continents,country ,name of beaches. Names of the countries and continent are stored in the taxonomy table. so if the user selects the continets, by using ajax it displays the list of countries belonging to the continent. my code look like..

function iks_beaches_create($node, &$form_state) {

drupal_set_breadcrumb(array(
    l('beaches', 'beaches'),
    'Add New Beaches'
));
    $form['iks_beaches_continents'] = array(
    '#title' => 'Continents',
    '#description' => 'Taxonomy vocabulary defining Continents',
    '#type' => 'select',
    '#options' => iks_beaches_getTerms(variable_get(IKITESURF_BEACHES_CONTINENT, '')),
    '#required' => true,
    '#ajax' => array(
    'callback' => 'countryDisplay',
    'wrapper' => 'countryDisplay',
    'event' => 'change',
     ),
     );
    $form['countryDisplay']['iks_beaches_country']= array(
     '#type' => 'select',
     '#options' =>iks_beaches_getTerms(variable_get(IKITESURF_BEACHES_REGIONS, '')),
     '#title' => 'Country',
     '#required' => true,
     '#description' => 'Taxonomy vocabulary defining Country',
     );
     $form['regionDisplay']['iks_beaches_regions'] = array(
     '#title' => 'Regions',
     '#description' => 'Taxonomy vocabulary defining Regions',
     '#type' => 'select',
     '#options' => iks_beaches_getTerms(variable_get(IKITESURF_BEACHES_REGIONS, '')),
     '#required' => true,
     );

     $form['countryDisplay'] = array(
     '#type' => 'markup',
     '#prefix' => '
',
     '#suffix' => '
',
     );

the corresponding ajax function is

 function countryDisplay($form, &$form_state){
    $city = isset($form_state['values']['iks_beaches_continents']) ?        $form_state['values']['iks_beaches_continents'] : 'default';
    $query = new EntityFieldQuery();
    $entities = $query->entityCondition('entity_type', 'taxonomy_term')
                      ->propertyCondition('vid', variable_get('iks_beaches_countries'))
                      ->fieldCondition('field_continent', 'tid', $city)
                      ->execute();
    if(isset($entities['taxonomy_term']) && count($entities['taxonomy_term'])) {
    $countries = taxonomy_term_load_multiple(array_keys($entities['taxonomy_term']));
    foreach($countries as $coutry){
   $options[$coutry->tid]=$coutry->name;
   }
    }
    $form['countryDisplay']['iks_beaches_country'] = array(
         '#type' => 'select',
         '#options' => $options,
         '#title' => 'Country',
         '#required' => true,
         '#description' => 'Taxonomy vocabulary defining Country',
        );
return  $form['countryDisplay'];
}

But countries value is not displaying on form submit

function iks_beaches_create_submit($form, &$form_state) {
echo "
";print_r($form_state['values']);echo "
";exit; }

Array
(
    [iks_beaches_continents] => 673
    [iks_beaches_regions] => 783
    [location_name] => hdnffgh
    [description_location] => fgdh fgh fg hrt yry bnmbv mbcsd rty
    [travelling_details] => fh ty vcrsw t ytrywswe5
    [location_facilities] => ry  yuf d sdaf sa warewe svbvcber
    [tags] => e
    [longtitude] => 23.536343
    [latitude] => 45
    [images0] => 13803
    [images1] => 0
    [images2] => 0
    [images3] => 0
    [images4] => 0
    [images5] => 0
    [images6] => 0
    [images7] => 0
    [images8] => 0
    [images9] => 0
    [submit] => Publish Beach
    [form_build_id] => form-ZpuHlTPwSjJ2ElN_nPlSTsmHdQC6mmvSyKQOfMy4xvM
    [form_token] => n6vBuvZLJJNdcjdYERIsOm2REge8JoJMOSMmEuzpom8
    [form_id] => iks_beaches_create
    [op] => Publish Beach
)

Your mistake is a misconception about AJAX callback function. In Drupal, all permanent changes to a form needs to be done in form creation function, in your case iks_beaches_create. Function pointed in ['#ajax']['callback'] has the only purpose to determine what part of form is supposed to be updated. It can change $form, but these changes are one-time only, and preparing form to save values counts as a second time. Move all your form assembly logic to iks_beaches_create, so you could trim callback to

function countryDisplay($form, &$form_state){
  return  $form['countryDisplay'];
}

and it will work.


Migrate module problem with migrating images - D7 I am attempting to migrate images from a directory into an image field. All of my other fields are migrating correctly. No errors are being thrown, the database values do not appear and the image is not copied into the destination directory.

// Image migration
// basic mapping of destination field and source field
$this->addFieldMapping('field_figurae_image', 'highresfile');
// Directory where source images are located
$this->addFieldMapping('field_figurae_image:source_dir')
     ->defaultValue(drupal_get_path('module', 'migrate') . '/matrixmigrate/matrix_libary');
// Directory that source images will be copied to
$this->addFieldMapping('field_figurae_image:destination_dir')
     ->defaultValue('sites/default/files');

I believe my syntax is at least close to correct here. It is based on the "BeerNodeMigration" example. I had difficulty with Taxonomy migration that had very similar results. It turned out that I had another piece of code that was not formatted correctly. This is the only code I have related to images, is there an additional step that I'm missing?

Thank you for your time.

-Mitchell

I think my source_dir path was incorrect. I used the following and it worked:

// Image migration
// basic mapping of destination field and source field
$this->addFieldMapping('field_figurae_image', 'highresfile');
// Directory where source images are located
$this->addFieldMapping('field_figurae_image:source_dir')
     ->defaultValue(drupal_get_path('module', 'matrixmigrate') . '/matrix_library');

The major difference here is that I used my sub-module instead of the migrate module itself to grab the path. I also played with permissions in various directories. I think one of those two things did it. I also dropped the destination directory since it defaults to your Drupal file directory.


Sliding Popup in Drupal 6 Im trying to create a sliding popup using jQuery in my drupal module .

Referring the code from:

http://karlagius.com/2009/02/08/creating-a-sitepoint-like-sliding-popup-in-jquery/

My popup window, defined in the module, is a html string (using divs, a, img etc) .

How do I pass this html string to .js file. It gets used there in .get(url, function(data)).

Tried using drupal_to_js and drupal_json, both returns the value 0, not the string.
Need some suggestion on how to proceed.

You need

a hook_menu() implementation that will provide you with the url:
a page callback funtion that does print() or echo on the html snippet, then exit(). So no drupal_to_js() or drupal_json().


Track Browser and set site language I have these modules installed:

cck-6.x-2.9

i18n-6.x-1.10

token-6.x-1.18

views-6.x-2.16

I would like to set the language of the website by checking the language used by the browser and set that as the website language.

Is this something that is possible?
Can you show an example of how to do this?

If writing code is not an issue you could probably handle this in your custom module's hook_init() implementation by using sessions (to check if the user has been redirected already) and PHP-s $_SERVER['HTTP_ACCEPT_LANGUAGE'] variable. Assuming that your site is using path prefixes to determine the language the code could be something like this:

function mymodule_init() {
  // If the user landed on the front page and hasn't been redireced during their session.
  if (!isset($_SESSION['mymodule_redirected']) && drupal_is_front_page()) {
    global $language, $base_url;
    $current_lang = $language->language;
    // Available languages besides the sites main one that is using $base_url as it's path.
    $available_langs = array('en', 'de');
    $langcode = explode(";", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
    $langcode = explode(",", $langcode['0']);
    $langcode = explode("-", $langcode['0']);
    $lang = $langcode[0];
    $_SESSION['mymodule_redirected'] = TRUE;
    if (in_array($lang, $available_langs)) {
      if ($lang == 'en' && $current_lang != 'en') drupal_goto($base_url . '/en');
      if ($lang == 'de' && $current_lang != 'de') drupal_goto($base_url . '/de');
    }
  }
}


URL alias, tokens is replacing 0s and 1s with node and entity Has anyone seen a case that url aliases or tokens end up replacing certain numbers in a url with the words node and entity. A UTC Timestamp in my url ended up replaced like this:

node4328522entityentity

I cannot find any errors in the watchdog table. It seems like it's trying to "encode" numbers, but those are numbers that shouldn't be encoded. Or another possiblitiy I've thought of is maybe it is trying to grab something out of a non-existent array at index 0 and 1?

This seems pretty similar to what is asked in the question about Tokens causing incorrect text substitutions .

Refer to my answer in that question for various options to further debug what might be going on. If you can, please enhance your question (by editing it) to indicate which of the possible reasons in your case do apply, or don't apply at all.

Also note the brand new comment there (from "diego"),
here is what that comment says:

  I was able to find a work around at east for the Webform submissions. If I use a Rule to send the email (using [data:{field-name}-display] tokens) instead of the Webforms built in email function it doesn't seem to substitute any of the tokens.


small php script used in drupal module not clear with arrays in php Here is a small PHP code which I am not clear with.

/**
* Form for configurable Drupal action to beep multiple times
*/
function beep_multiple_beep_action_form($context) {
$form['beeps'] = array(
'#type' => 'textfield',
'#title' => t('Number of beeps'),
'#description' => t('Enter the number of times to beep when this action executes'),
'#default_value' => isset($context['beeps']) ? $context['beeps'] : '1',
'#required' => TRUE,
);
return $form;
}

In the above user defined function return $form what does it return? How do you access the individual elements of $form['beeps'] what is the significance of writing word beeps in square braces in $form['beeps']

function beep_multiple_beep_action_validate($form, $form_state) {
        $beeps = $form_state['values']['beeps'];
        if (!is_int($beeps)) {
        form_set_error('beeps', t('Please enter a whole number between 0 and 10.'));
        }
        else if ((int) $beeps > 10 ) {
        form_set_error('beeps', t('That would be too annoying. Please choose fewer than 10
        beeps.'));
        } else if ((int) $beeps < 0) {
        form_set_error('beeps', t('That would likely create a black hole! Beeps must be a
        positive integer.'));
        }
}

In above code what is

$beeps = $form_state['values']['beeps'];

line doing?

In your first section of code, that function is creating a form using Drupal's Form API and $form['beeps'] contains the settings for a single form element, in this case a textfield.

The second function is the one is used to validate the form values and will display an error for any unacceptable value.

$beeps = $form_state['values']['beeps'] fills the variable $beeps with the value of the "beeps" textfield from the form generated in the first function.


How to import config and content using config import and hook_update_N Background: I have config read-only setup on non-development environments. So all configurations (including enabled modules) are created and exported from development site and imported to different environment.

Problem: I need few new content entity types to be imported and add content of those types in database update (i.e. hook_update_N()).

As per https://www.drupal.org/node/2762235, all database updates should run before configuration import. Since my entity definitions are in configuration,  hook_update_N throws fatal that entity types do not exist. I can run config-import after hook_update_N, but it can cause other problems (as mentioned in above d.o issue).

How to import configuration and content in this case?

Don't add content using hook_update_N() there's not really anyway to make that work if the entity types are in config. What you can do is just use something like default content and add you own step to config import to look to see if any installed modules provide default content and create that.


drupal 7 programatically close comments in custom node type I have created a content type programmatically. Also looked at http://drupal.org/node/1169864 but comments are not being close. Although I solve it by variable_set('comment_mynodetype', '1'). Any other help.
My code is below:

$t = get_t();

  $node = array(
    'type' => NODE_NAME,
    'name' => $t('My Node Type'),
    'base' => 'node_content',
    'locked' => TRUE,
    'node-preview' => 0,
    'node-options' => array('status'),
    'comment' => array('status' => 1),
    'description' => $t('A content type.'),
    'title_label' => $t('Title'),
    'custom' => FALSE
  );
  $content_type = node_type_set_defaults($node);
  //add body field using drupal function
  node_add_body_field($content_type, $t('Description'));
  node_type_save($content_type);

Any help ..

[UPDATED]

 $node = array(
        'type' => NODE_NAME,
        'name' => $t('My Node Type'),
        'base' => 'node_content',
        'locked' => TRUE,
        'node-preview' => 0,
        'node-options' => array('status'),
        'description' => $t('A content type.'),
        'title_label' => $t('Title'),
        'custom' => FALSE
      );
   //close comments
   variable_set('comment_mediasite', '1');

$node->comment should be an integer (not an array). Acceptable values are:

COMMENT_NODE_CLOSED
COMMENT_NODE_HIDDEN
COMMENT_NODE_OPEN


Different entity types for one field value I have a content type "Application".  And "Site Administrator" and "Developer" users are allowed to add it.

If logged-in user is "Site Administrator", the value of "Author" field will be the reference of other content type. So, in the respective field table,

entity_type : node, bundle : {content-type-name}

If logged-in user is "Developer".  I'd like to save current logged-in user id as the value of "Author" field.

entity_type : user, bundle : user

How could I get it with drupal?

Thanks in advance.

The "author" field would be a User Reference field.
You can use hook_form_alter to limit this fields allowed $options to be either the logged in user, or the list of users of Developers.

Something similar too ...

function MYMODULE_hook_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == 'node_add_application') {
    if (in_array('Developer', $user->roles)) {
      // Set the default value of the author field to the logged in users uid.
      $form['field_AUTHOR_FIELDNAME']['options']['#default_value'] = $user->uid;
    }
    if (in_array('Site Administrator', $user->roles)) {
      // Overwrite the general users list with UIDs only of a specific role.

      // Get uids of a specific role.
      $query = 'SELECT DISTINCT(ur.uid)
          FROM {users_roles} AS ur
          LEFT JOIN roles r on ur.rid = r.rid
          WHERE r.name = :role';
      $result = db_query($query, array(':role' => 'Developer'));
      foreach ($result as $row) {
        $developer_uids[] = $row->uid;
      }
      foreach ($form['field_AUTHOR_FIELDNAME']['options'] as $uid => $label) {
        if (!in_array($uid, $developer_uids)) {
          unset($form['field_AUTHOR_FIELDNAME']['options'][$uid];
        }
      }
    }
  }
}

This is a rough example of the logic and code it would take to alter the select list of user names for the author field to either default to the logged in developer, or show "site admins" only developers.

I have written such code before, this exact code is only an example based upon the details given in your question. It is un-tested.


Is it possible to create a calculation field using database abstraction layer? I am trying to work out if it is possible to write the following using Drupal's database abstraction layer.  The tricky bit is the second field which is a function to calculate distance.  Is it possible to include this calculation field (3959 * acos(cos(radians(:lat)) * cos(radians(field_bluescope_geolocation_lat)) * cos(radians(field_bluescope_geolocation_lng) - radians(:lng)) + sin(radians(:lat)) * sin(radians(field_bluescope_geolocation_lat)))) AS distance using the abstraction layer?

  $result = db_query_range('SELECT '
  . 'geo.entity_id, '
  . '(3959 * acos(cos(radians(:lat)) * cos(radians(field_bluescope_geolocation_lat)) * cos(radians(field_bluescope_geolocation_lng) - radians(:lng)) + sin(radians(:lat)) * sin(radians(field_bluescope_geolocation_lat)))) AS distance '
  . 'FROM '
  . 'node__field_bluescope_geolocation AS geo '
  . 'INNER JOIN '
  . 'node__field_bluescope_consumer_supp AS consumer_supp '
  . 'ON '
  . 'geo.entity_id = consumer_supp.entity_id '
  . 'WHERE '
  . 'geo.bundle = \'bluescope_business\' '
  . 'AND '
  . 'consumer_supp.field_bluescope_consumer_supp_target_id = 28 '
  . 'ORDER BY distance', 0, 200, [':lat' => $lat, ':lng' => $lng]);

Yep Haversine should work without a problem. This is slightly modified from a production site which is up and working right now, for example:

$lat = 51.5014;
$lng = 0.1419;

$query = db_select('field_geo_latitude', 'f')
  ->fields('f', array('entity_id'))
  ->orderBy('distance');

$earth_radius = 3959;
$expr = "(
  $earth_radius * acos(
    cos(radians(:lat))
  * cos(radians(field_geo_latitude))
  * cos(radians(field_geo_longitude) - radians(:lng))
  + sin(radians(:lat))
  * sin(radians(field_geo_latitude))
  )
)";
$query->addExpression($expr, 'distance', array(':lat' => $lat, ':lng' => $long));

$query->having('distance <= :radius', array(':radius' => 10));

Resulting query:

SELECT f.entity_id AS entity_id, (
  3959 * acos(
    cos(radians(:lat))
  * cos(radians(field_geo_latitude))
  * cos(radians(field_geo_longitude) - radians(:lng))
  + sin(radians(:lat))
  * sin(radians(field_geo_latitude))
  )
) AS distance
FROM {field_geo_latitude} f
HAVING  (distance <= :radius)
ORDER BY distance ASC

When executed all the parameters are replaced as expected.


How do I add a thumbnail to the teaser of a blog post containing an image? I am using Drupal 7 and have added an image field to the blog content type.  The image comes in fine when creating the blog post, but when viewing the teaser of the blog entry in the list of user's blogs, there is no thumbnail in the teaser showing that there is an attached image.  Is this possible to have? How do I do it?

Go to display settings for your content type ('blog post'), and then select teaser ex.:

/admin/structure/types/manage/article/display/teaser

From here you can control which fields will display in your teaser (or full, or other defined formats). Your image field is most likely hidden for your teaser, you'll want to have it displayed and style accordingly.


Why does DRUPAL_BOOTSTRAP_PAGE_CACHE phase come before DRUPAL_BOOTSTRAP_DATABASE? According to this article about drupal_bootstrap function, all parameters for drupal_bootstrap() run sequentially. And if we see the sequence, here first comes - DRUPAL_BOOTSTRAP_CONFIGURATION, second DRUPAL_BOOTSTRAP_PAGE_CACHE and then database (DRUPAL_BOOTSTRAP_DATABASE),

So, My question is cache is itself stored in database, so in order to serve pages from cache, a database connection is a must. Then How Drupal manages these calls sequentially?

Accordingly, DRUPAL_BOOTSTRAP_DATABASE should come before DRUPAL_BOOTSTRAP_PAGE_CACHE. If not, what is the reason?

Inside of _drupal_bootstrap_page_cache() the key bit of information is this bit of code

  if (variable_get('page_cache_without_database')) {
    $cache_enabled = TRUE;
  }
  else {
    drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES, FALSE);
    $cache_enabled = variable_get('cache');
  }

The call to bootstrap DRUPAL_BOOTSTRAP_VARIABLES will also bootstrap DRUPAL_BOOTSTRAP_DATABASE because it's before variables inside of drupal_bootstrap()

What this means is if your cache doesn't require a database connection (like memcache or filecache) then you can speedup page cache hits by not connecting to the database. The linked article talks about this.


How can I stop auto uploading of managed_file elements? I am trying to create a field to upload the xml format of site map. But when I add a file to my filed it automatically uploaded and saved in the S3 bucket before I click on the submit button.

The issue is when someone added a xml file to that field and then closes the tab without submitting the form. The xml file is already uploaded to S3 bucket that way.

I need a way to manually upload this. I need to upload the image only after I pressed the submit button in the form. Without uploading the xml file automatically when selecting.

This is my buildForm() function.

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

  $form['sitemap'] = [
    '#type'              => 'managed_file',
    '#name'              => 'sitemap',
    '#title'             => t('Upload Site Map (xml)'),
    '#upload_location'   => 's3://private/sitemap',
    '#field_suffix'      => 'XML format supported',
    '#upload_validators' => [
      'file_validate_extensions' => ['xml'],
    ],
    '#required'          => TRUE,
    '#validated'         => TRUE,
  ];

  $form['submit'] = [
    '#type'       => 'submit',
    '#value'      => t('Save configuration'),
    '#attributes' => [],
    '#validated'  => TRUE,
  ];

  return $form;
}

Try overriding the #attached library on the managed file field:

$form['sitemap'] = [
'#type'              => 'managed_file',
'#name'              => 'sitemap',
'#title'             => t('Upload Site Map (xml)'),
'#upload_location'   => 's3://private/sitemap',
'#field_suffix'      => 'XML format supported',
'#upload_validators' => [
  'file_validate_extensions' => ['xml'],
],
'#required'          => TRUE,
'#validated'         => TRUE,
'#attached'          => [
   'library' => [],
 ]

];


Creating Tabs using Drupal? I have been looking for a solution that allows me to add tabs to my website something similar to this page.

So far I have been using HTML inside of ckeditor to write all my content. However, now I need to be able to have a form and tabs.

Can someone provide me a module or a solution to have tabs and form ?

Thank you in advance

H.

Quicktabs + Webforms. You can have multiple pages (nodes) or blocks and using the quicktabs module would allows you to have the different insert those pages or blocks into tabs. To created the field form you can used the Webform module and inserted into quick tabs module.


Clicking any administration menu link results in empty overlay screen I've created a Drupal site which behaves rather strange - whenever I click an item in the administration menu or use a contextual link to edit a page, the half-opaque overlay shows, but no editing window opens on top of it as it should  (not just "not immediately", but never).

Once I'm in "overlay mode", if I click a menu item, the linked page opens as it should, on top of the overlay. From here, all items work as intended, except when opened in a new tab - that will also only show an empty overlay page.

When the overlay is eventually closed again (for example, by clicking the home link to return to the front page), the error described above will reoccur the next time an administrative link is clicked.

Can anyone assist me in finding the source of this problem? Please let me know if you need additional information.

The site was built on 7.53 originally and is now updated to 7.54 (up to date). No changes to the .htaccess file have been made, therefore all of my changes are within the /sites/ directory.

I'm using these contrib modules: Chaos tools, CKEditor, Views, Views UI, Webform

My administration theme is Seven.

I've set up other Drupal 7 sites on the same environment and didn't have this problem, so I clearly I did something different here. I have no idea where to start looking, though, and wasn't successful in finding other questions or external info covering anything even remotely related.

The issue turned out to be caused by me including jQuery via the following line in my theme's info file:

scripts[] = js/jquery-3.1.1.min.js

Removing this line and using the jQuery version included by default (1.4.4) will return the $ is not a function error when using $() syntax, which can be resolved by wrapping existing jQuery code in the following:

jQuery(function ($) {
  // ...
});


display nodes of types on a menu item : drupal 7 I have created some nodes of type books and now I want to display some of them on a menu item. How can I do that without using views?

Mome | Books | Atricles |

node type: (Machine name: books)

For example above is my menu structure. And when a user click books it will show some of the books I have created.

Is it just the book name? Like a list of the names and then you can click on it and view more information? In that case, you could just put those book links in the menu itself (if you have a drop-down).

Otherwise, and the more doable option is to just use Views and have it create a page that displays the names of all of the books you've entered.

Is there a reason why you are opposed to using Views to do this?


Clear a single url from cache Using Drupal's standard cache system, is there a way to clear the cache for a node or url without clearing the entire cache (which slows down the whole site)?

The module Cache actions provide very fine grained control over your cache clearing.

Unfortunately, whether it will solve your exact problem depends on how this particular url is built up. In case it doesn't do exactly what you want, it's codebase would still be an excellent start for building more exactly what you need.


Create content after editing other content-type I have a certain content-type B with an entity reference to items of content-type A.

I'm trying to programmatically create a content-type B node when a bool field in content-type A is set to true, whether during creation of content-type A or update/editing of content-type A.

Something like this story:

  When user creates or edits a news content (ie, sets the push_to_slider field as true), create a slide content if it doesn't exist. If the user sets the field as false, delete the slide content.

I've been exploring how to do this, and I found out about hook_entity_presave. So, right now, I'm able to check what was edited in the content-type A form, and if it is being created or updated.

My questions are:

How can I find out the ID of the content-type A node? I need to know it so I can pass it along when I getStorage('type-B')->create(array). This might be available when editing a A-type node, but not when inserting it, at least not in hook_entity_presave. As far as I can tell, I might be doing this in the wrong place as this hook operates before the DB insertion, is this correct? As such I think I wouldn't have access to an ID at this point. What could be the alternative?
Also, how can I find out if a B-type content already exists referencing the A-type node I'm working with? I intend to use that to find out if what I need to delete in case the option in the form is set to false.

Hope this makes sense. If not, let me know and I'll try to clarify. Any help would be very appreciated.

How can I find out the ID of the content-type A node?

You should use devel module's kint function to get all available methods of an object, and you could easy find out, that it's: $node_object->id();

how can I find out if a B-type content already exists referencing the A-type node I'm working with?

You will write a Database service query (not pure sql query), where you will have two important condition:

the node type must be B
it's reference field contains the id of the A content.

You will of course have to use table joins. To better understand the schema representation of your content types, I suggest you do use phpmyadmin parallel.


Show node in overlay using drupal 7 overlay module Is there anyway to open a overlay with a node content using drupal overlay core module? If I could reuse at least the javascript code I'd already be happy =)

The faster way is to implement hook_admin_paths_alter() in a module to redefine which of the menu items defined in hook_menu() by other modules are administrative paths.
The value returned from the implementations of hook_admin_paths(), which are then altered from the implementations of hook_admin_paths_alter(), are used from the Overlay module to decide which pages are rendered as overlay. As other modules could use the same information to render the pages using a different theme, the module should require the Overlay module as dependency, to be sure the additional pages are effectively rendered as overlay.

function mymodule_admin_paths_alter(&$paths) {
  $paths['node/*/view'] = TRUE;
}

If you notice that this implementation doesn't work when the users are viewing, for example,example.com/node/1, but only when they are viewing example.com/node/1/view, then I would implement the hook using the following code. The first implementation I provided should work, as the "View" tab is the default one, and when users are viewing example.com/node/1, Drupal is really showing example.com/node/1/view.

function mymodule_admin_paths_alter(&$paths) {
  $paths['node/*'] = TRUE;
  $paths['node/*/view'] = TRUE;
}

As the first line could catch all the node pages (I didn't verify that), I would verify if there are other pages under that path that should not be rendered; in that case the implementation can be changed as the following one ("node/*/backlinks" is only an example):

function mymodule_admin_paths_alter(&$paths) {
  $paths['node/*'] = TRUE;
  $paths['node/*/view'] = TRUE;
  $paths['node/*/backlinks'] = FALSE;
}

Normally, modules implement hook_admin_paths() to report which of their menu items are administrative pages; this means that if a page is not an administrative page, an entry for that page is not added to the returned array.
hook_admin_paths() is implemented for the menu items defined in your own module; to redefine when menu items defined from other modules are administrative pages, you need to implement hook_admin_paths_alter().
To the pages that are defined as administrative pages is not automatically applied an access control; this means that the module defining those menu items that are reported to be administrative pages still need to use "access callback" and "access arguments" to define which users can access those menu items associated with administrative pages. Pages defined as administrative pages are only rendered differently, if there is a module that does that.
The node module defines the node editing pages as administrative page only when a checkbox in an administrative page is selected; those pages are already handled.


View which filters based on URL matching field value I'm trying to create a view for solr search results, what I'd like to do is have have a page in the view each of which pull data from the same set of results but filter them based on matching part of the URL to a field in the content type being indexed.

The problem is the part of the URL used for matching won't match the value of the field in content type, so I was thinking of having a list of some sort which would match the URL with the corresponding field value.

Is this even possible? If it's not I could always create a new view page for each possible URL & manually set a filter criteria. I was just hoping that rather than creating multiple view pages I could do it with one.

I wasn't able to do exactly what I wanted but what I did instead was create an exposed filter for the field in the content type being searched & use the URL parameter it created when in use to filter search results.

The exposed form itself is hidden with CSS as just including the filter without exposing it won't allow it to be activated via a URL parameter.


Strange Page not Found, Permissions, Clear cache On my D7.80 I have developed a custom module:
    function wrong_answer_menu() {
    dd('it entered in hook menu');
  $items['wrong-answer/%id'] = array(
    'title' => t('Wrong Answer Dashboard'),
    'page callback' => 'wrong_answer_dashboard',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
  );

  return $items;
}

/**
 * Callback: hook_menu.
 */
function wrong_answer_dashboard($node_param=NULL) {
dd('it entered in dashboard');
....
}

Everything was fine, I was developing the menu nicely accessing the
mydomain.com/wrong-answer
and everything was fine.
Then I wanted to add permissions to my custom module, so that only the admin can access this page hence I added the wrong_answer_permission function and in the dashboard function I checked if the user had permission to access the page
/**
 * Implements hook_permission().
 */
function wrong_answer_permission() {
  return array(
    'wrong_answer_' => array(
      'title' => t('View the wrong answer'),
    ),
  );
}

    function wrong_answer_dashboard($node_param=NULL) {
     dd('it entered in dashboard');
     if (!user_access('wrong_answer_admin')) {
      return;
     }
    ....
    }

At this stage, when I accessed the page mydomain.com/wrong-answer I could still access it even though I did not assign the permission to it. Then I cleared the cache from the Performance menu via the admin/config/development/performance, and then I got the error message
The requested page "/wrong-answer/717" could not be found.

I get the same error for acessing just mydomain.com/wrong-answer.
Then I thought it was all fine, I added the permission wrong_answer_admin to the admin role, but then I still got the same error "The requested page .... could not be found.
Afterwards, I:

cleared the cached
removed the code that I had added on the permission and checking the user access
rebuild the registry_file by emptying the table and running the update.php
assigned the permission to the wrong_answer_admin to all the roles, including anonymous role
deleted the wrong_answer_admin row in the permissions table in the database
disabled and re-enabled by custom module

but nothing worked, I still get the error "The requested page cannot be found".
Then I noticed the strangest thing, that whenever I would clear the cache at, I would would get an entry in the drupal_debug.txt
it entered in hook menu

I do not get this entry in the drupal_debug.txt when accessing the wrong-answer page, I only get it when clearing the cache.
Could you please help me understand what is going on? why can't I access the wrong-answer page anymore?
Many thanks

An answer to part of your question:

Then I noticed the strangest thing, that whenever I would clear the
cache at, I would would get an entry in the drupal_debug.txt
it entered in hook menu
I do not get this entry in the drupal_debug.txt when accessing the
wrong-answer page, I only get it when clearing the cache.

If Drupal built the menu for every page load, it would result in heavier page loads. As such, hook_menu() is only called after the cache is cleared, as the menu cache is rebuilt the first time it is needed and no cache exists. Once it's been cached, hook_menu() does not get called anymore.


Webform doesn't send hidden input if sender is not logged-in I have a webform which works fine only it is submitted for logged in users.

The problem is that the webform includes a hidden input. When I receive the email (sent by the webform) I can see all the values for the inputs, but the hidden input value is missing.

This does not happens if the webform is submitted for a logged in user.

Is this something related to permissions?

thanks

Can you give us the token you use for the hidden field? Maybe the token you use only available for logged user. I used hidden fields but with a general token (for example date or ip_adress) and it works fine for non logged users


CSS customization won't work Recently, I signed up with the Amazon's Lightsail service that comes with a version of Drupal (8.3) provided by Bitnami. I am not sure how this is different from any other installations, but when I tried to increase the font size of my site name, it wouldn't work.
The file I updated is style.css under ~/apps/drupal/htdocs/themes/zircon/css. (I am using the Zircon theme.)
The CSS ruleset I added is the following.
.site-name {
  font-size: 30px;
}

I tried clearing the cache, unchecking the "Aggregate CSS files", but none of them works.
Googling, I learned that adding a sub-theme is recommended for the job, that I tried, but the admininistration pages of the site simply wouldn't load after I created a folder (with the .yml file in it) under the themes(~/apps/drupal/htdocs/themes) directory.
Is it still possible to update a given style.css file from a given theme?

It seems like you updated the CSS semi-correctly.  Semi because, it does look like Zircon's CSS is built using SASS/Compass and not directly. You might want to look at how to set this up properly.
You are also correct that you really need to set up a sub-theme first.  The reason to do this is that when updates to the Zircon theme come out, you will need to figure out what you changed, save it, update the theme and then re-merge your changes.
See the documents on how to set up a sub-theme.
As to why your CSS change did not take effect, these are some possibilities:

First, your rule was added, but is being overridden by a more specific rule.  Inspect the element and see if the rule shows up but it's red lined.
A quick hack is to just add !important to your rule.  This should make it most specific, unless someone else added it to their rule.
The best way would be to get SASS/compass set up, find where the .site-name is themed in the SASS files, change it there, and rebuild the CSS with Compass.

If it's not a CSS rule thing, it might be an external caching system.  First, I assume you did a FULL reload of the page (Generally Shift F5) to clear the local browser cache.

Next, did you set up Varnish with your site?  If so, you might need to clear the Varnish cache, or set up some rules so that logged-in users don't use cache.

Are you using something like Cloudflare? This can also cache CSS. You can check for external caching by using Chrome's Network tab (inspect something on the page or select the Network tab). Look for the CSS file that you modified, click on it, then check the headers. See if there are any tags like CF-xx or X-varnish with values like hit or miss. (A hit means it was served from cache).

That said, while you are developing a site, you probably want to do what you did:

Turn off all aggregation
Turn off caching (Config -> Devel-> performance)

This might seem a bit daunting but it's really not.


How to create anchor link to another page I want to set an anchor link on a page to an anchor on a different page. I have been able to do this using CKEditor, specifying the target anchor and then specifying an href for the link in CKEditor to, for example, /training/classes/#puppy-training.

This works, but the resulting URL obviously includes the #,  instead of /training/classes/puppy-training. Is there any way to remove the # mark from the URL?

This is using nodes built with custom content types in Drupal 7. I've also noticed the Links module, and wonder if it might be of any any help setting up anchors?

I'm also wondering how to approach this if I was using Views.

If 'puppy-training' is a section on the '/training/classes' page then there is not a way to remove the '#' symbol. The '#' symbol is a fragment identifier. It is supposed to refer to a location within a resource (i.e., the '/training/classes').

If you would like to have a URL without the '#' symbol, I would recommend creating a separate node for that piece of content.


How to get notifications in a new window when using the Mentions module? I am using the Mentions module to be able to tag other users in a posts.

I also installed the Rules module and made a new rule which sends email and shows a message on site if the logged in user is mentioned in a blog.

But I need notifications like this to be displayed in a new window.

How can I achieve that?

You could also use the Message module for this. So that you expand the rule you already have (or clone it in a variation of it) to have the Rules module create message "entities" (which is what you get if you use the Message module). And then just use the power of Views to display those messages that got created in the format you need (page, block, etc).

Here is a blueprint of what you'd need:

Define an appropriate Message type, using the Message module. Think of Message types as similar to "Content types", which will be used to create Messages, similar to Nodes. I'd imagine that the message text you'll  want to use is similar to the eMail or messages your existing rule already produces.
Enhance your rule with a Rules Action "Create entity" (of type "Message"). Refer to the answer in Which user related token(s) can be used to create a Rule for setting up a message type? for some examples, which are related to these variations of using Mentions:

A user gets flagged (using Flag).
A user is mentioned (using Statuses (Social Microblog)).

Make sure to also add a Rules Action to pass any relevant tokens from Statuses, via Rules, as Replacement tokens that you can use in your Message type you created with the Message module. Refer to What's the purpose of "Replacement tokens" of a Message type? for more details on this.
Use Views to display the created messages in the format you prefer.


Which Rules event can I use to send a weekly mail to all users using Rules? I'm using Drupal 7 and I need to send a weekly mail to all users.

I want to use the Rules module to do this. But I couldn't find a Rules Event which allows for this.

How can I implement that?

Below is a blue print of how I would resolve this challenge, without any custom code needed ...

Step 1: Enable the 'Rules Once per Day' module

Have a look at the "Rules Once per Day" module. Here is how it works (as per the comment in issue 2495775, from the module owner):

You specify a trigger hour on the administration settings page for this module.
The Rule trigger will then run when cron tasks are first run after the start of that hour. The actual run time will depend on your cron task timings.

So this is another way to understand/Read this:

The "Event" will only be triggered when a cron job is run.
And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

On top of that, also note what's mentioned on its project page, ie:

  The module also provides a "Day of the week is a" Rules condition, to further restrict actions to being run on specific day(s) of the week, on working days only, or at weekends only.

With that, you should be able to adapt any rule to perform its rules actions only once a week.

Step 2: Create your custom rule

As per your "mail to all users" requirement (for which you want to use the Rules module), just create some custom rule to do so. The most straight forward Rules Action to use for this, seems to be "Send an eMail to all users of a selected role", whereas role is just authenticated users.

If however you want more granularity in the set of users to be selected, you could use the Views Rules module instead. for more details on such approach, refer to the Plan b part of my answer to "What's wrong in my rule for sending e-mails using VBO?".


add html to fieldset I try to customize fieldset ABC that are inside drupal commerce checkout page.
Markup looks like this

<fieldset>
 <legend>ABC</legend>

</fieldset>

I would like to put some additional code directly inside fieldset and then also some other html directly inside form-item elements.
Question> What should I do to achieve that? I found this page https://api.drupal.org/api/drupal/includes!form.inc/function/theme_fieldset/7 would it be of any help? Thank you.

images

Try to change it using hook_form_FORM_ID_alter().

// Replace FORM_ID with commerce checkout form id
function hook_form_FORM_ID_alter($form, &$form_state, $form_id) {
  $form['fieldset_item']['mymarkup'] = array(
    '#type' => 'item',
    '#markup' => 'My Markup Here.',
  );
}


Is displaying a working Field Widget Form on its own possible? I'm interested in embedding a Field Widget Form out side the context of the whole node edit form.

I have displayed full forms in the past using drupal_get_form but that doesn't seem to apply for solitary Field Forms.

Is displaying a working Field Widget Form possible? What would be the best way to do so?

Both field widgets and "normal" forms seem very alike, so if this is not possible, what would be required to "change" a widget form into a normal form?

This question appears to be asking for something similar but I don't understand the answer.  That answer specifies using hook_field_widget_form_alter; what I don't understand is how to get the Field Form to be displayed not how to hook it once it is being created.

VBO does something like this in modify.action.inc:

$form_key = 'bundle_' . $bundle_name;
$form[$form_key] = array(
  '#type' => 'fieldset',
  '#title' => $label,
  '#parents' => array($form_key),
);
field_attach_form($context['entity_type'], $entity, $form[$form_key], $form_state, LANGUAGE_NONE);

So, you need the entity type, the entity (which can be a blank object with just the bundle key set, that's what's actually used), the form where the widgets are added, and the language.
If you want to embed the widgets deeper into the form (not in $form, but in $form[$form_key] as I did, or even deeper), then that form array needs to have #parents set.

Of course, notice that this will embed the widgets of all fields belonging to that entity type & bundle. This is how the attach functions were written.
Going around that would require you to reinvent quite a lot of code; see the actual code that does the heavy lifting.
What I do is go through field instances, get each $field_name, and if that field type doesn't interest me, I set $form[$form_key][$field_name]['#access'] = FALSE;
which hides those widgets from sight.

EDIT: Okay, ctools has ctools_field_invoke_field() which could in theory allow you to work on a per-field basis. I've never used it though. The text above is my direct experience.


How to remove stylesheets only for anonymous users? I am trying to remove all unnecessary/unused stylesheets for anonymous visitors to get better performance and a clean <head> section. This works fine by listing them inside mytheme.info.yml:
stylesheets-remove:
  - path/to/stylesheet.css
  - path/to/another/stylesheet.css
  - core/modules/system/css/components/hidden.module.css

However, the third entry in this example breaks the styling of the toolbar - which is only visible to the admin. Is it possible to programatically tell Drupal which stylesheets to remove only for anonymous visitors? I appreciate your help!

Having tried to do this myself before, this is probably not a route you want to go down.  This approach becomes harder to maintain as you install more modules (different modules can inject CSS on different paths), and often can turn into a maintenance nightmare.
Drupal can aggregate CSS files out of the box; this is often all you need to improve performance dramatically.
To turn on the basic aggregation, you can check Aggregate CSS files at /admin/config/development/performance.
To do something more complicated, try using the Advagg module. Configuring this module can be complex but it allows you to do more specific aggregation, CSS minification, and so on.


How to add css classes to modal forms module My Problem

I'm trying add CSS classes to help me style the modal forms created using the Modal Forms module.

I have a User Login and a User Register form at the moment, but they have no form specific CSS classes.

Example 1

To style the height of the input boxes:

I either have to use "form-text" in <input> which will edit all form inputs across all forms or "edit-name" which will become "edit-name--1" if the user fails to login and the break the css.

    <input id="edit-name" class="form-text required"
    type="text" maxlength="60" size="25" value="" name="name">

Example 2

To alter the labels "username & password" the only tag I can work with is edit-pass

    ...

Which will change edit-pass--x every time they fail to complete the form correctly, resetting the css.

How would I insert CSS classes using hook form alter?

What I've tried

I printed out the array for the user login form (using print_r, can't use dpm because have to be logged in and user login won't work if you're logged in), here's the first chunk of it.

Array ( [name] => Array ( [#type] => textfield
                          [#title] => Username
                          [#size] => 25
                          [#maxlength] => 60
                          [#required] => 1
                          [#description] => Enter your drupaltest2 username. )

        [pass] => Array ( [#type] => password
                          [#title] => Password
                          [#description] => Enter the password that accompanies your username.
                          [#required] => 1 [#size] => 25 )

        [#validate] => Array ( [0] => user_login_name_validate
                               [1] => user_login_authenticate_validate
                               [2] => user_login_final_validate )

        [actions] => Array ( [#type] => actions
                             [submit] => Array ( [#type] => submit
                                                 [#value] => Log in ) )

I tried inserting

[#class] => 'TEST';

into [name] and other slight variations but none of them work.  I can give more examples if I've explained this badly.

EDIT -- RajeevK Solution -- Not enough granularity

I added the following lines into my alter form:

Name array:

$form['name'][#prefix] = '
';
$form['name'][#sufix] = '
';

Pass array:

$form['name'][#prefix] = '
';
$form['name'][#sufix] = '
';

And the end results looks like this:

This is what the page looks like (I'm using firebug to show what the div contains).

Or if I select CAPTAINTEST it looks like:

Hopefully this will help some though and cheers to RajeevK for the suggestion. I was hoping to control individual elements of the forms, does anyone know whether it would be possible to get more granularity without having to hack the module?

(Here's my form alter:

function mytheme_form_user_login_alter(&$form, &$form_state, $form_id) {
  //override to change text in user sign in box
  drupal_set_title('');
  $form['name']['#title'] = 'Username/Email';
  $form['name']['#description'] = '';
  $form['name']['#prefix'] = '
';
  $form['name']['#sufix'] = '
';
  $form['pass']['#description'] = '';
  $form['pass']['#prefix'] = '
';
  $form['pass']['#sufix'] = '
';
  $form['actions']['submit']['#value'] = 'Sign In.';

You can use #attributes to add some classes to the elements:

$form['name']['#attributes'] = array('class' => array('your-class'));

Will output something like this (class added to input element):

  Username *
  <input type="text" maxlength="60" size="60" value="" name="name" id="edit-name" class="your-class form-text required">
  ...


How to remove "pending update"? I updated a module, ran update.php, made some edits and backed up it's table for migration. And then HDD on server failed. Admins restored it from nightly backup, and from my backup as well (both was in proper backup directory). So I had new table structure and data, but old files. I uploaded module's files and it all works, but it shows I have one pending update. Update that is bound to fail as columns it's supposed to rename are already renamed.

Is there an easy way to tell Drupal manually "it's done already, don't try to run this update"?

I've never done this before so I'm not sure if this will work but I assume you can manually update the schema_version column in the {system} table to the highest hook_update_N number. For example if there's mymodule_update_7101 in the .install file of mymodule then update the schema_version column of the system table for mymodule to 7101.

I don't get it though, how come if you have updated fields in the module table of same database, how is it that the system table is older?


The correct way to include jquery in a module's form I'm trying to use jquery in a form of mine that is rendered via the form api.

How i'm getting jquery to work now is like so

$form['raf_raffle_name'] = array(
    '#type' => "textfield",
    "#prefix" => "
Raffle information

",
    "#title" => "Raffle Name:",
    "#required" => TRUE,
    "#attached" => array(
        'js' => array(
            "$path/jquery.js", "$path/test1.js"
        ),
    )
);

well it works, but i'm not sure if its the right way. Is there a better way? I'm inclined to ask after i saw the 'library' attribute which is supposed to load up certain javascript plugins.

You should not have to manually include jQuery:

"When JavaScript is added to a page through Drupal, jQuery is automatically added to the page."

-- https://www.drupal.org/node/171213


Get all users with edit/view permission for a node I'm working on a Drupal 7 project. And for this I need to get all the users that have a certain permission for a node. I need this info in the hook_node_update method, which means that I can currently get the $node object just fine but I'm unable to find a way to query a list of users that have edit rights to the particular node that's being updated.

Can anyone provide an insight? That would be great!

Thanks.

Every content type has fix pattern of permission

For node edit permission, Just use user_access() with string parameter
"edit own [content-type] content"
OR
"edit any [content-type] content"
If current user has this permission it return TRUE else FALSE

AND

If you want this permission for other user, Just pass user object as second argument in user_access()


Trying to override Drupal core 'find content' with a view and VBO I am trying to replace the core content admin area with a view and VBO. I managed to create the view and have it override admin/content/node without an issue. However the administer content area is also accessible by admin/content. I tried creating a second view to override it but it breaks the menu. It appears to be a menu router issue. Any thoughts on how to overcome this (other than adding a redirect)?

Views doesn't really know how to override paths. It always breaks menus.
You need the Admin Views module that provides some extra code for overriding to work.


How to set up drush on Cloudways / Digital Ocean? I have been experimenting with Cloudways and Digital Ocean as a hosting solution.

I am attempting to set up Drush and have been following some instructions provided by GoDaddy.

The notes appear up to date and well written - See https://uk.godaddy.com/help/how-to-install-drush-on-cpanel-shared-hosting-12396 . I am not using cPanel but I do not think this should matter.

When entering

echo "alias drush='~/drush/drush'" >> .bashrc

The system returns

echo "alias drush='~/drush/drush'" >> .bashrc
bash: .bashrc: Permission denied

The same also happens with sudo

After continuing with rest of the instructions Drush is now installed but does not seem to be available for the public_html directory. I'm guessing that the GoDaddy instructions are missing a step or are not quite compatible with this environment.

I have provided an example of a Features download (below) and as can be seen, the download is being placed in the drush directory and not sites/all/modules

[master_vkhgjqkyfv]:public_html$ drush dl features
Project features (7.x-2.8) downloaded to /home/master/.drush/features.

Can anybody say what I need to do to get this working properley?

I'd recommend trying the official Drush installation instructions.  Note that the first recommended installation method is to download the phar, which you might find easier to get working than the Composer-based instructions.

The GoDaddy instructions (at the time of this writing) recommend installing the latest unstable version of Drush. This is not recommended unless you are planning on frequently updating Drush, in which case you are better off installing via git rather than downloading an archive.


Site with Themekey has CSS cross-contamination I'm using Themekey with Context to enable one of three different themes on a site, depending on a themekey field. The homepage is set to use my main theme, called 'sitetheme'. Sitetheme is set as default, but many themes are enabled.

All the pages that I've tested look good, including the homepage. There's just one exception. My main menu, a horizontal header region menu block that uses Nice Menus to create dropdowns, has weird styling on it. When I inspect the element, I see that it has styling applied from a CSS file that lives in a different theme than the one that is enabled on the front page.

The front page is also of a nodetype that doesn't have the themekey field that some of the nodetypes have, that can be used to override the theme.

Why is my foo theme's CSS for Nice Menus getting applied on pages that use Sitetheme?

I think Nice menus apply to all themes unless you have specified other.

Just go to the following location admin/appearance/settings/your_theme_A.
Then look for "Path to custom Nice menus CSS file"

Then go to your next theme admin/appearance/settings/your_theme_B
And also check "Path to custom Nice menus CSS file"

You might surprise, Nice menu use common CSS file regardless of your theme unless you have changed.


Adding a css file to a custom theme I'm a very beginner in drupal and I just want to add a css file to my custom theme.

So I created a upjv.libraries.yml in themes/upjv and I added :

global-styling:
version: '8.4.4'
css:
   theme:
       css/styles-upjv.css: {}

And I have created a styles-upjv.css in themes/upjv/css. On my index page, my file isn't loaded and I don't know if it's because I created the file in a wrong place, if the content of my libraries.yml is correct. Can anyone help me on this little problem please ?

You have to add the following in your upjv.info.yml:

libraries:
  - upjv/global-styling

Make sure to clear cache after that by navigating to configuration > Development > Performance then clicking on Clear all caches under CLEAR CACHE.


Where drush make downloading my projects? I have created a drush make file through drushmake.me

Which is, I've created a file my.make in public_html folder and run the following command:

drush make my.make

It shows all the files downloading ok, but when I am checking my public_html folder it's showing nothing in my public_html.

I don't understand where all the projects are downloaded.

Any idea?

Normally drush makes default behaviour is to create the site in the current directory - relative to where you run the command.

But the simplest way to deal with this is just to run drush-make with a parameter explicitly stating where to deploy the site:

drush make my.make relative/path/to/my/public_html

or

drush make my.make /absolute/path/to/my/public_html

Obviously replacing the path in question with the appropriate one. Don't understand UNIX file paths? Read up on them on wiki page.

And while I am at it, why don't you take a look at the drush make documentation too.

There are a number of drush configuration files that affect the working directory for drush commands - the most likely candidate being a drushrc file is example.drushrc.php.


How do I secure pages and related media files? I would like to password protect Drupal pages (solved) and media files related to these pages (solved, but not optimally).  Currently the Drupal pages are secured via Drupal and the media files via htaccess.  The problem with this is the users then have to authenticate twice to get to the media content.  I've been told that the way to solve this is to create a role and restrict access to both Drupal pages and media using Private files download permission module.

I'm quite new to Drupal and am wondering if this is the normal way that people solve this problem; or is another method better/more common/etc..

Try to use Secure Site for this.

  This module allows you to authenticate users with a browser-based password (HTTP Auth). You can restrict access to the site by role and choose to secure restricted pages or the entire site. This means the site will be inaccessible to search engines and other crawlers, but you can still allow access to certain users.


Menu Link not translating correctly on initial creation through node form Using Entity Translation and Entity Translation Menu

On the node form, there is a section called "Menu Settings" then "Provide a menu link".

1) Create a new node, click "Provide a menu link" and put in your English menu item title.
2) Translate the node, click "Provide a menu link" and put in your French menu item title.
3) The menu item displays the french menu item title no matter which language you are viewing the site in.

The menu item's title that you created during the English version is overridden with the French menu item title. In fact, when you edit the menu item through the /admin/structure/menu interface, there is only one translation, the default. All we did was
override the default translation with the french translation.

After a while I figured out how to get around this.

1) Create a new node, click "Provide a menu link" and put in your English Title.
2) Go to /admin/structure/menu/manage/main-menu, move your new menu item up or down, and click "Save Configuration". This properly sets the properties of the menu item.
3) Translate the node, click "Provide a menu link" and put in your French Title.
4) It works!

But obviously, we can't have our administrators jumping through the extra hoop. If someone can tell me if there is already a fix on this issue or if there is a hack I can do which re-saves the menu-item after it's created, please let me know

I created a hook to set customized=1 which allowed the menu item to be translatable without editing it directly.

function epc_menu_insert_menu_link_insert($link){
    $link2 = menu_link_load($link['mlid']);
    $link2['customized'] = 1;
    menu_link_save($link2);
}


Configure Australian GST Taxes on Commerce Kickstart 7.x-2.14 I would like step-by-step instructions as to how to configure Australian GST Tax on a Commerce Kickstart site, if possible using configuration only.

The business rules are:

Primary Objevctives

Australian GST tax is 10%.
It has to be included in the quoted price. So an item that is quoted as $11 would contain $1 of GST.
The amount of contained GST has to be displayed as a separate item in the bill.
It is only applied to orders being sent to an Australian shipping address. This includes the shipping cost itself, which is GST-free for orders going overseas.
There can be GST-free items, which don't incur GST whether they are sent overseas or not.

Secondary Objectives

Related to the third item above, technically one is not meant to show separate "(tax-free) Subtotal" and "Included GST" rows but for the time being I'm willing to ignore this legal requirement.
Somewhat related, instead of just removing the GST for overseas orders I would prefer to still show the contained GST amount but have the line item as something like "GST (removed)" and then not have it included in the calculation. My gut feeling is that these two secondary objectives are related.
There seems to be an issue that sometimes crops up if I'm testing within the one browser and it remembers my previous shipping address, so that when I change to an overseas shipping address between orders it doesn't update as I would have expected. Might be a bug in Commerce though, and I'm expecting this to be an edge case.

My basic strategy so far has been:

Do a clean install of the latest Commerce Kickstart via Aquia Desktop
Write out a strategy of how I'm going to implement the tax
Implement using a combination of things based on Randy Fay's Conditional Tax video, commerce_australia module, various other patches/tax removal modules/etc that are buried in drupal.org
tweak until I realise that I'm no closer. Pull out hair. Take a walk and try to come up with another strategy. Rinse and repeat.

Also, is anyone able to give me a clear answer to what the difference is between how the tax is applied in Rules as opposed to if I access it from Taxes-->Configure Components?

Apologies for the long post but I'm honestly at my wits end here. I can give more information on what I have tried so far but I'm worried I may pollute the responses.

Here is a module maybe is useful.

  The Commerce Australia module provides a number of customisations for
  Drupal Commerce (http://drupal.org/project/commerce) that allow it to
  be better suited for deployment in Australia.

  Most notably, these include basic currency formatting for Australia
  and workable GST (Goods and Services Tax) rules.

https://www.drupal.org/project/commerce_australia


How to add javascript with #attached in a node which contains a specific paragraph bundle I need to attach js in all nodes with a specif paragraph bundle. I know how to do this with drupal_add_js, but I prefer don't use it to prevent cache problems.

I am trying with hook preprocess_entity but I don't get it, I don't know how to use the ["#attached"]

function THEME_preprocess_entity(&$variables) {
  if (isset($variables['paragraphs_item']->bundle) && variables['paragraphs_item']->bundle == "XXXXX") {
   $variables["elements"]["#attached"]['js'][] = array(
                'type' => 'file',
                'data' => 'myfile.js',
              );
      }
    }

What am I doing wrong?

Try this code for attaching

$variables['#attached']['js'][] = 'myfile.js';

Or

$variables['#attached']['library'][] = 'myfile.js';


How can I add text into ckeditor textarea in drupal 7? I'm using ckeditor-7.2 version. How can I set the values to my ckeditor text area from out side.

Assuming you want to set some value at the beginning -

Get the id of the form. https://www.drupal.org/project/get_form_id

Get the id of the field you want to alter.

Make a small custom module, with hook_form_alter() and set #default_value to that :

function YOURCUSTOMMODULENAME_form_alter(&$form, &$form_state, $form_id) {
  if ( YOUR_FORM_ID == $form_id) {
    $form['YOUR_FORM_ID']['YOUR_FIELD_ID']['#default_value'] = 'some default text'
  }
}

For adding some text after taht that, use jQuery.

$('#input-field-id').val('some text');


Can use Webform for add combobox for select language on the site? I want to know how I can add a combobox to a page. For example, on the front page, I want to add a combobox for selecting the language. I use the default modules for creating multilingual sites. Languages are displayed as a list on the page. I want to display a combobox instead of the extended list.
Can I do this with the Webform module?

No, you can't do this with webform. Webform's purpose is to collect and store user submitted data.
You can create a language dropdown by creating an override template for links--language-block.html.twig in your custom theme.