Deleting the "Page title" module in an existing site that needs some module-removal (Will damage SEO?) A drupal 7 site owner asked me to clean all unnecessary modules in her site. After I've successfully updated all modules and DB, I went to start delete some modules.

I've deleted unused modules until I came across Page title, the well known module from the Drupal 6 era, which it's functionality now a part of the Metatag module. I wonder if deleting it will destroy the page titles that have already been added to the site's nodes... What is the technical truth?

Page Title stores its titles in a DB table, which will be deleted (along with all its data) if you uninstall the module. It uses an HTML preprocess hook to load that data from the DB on a page-by-page basis, and replaces whatever would normally be the title for that page right at the last minute.

So...

  I wonder if deleting it will destroy the page titles that have already been added to the site's nodes

Is entirely accurate. If you remove the module, you'll also remove the page titles that were added using it, and Drupal will use whatever default title was applicable for the entity before you installed it in the first place (e.g. for nodes that'll be whatever is in the title property).


Unable to add custom validation rules using client side validation module in Drupal 7 First I want to clarify that I am new to Drupal. So please excuse me If my question is naive.

I have installed the Client Side module in Drupal and it is working fine for all the required fields. I have built a custom form using Drupal form API. Now I want to add some custom rules to some of the fields on the from. I have searched on the internet and found this https://drupal.org/project/fapi_validation and below is the code that I have implemented but this is not working. I think there is some thing that I am missing here.
The module name is instructor_registration and I have written this code in instructor_registration.module file.

function instructor_registration_fapi_validation_rules() {

return array(
    'select_required' => array(
        'callback' => 'validation_rule_select_required',
        'error_msg' => 'Please select %field',
    ),
);
}

function validation_rule_select_required($value) {
if ($value == '0') {
    return FALSE;
}
else {
    return TRUE;
}
}

In the form element I am calling this as :

'#rules' => array('select_required'),

If there is any other information required from my side then please let me know.

Finally found the solution. Actually the code that I was writing was not complete. The examples for adding custom rules in client side validation can found at https://drupal.org/node/1324772 . Hope this helps some one.

Cheers!!!


how to make config fields stick at admin/structure/types/manage/? I am adding a config option to all content types. I have textfield and checkbox now.

How to SAVE what I write in the textfield and state of checkbox when I hit submit?? Do I need to alter submit function for this form?

function neil_misc_form_node_type_form_alter(&$form, $form_state) {
  global $user;
  if (isset($form['type'])) {
    $form['followbtn'] = array(
      '#type' => 'fieldset',
      '#title' => t('Follow Button settings'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
      '#group' => 'additional_settings',
    );

$form['followbtn']['comment'] = array(
  '#type' => 'textfield',
  '#title' => t('Email address to send updates to'),
  '#default_value' => $user->mail,
);

$form['followbtn']['followbtn_default_mode'] = array(
  '#type' => 'checkbox',
  '#title' => t('Add Follow button to this Node Type?'),
  '#default_value' => variable_get('comment_default_mode_' . $form['#node_type']->type, ADD_FOLLOWBTN),
);
  }
}

You can add a custom submit handler for your custom group of options and controls. For example on the base form you add an additional #submit value and check your own custom fields:

$form['#submit'][] = array('mymodule_form_followbtn_custom_submit');

if needed you can validate is form element independantley:

$form['followbtn']['followbtn_default_mode']['#element_validate'] = 'mymodule_followbtn_element_validate_default_mode';

or ...

$form['followbtn']['comment'] = 'mymodule_followbtn)element_validate_comment';

Then your submit function just does your processing (after elements validate on submission:

function mymodule_form_followbtn_custom_submit($form, &$form_state) {
  // save your stuff ...
}


One Content Type - 2 Different Displays I have a content type that I want to have certain fields show up for different users. For instance, for admin, I'd like the users to see all of the fields available, however, for non admins, I'd like to have one certain fields displayed. Is this possible?

Field visibility & access can be controlled with the Field Permissions module.


Convert Field Collections into Paragraphs during Migration I have a content type that uses Field Collections in Drupal 7. I am migrating to Drupal 8. Is there a way to convert the Field Collection Entity into Paragraph during migration?

As more sites migrate from D7 to D8, this is definitely a needed functionality. I see that there is now a patch for Paragraphs that is attempting to address that: https://www.drupal.org/node/2911241

If you can test and/or contribute, we can get this moving along!


View with Page display won't show menu tab for an alias I want to add a few views (members and challenges) to a specific content type called group. I don't want the views to display all on the same page, this is easily done with the block display type. But I want to have menu tabs at the page, this is also easily done (/node/%/members) if you only use one content type. But I'm using multiple content types what than also will have the Members tab.

Basically I'm asking how to manage the visibility of a menu tab.

This is what I tried so far for the view Group Members (User):

Path: /group/%/members
Menu: Tab: Members

nothing showed up..

This is what I tried so far for the view Group specific Challenges (Content):

Path: /node/%/challenges
Menu: Tab: Challenges

It showed up on every node.

Create your views as follows:

Challenges -

path: node/%/challenges

tab: menu tab with title Challenges

filter criteria: type = group

Contextual filter: nid, and in section WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED specify validation criteria: Validator Content, Content types group

Members-

path: node/%/members

tab: menu tab with title Members

filter criteria: you con't need any as you are displaying users (you have a view of users)

relationship: add a relationship to the node table such as: User: Content authored. This will bring in the related nodes.

Contextual filter: nid, in the section rlationships nodes must be selected. Specify validation criteria as Validator Content, Content types group

And these two tabs will now show up only for node type group. If you need it on other content types as well then adjust your views filter criteria and contextual filter validation as required.


Recover from a Lost Drupal Administration Menu When I log into the Admin on my site, the drupal controls are all missing.  Our former Web Developers refered me to an article online that told me I need to enable the toolbars by:

What you need to do is access the main "Modules" page. The best way to get there is by typing in the URL of the modules page.

Try adding one of these to your main domain name:
•/admin/modules/
•?q=admin/modules

Neither of these worked. With /admin/modules/ I get "Page Not Found".

With ?q=admin/modules I get "Access Denied"

How can I get the drupal controls back so I can make edits?

Open below URL and change settings

admin/people/permissions

Or else you can edit here roles & permissions

admin/people/permissions/roles


Hiding a block based on code I'm looking for the best way to programmatically hide a block. In Drupal 6 I'd normally use preprocess_block to do all my logic and then unset title and content/body from there. I've tried to do same thing in Drupal 7 but failed. What's the correct way of doing this? I'd like to avoid editing the settings through the UI as this change has to be deployed in code rather than database.

The best (IMHO) way is to implement hook_block_list_alter() in a custom module and unset specific blocks when you need to. Advantages are:

No PHP code in your database, so your alterations can be managed in a version control system
No hacking in the theme layer, so the alterations will remain when you switch themes
Better performance because the block is removed from the list before it is rendered

Drupal core also uses this hook to hide blocks: block.module itself implements hook_block_list_alter to apply the default block visibility settings.


Rules token one-time-login-url is showing up empty I have a rule that, after submitting a webform, a user gets created and then sends two emails to that user.  One saying their form data is being looked at by someone for review before they get a certain role, and another that gives them the one-time login url.  The problem is the that, while the rule works and both emails get sent, the login url is not displayed in the second email.

{ "rules_application_submission_affiliate" : {
    "LABEL" : "Application submission: Affiliate",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "webform_rules", "php" ],
    "ON" : { "webform_rules_submit" : [] },
    "IF" : [
      { "webform_has_id" : {
          "form_id" : "[form-id:value]",
          "selected_webform" : { "value" : { "webform-client-form-101" : "webform-client-form-101" } }
        }
      }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "user",
            "param_name" : "\u003C?php echo $data[\u0027components\u0027][\u0027your_username\u0027][\u0027value\u0027][0]; ?\u003E",
            "param_mail" : "\u003C?php echo $data[\u0027components\u0027][\u0027your_e_mail\u0027][\u0027value\u0027][0]; ?\u003E"
          },
          "PROVIDE" : { "entity_created" : { "new_user" : "New user" } }
        }
      },
      { "entity_save" : { "data" : [ "new-user" ] } },
      { "user_unblock" : { "account" : [ "new-user" ] } },
      { "mail" : {
          "to" : "[data:your_e_mail-value]",
          "subject" : "Thank you for your application!",
          "message" : "Your application is being processed.  You will receive another email when your account is ready for activation.",
          "language" : [ "" ]
        }
      },
      { "mail" : {
          "to" : "[new-user:mail]",
          "subject" : "Your account is ready!",
          "message" : "You may activate your account by going to this link to set your password:\r\n[new-user:one-time-login-url]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

The problem was on the "save entity" action, I had to force it to save by checking "force" on the action, because the entity would only get saved after the other actions had been applied.


Alter menu title or add menu item programmatically? I want to create link to user from the menu created by UI. I tried with hook_menu but the link is 'user', but it doesn't work, because don't want to create new page. I would like to alter title or add menu item programmicaly to use First name in the the menu title.

What i know is the 'mlid' = '3228' and menu name is 'menu-user-links-top'

PS. I also tried with hook_menu_link_alter but it doesn't work, for all users (the first name appears after pressing edit menu and uses only admin's first name).

For example, if I take the User-Menu in bartik theme, and I want to change the My Account menu-title with Username, So whenever, the user logged in, instead of My Account that menu-item shown the Username.

Image-1: Default menu-item

Image-2: After the code

function YOURTHEMENAME_translated_menu_link_alter(&$item, $map) {
    global $user;
    if ($item['href'] == 'user') {
      $item['title'] = t($user->name);
    }
}

Now, same way as shown in the above code, you can change the apply the href of any particular menu-item and there it will show the user-name instead of the menu-title.

I am not sure are you looking for this or other, but this is the straight code to change the men-item with username.


Twig: Display media library reference user image at particular resolution with alt tag (on /user/1231 page) On our user page (/user/12345) we want to change the profile image field to be a media library reference field instead.  I've created for the user object a new field called field_profile_image that is an entity reference/media library reference.
In my twig template for this user page I can display the full rendered user image in the default display mode with a bunch of extraneous information by using {{ content.field_profile_image }}
What I would like to do is display just the image at 136x156 (a media display mode I've set up), preferably with an alt tag.
I've tried various solutions with or without twig tweak, and am still having trouble showing just the referenced image with an alt tag.
Note that I see a lot of examples for twig tweak have something like
{% set media_uri = node.field_media|file_uri %}
{% if media_uri is not null %}
{{ media_uri|image_style('thumbnail') }}
{% endif %}
but node is null since this is not on a node, and replacing node.field_media with content.field_profile_image in the above script doesn't render anything at all.
How can I display a media library image in a particular display mode preferably with alt tag?

but node is null since this is not on a node

In user template there is {{ user }} variable wich holds user entity. So just replace "node" with "user" in your snippets.


Render Image on Controller I have a controller that renders page elements. I have a php variable of type png image. What is the proper way to render it?

My code:

public function buildPage() {

    $page = [];

    $block_manager = \Drupal::service('plugin.manager.block');
    $config = [];
    $plugin_block = $block_manager->createInstance('my_custom_block', $config);

    $page['element_one'] = $plugin_block->build();

    $page['element_two'] = array(
      '#type' => 'markup',
      '#markup' => $this->t('This is the second page element'),
    );

    //How to render this on a third page element?
    $image = 'test.png'

    return $page;
  }

Thank you

You can add the element using the image theme hook:

$page['element_three'] = [
  '#theme' => 'image',
  '#uri' => $image_path,
  '#alt' => $title,
  '#title' => $title,
  '#width' => $width,
  '#height' => $height,
];


Theme file upload form element I want to theme all the file upload fields on my site but I don't know how to name the template file.

I want to alter the form-element.html.twig file but as I have multiple file fields I don't think that the best way is to create theme files for each field. So I was thinking to create a theme based on the field type. Is that possible?

I used the hook_theme_suggestions_input_alter.

function MY_MODULE_theme_suggestions_input_alter(&$suggestions, array $variables) {
  $element = $variables['element'];
  if (strcmp($element['#type'],'file') == 0) {
    $suggestions[] = 'form-element--file';
  }
}

After clearing the caches seems that doesn't work.

Is this the correct way or is there any other way?

As suggested by Ivan Jaros, you can override input--file.html.twig if you want to use twig templates. Basic input template is as follow:

{#
/**
 * @file
 * Theme override for an 'input' #type form element.
 *
 * Available variables:
 * - attributes: A list of HTML attributes for the input element.
 * - children: Optional additional rendered elements.
 *
 * @see template_preprocess_input()
 */
#}
<input{{ attributes }} />{{ children }}

If you need to add more dynamic variables, you can use template_preprocess_input() preprocess function.

Also, you can use debug: true under twig.config in services.yml. This will help for theme-related development.

Note: Drupal provides default classes that are from generic to specific to the field. If generic classes helps to theme, I would suggest to avoid all the above.


Facebook Oauth field collection I have Facebook Oauth set up to receive a few fields.  They are mapped in the Configuration -> Facebook OAuth settings -> Field Mapping to fields I added to the account object.

When a facebook user tries to connect, they are prompted for permissions on these fields, and the user accepts.  However, the fields are not being captured to the fields they are mapped to.

Ideas??

It looks like I had my profile2 fields mixed up with my account fields.


adding new field to imceimage I have imceimage.module,v 1.1.2.4. the default of this module is to create a table for the field i want to create as below:

desc content_field_slideshow_image;
+-----------------------------------------+------------------+------+-----+---------+-------+
| Field                                   | Type             | Null | Key | Default | Extra |
+-----------------------------------------+------------------+------+-----+---------+-------+
| vid                                     | int(10) unsigned | NO   | PRI | 0       |       |
| nid                                     | int(10) unsigned | NO   | MUL | 0       |       |
| delta                                   | int(10) unsigned | NO   | PRI | 0       |       |
| field_slideshow_image_imceimage_path    | char(255)        | YES  |     |         |       |
| field_slideshow_image_imceimage_width   | int(11)          | NO   |     | 0       |       |
| field_slideshow_image_imceimage_height  | int(11)          | NO   |     | 0       |       |
| field_slideshow_image_imceimage_alt     | text             | YES  |     | NULL    |       |

and i want to add new field for seo_alt

| field_slideshow_image_imceimage_seo_alt | varchar(255)     | YES  |     | NULL    |       |

I have doen this:
1- i have altered the table  alter table content_field_slideshow_image add  field_slideshow_image_imceimage_seo_alt varchar(255);
2- added 'imceimage_seo_alt' => array('type' => 'varchar', 'length' => 255)); in imceimage_field_settings hook
3-changed #columns in imceimage_elements hook to be  '#columns' => array('imceimage_path','imceimage_width','imceimage_height','imceimage_alt','imceimage_seo_alt'),
4- added $element['#value']['imceimage_seo_alt'],  to $element['imce_view'] in imceimage_process hook
but now when i edit a slideshow and add the imceimage_seo_alt, it wouldn't be saved in the database :(... what shall i do to add this customized field??
Thanks for your help

You have taken the wrong approach. It's not as simple thing to do as you would like.

What's needed depends on your Drupal version 6 or 7. The columns in the table for the field is created though the field definition that defines which columns are needed. It's not possible to alter this without hacking the module that provides the field. This is not the approach you want to take.

Instead you need to create your own version of the field definition. You should be able to copy most of the code and alter the bits needed for the table definition. Only field or cck knows that the table contains the column for SEO it will also save and load values for that column. If you are not familiar with CCK/Fields it might take a little while to get things working. Also a down side is that you most likely will create your own version of the image field that you will have to maintain.

An alternate solution is to not store the values in the field table, but create your own table and handle saving and loading the data yourself. If you don't need integration with Views, this would probably end up as a cleaner solution.


Check if a panel page is enabled programmatically? I need to be able to verify if a panel page (which is just a variant of a ctools page) is enabled or disabled.  How would one do this, programmatically?  If it is disabled, how would one enable it, programmatically?

You can use

panels_load_display

Then check the disabled flag for page status.


Contextual Filters via Taxonomy I am in the process of creating a View for my Drupal site and I am attempting to add a contextual filter by Taxonomy so I've added the Content: Has Taxonomy term ID (with depth) filter and selected the Specify validation criteria option and selected the Taxonomy that I wanted to work with. I also used the filter value type of Term name converted to term ID yet when I attempt to preview the filtered elements, I get the no results behavior. What should I be typing to call the filtered elements correctly?

Atm, to provide a concrete example, I have tried my_view/mississippi-river to call all nodes tagged with the Mississippi River taxonomy term via hierarchical select. Again, this leads me to the no results behavior. Additionally, how would I call a child of the Mississippi River Taxonomy term? Any ideas?

Contextual filters are just the term. So in the contextual filter input box for the Views Admin you would put mississippi-river as an example. In addition to Term name converted to Term ID you want to be sure you check the box for convert spaces to dashes further down in the specify validation criteria or else "mississippi-river" will not be found because it's expecting a space and you're providing a dash.

For the parent/child filters you're trying to achieve look at Taxonomy Edge. The -dev release contains some contextual filters for "parents" and "children" of stuff.


Mass image upload with Storage API and Services API I am trying to set up a site that will be storing a large amount of images (roughly 50,000 to start with). The strategy for this was to use Storage API and S3 storage to deal with the costs of hosting, and Services API to provide an interface for a offline converter/uploader to get the images to the site.

This is working pretty good. If I upload an image manually by creating a node and filling in the image field, it gets sent to Storage API and good things happen. I can also upload files and create nodes from the offline uploader via the XMLRPC Services API.

The problem is that the files uploaded with the offline uploader don't get handled by Storage API. Currently the script uses the Services API method 'file.create' to create and object, then the details returned are used to fill in the image field on the node that is created next. I expect there is a better way to do this, but I am not sure.

Still in early dev, but checkout  Storage API Populate:

  Storage API Populate provides a mechanism to move existing files
  within file/images fields into storage. The module requires the
  Storage API module.

  For a scenario where you have an existing site, without any Cloud/CDN
  support for assets and would like to use Storage API to manage the
  storage and serving of files.


Creating a List View and Thumbnail view in Drupal 7 view I created a view but I am hoping to create two possible viewings of it.

Basically, it's showing it in either List View or Thumbnail View. Now, one option would be to create two views and showing one of them by default and hiding the other; hence toggling each when the button is pressed. But I was hoping to find some more efficient less resource intensive solution.

Thumbnail view

List view

Thanks.

You could create one view with 2 pages or blocks depending on how you are setting up your view. Then have one show list view and the other show thumbnail view. You could then use tabs to switch between the 2 views.


Pass value into a view using block input I have created a Drupal 9 site with articles that belongs to taxonomy terms. I want to give the ability to the administrator of the site to place a block with whatever taxonomy he wants.
How would I set up the block configuration with a drop-down of the taxonomy terms and pass the selected values to the Drupal views and filter based on the selected taxonomy terms?
In the block settings there is not any option to pass the filter to the block.

Any Idea on this using existing module or with custom code?

Not answering directly, because I don't know if you could do this with a configurable Views block without custom code.
A different approach only using UI would be on entity level, creating a block type containing two fields, the taxonomy drop-down and an EVA field passing the other field's value via a token. The site admin has then to use the Custom Block Library to create a custom block for this block type.
Add the EVA field to the block type with this module: https://www.drupal.org/project/eva


Using video module with ffmpeg to convert; how do I display converted files? All uploaded videos on our Drupal 7 site need to be in a standard web format: MP4-H.264/AAC to assure play back by all user devices.

ffmpeg is working correctly. Video upload field stores all uploaded files into sites/default/files/videos/originals.

ffmpeg saves converted files into sites/default/files/videos/converted/nnnn which is a directory containing the converted file, and nnnn is a number unique for each file.

On the web page, the original uploaded file is displayed. How can I switch to the converted ("transcoded") file?

Video module supports Rules integration. Is that a good solution?

Production and QA sites are hosted on AWS.

Solved this by modifying the custom module. Test if file has been converted, by looking in sites/default/files/videos/converted/nnnn, where nnnn is the File ID of the original file. If not then display the original video file. If conversion completed successfully, then display the converted file from sites/default/files/videos/converted/nnnn. There is only one file in the nnnn directory.


Site index removes "www" from url and files (e.g., '/about') don't work with "www." I have a peculiar problem in that people visit any other page other than the homepage with the "www." before the url they will receive an error.

If they visit the index with the "www." it is removed and whatever links they click will work as it doesn't have the "www." in front.

http://www.domain.com/        - will change to http://domain.com and work fine
http://www.domain.com/about   - will return '404 Not Found'
http://domain.com/about       - will work fine

I have Clean URL's installed (but I can't seem to change any settings in it) and I don't remember touching the .htaccess file.

Any help is much appreciated, thanks.

The following rules remove the www everywhere on your domain.
Put it in .htaccess file:

  RewriteEngine On
  RewriteBase /
  RewriteCond %{HTTP_HOST} ^www.yourdomain.com [NC]
  RewriteRule ^(.*)$ http://yourdomain.com/$1 [L,R=301]


Changing the target path of a Views more link Drupal 6, Views 2.

I would like the "View" link to point somewhere completely different than it normally does.

I've implemented hook_views_pre_render() and dug around in the $view object, but I can't seem to find the path in there.

How can I change the "View" link?

I used this method (views 3.x):

 <?php
 // get the $view object somehow and alter the display_handler options
 // see views_plugin_display.inc ~ render_more_link() method
 $view->display_handler->set_option('link_display', 'custom_url');
 $view->display_handler->set_option('link_url', 'node/!1/somewhere');


Module dependent on extension I am developing a small module which is dependent on the php_ldap extension. I would like to make sure that this extension is enabled before activating the module and if it is not display a message telling the user that the ldap extension needs to be installed and enabled. I have tried using hook_enabled() for this purpose, but since this hook is fired after the module is enabled it will not work as expected:

function example_enable() {
  if (!function_exists('ldap_connect')) {
    // Here I would like to halt the activation of the module
    drupal_set_message(t('The Ldap extension needs to be enabled.'), 'error');
  }
}

I am not sure how to stop the user from enabling a module if a specific extension is not installed or loaded. I was thinking about using hook_install(), but I am not sure that would work either.

The best solution for you is using hook_requirements .

function hook_requirements($phase){
       if ($phase =="install"){
         $requirements['php'] = array(
           'title' => 'LDAP extension',
           'value' => "LDAP",
          );
 if (function_exists('ldap_connect')) {
      $requirements['php']['description'] = 'YOU NEED TO install LADAP';
      $requirements['php']['severity'] = REQUIREMENT_ERROR;
     }
    }
return $requirements;

}

and another tricky solution (but NOT RECOMMENDED) is : Create Another module for php_ldap extension (let name it B), and on that module on hook_enable check the php_ldap extension is exists if not,  uninstall module(uninstall B module) , and  set your main module  dependent on first one(I mean Module B) . with this method you will be sure if the extension Available Module B can be installed and consequence Your main Module.

Something like  following snippet could help you to implement that

function MODULEB_enable() {
  if (!function_exists('ldap_connect')) {
        module_disable(array('MODULEB'));
       drupal_uninstall_modules(array('MODULEB'));
       drupal_set_message(t('The Ldap extension needs to be enabled.'), 'error');
  }
}


Add button on block body using php How To Add PHP code to the body of a Drupal 7 Block

I just want to make a button on block body. Is that possible?

this link will explain what i want to do [add button]: http://drupal.org/node/1046700

  This article is for Drupal 7 developers who have tried to put PHP code
  in the body of a Custom Block, but can't get it to run.

I'm not sure why you need this and you want a similar module of PHP filter which adds a new text format.

If you are familiar with custom moduling and hooks, I would give you a straightforward solution.
You could implement this using hook_block_view_alter by defining custom patterns (tokens).

<?php
function mymodule_block_view_alter(&$data, $block) {
    $patterns       = array('[add button]'); # more replacement patterns here
    $replacements   = array('<button type="button">Button</button>');
    if(isset($data['content'])){
        $content = $data['content'];
        if(is_string($content)) {
            $data['content'] = str_replace($patterns, $replacements, $content);
        }
        elseif(is_array($content)) {
        }
    }
}

Here is the result.

You may expand the code as you like such as defining more tokens, adding criteria for certain blocks, user roles, etc. You can even create an administration page at admin/config to define token replacements from UI.


Defining a constant via a function provided by another module? In my custom module I want to define a constant which takes its value from a function provided by another module. When I call this function in my module I get a 'call to undefined function' error. Curiously, if I call the function from inside another function, I don't get an error and it works fine. It's as if all module functions get loaded at the same time and then executed, but anything that is not a function gets executed first before the functions become available.

// MY_MODULE.module

$var = FUNCTION_FROM_OTHER_MODULE();
define('MY_CONSTANT', $var);

// use MY_CONSTANT in the other hooks and functions of MY_MODULE

Why am I getting this error and how can I set my constant with this function? Hope this makes sense. thanks.

You can use the standard global keyword provided by PHP. This is better placed somewhere early in a page load. One that I can think of is hook_menu or hook_init.

Personally though I would strongly recommend to use the variable_get() function provided by Drupal.


Purpose of the .htaccess files in the Drupal files directory? Besides the .htaccess file in the Drupal site main folder, I've found a .htaccess file in the sites\default\files folder, and further such files some sub-folders of sites\default\files folder (for example, in sites\default\files\private).

My question can actually be broken down into two separate questions:

How would you define in simple words the purpose of both the main .htaccess files, and the others under sites\default\files (I assume there aren't anymore .htaccess files?).
Is the only reason for splitting the Python syntax to different .htaccess files is to not make a single huge file? Or there are other reasons?

Thanks,

The first .htaccess file in the root directory is for routing and to override any PHP related settings.

The second .htaccess file under sites/default/files is for security purpose, to avoid any file injection. This folder is Drupal's main upload folder.

The upload folder can be moved in different places, or in a multi site setup you could have more than one folder. That is why they provided a separate .htaccess instead of putting everything in one place.


Sorting logic with anonymous function does not work This question is related to my previous question about how to change the sort order in a view. Since this is a new question I thought I better post a new one.

My new problem is that I use hook_views_pre_render() as suggested, but I am having trouble getting the views sort order right. I use an anonymous function like this to change the views order:

/**
* Implementation of hook_views_pre_render. Sorts the nodes under "Givare"
 */
function mysite_views_pre_render(&$view) {
    if ($view->name === 'related_items' && $view->current_display === 'probes') {
        $node = node_load(arg(1));
        $sortorder = array();
        $groups = $node->field_lagg_till_givargrupp['und'];
        foreach($groups as $group){
            $group_nid = $group['nid'];
            $group_node = node_load($group_nid);
            $probe_nids = $group_node->field_koppla_givare['und'];
            foreach($probe_nids as $probe_nid){
                $sortorder[] = $probe_nid['nid'];
            }
        }

        usort($view->result, function ($a, $b) use ($sortorder) {
            $cmpa = array_search($a->nid, $sortorder);
            $cmpb = array_search($b->nid, $sortorder);
            dsm($a->nid." ".$b->nid." ".$cmpa." ".$cmpb);
            if($cmpa === $cmpb) {
                return 0;
            }
            return ($cmpa < $cmpb) ? -1 : 1;
        });
    }
}

The variable $sortorder contains an array with nids in the wanted order. But the resulting $views_result does not follow that order (but it is altered, just in the wrong way). Can anyone see what I am doing wrong?

EDITED: added context – the view in question is a block display with a grid setting (there are several of these block displays in the same view and these block displays are used by Quick Tabs to render each block under a tab as related items.) In this particular block display I have tested to omit exposed filters, to deselect grouping by title etcetera to see if that would impact the sorting, but with no luck. I was surprised that this block needed sorting at all because I give the order explicitely with a contextual filter. See this question for the contextual filter:
Sort criteria is ignored in Views

Also, as I added the row dsm($a->nid." ".$b->nid." ".$cmpa." ".$cmpb); I can see that there are more than one hundred value pairs, but there are only 22 items to be rendered(!). The first few rows of that dsm() looks like this, where for example the nid 20726 is repeated several times:

  20726 20693 7 12

  21863 20726 5 7

  20726 20695 7 4

  20726 20697 7 0

  20726 20699 7 15

  20861 20726 21 7

  20860 20726 20 7

  20859 20726 19 7

  20858 20726 23 7

  20857 20726 22 7

  20768 20726 2 7

PROBLEM SOLVED. As J. Reynolds pointed out there were missing nid values in $view->result before the sorting was made.

There was also an issue with the nids because I had forgotten to set the field mapping (migrate d2d) to "do not create automatic URLs" for pathauto during a an earlier migration from D6 to D7 of the group nodes that contained the items in question. So the item nids were fetched from the wrong group entity. My mistake :-(.

But everything is sorted out now. Thanks for your input!


View that shows posts specific to the node In my website, under every project we do, there is a project info post which summarises what the project is about as well as all the recent updates(posts) about that project.

this is what it looks like http://i.imgur.com/yuJEnYA.jpg

I am trying to find a way i can view a 'project-info' node and add a 'view' that shows all the related 'project-posts' related to the particular project that the 'project-info' node is about.

I'm not sure where to begin.

(Drupal 7)

You should begin around Views of course. Just make a taxonomy term per project, and use Views to create a page with all nodes of type "update(post)". Then in tpl.php for a texonomy field of "project info post", build a link based on taxonomy term. That's pretty much all.

Entity reference module is worth to look at, too. Using it you could relate all "update" nodes to "project info" node. Similar effect to taxonomy, has it's pros and cons of course. Read about both, and choose your poison - referencing node directly is cleaner way, but taxonomy seems to be supported better, and is in core so less contrib modules for you.

Last but not least - you could simply make the update posts a comments on project info post.


Add values to an existing custom entity bundle I've created a custom entity with bundle and added 3 fields to the bundle(namely recipient, sender, flag). How can I add values to it programmatically.
Any help would be appreciated.

Thanks

One approach is using entity_metadata_wrapper:

  The Entity API provides wrapper classes you may use to make dealing with the values of an entity's properties and fields easier.
  Wrappers make it easier to get and set the values of fields and
  properties as well as to programmatically retrieve additional
  information about these elements and iterate over lists of values in a
  consistent manner.

Example:

$entity_wrapper = entity_metadata_wrapper('myentity', $id);
$var = $entity_wrapper->field_flag->value() + 1;
$entity_wrapper->field_flag->set($var);
$entity_wrapper->save();


Login via REST fails (403 forbidden) if cookie set by Drupal is kept I am trying to login via an Ajax request. I don't need any fancy REST features, I just want to login. According to the docs and other questions here it should be pretty straightforward for Drupal 8.3.7:

 $.ajax({
    method: "POST",
    url: "/user/login?_format=json",
    dataType: "json",
    contentType: "application/json",
    data: { user: "myname", pass: "mypass" }
})

However, this doesn't work at all for me, as I always get a 403 forbidden response.
The funny thing is, I can get it to work in Postman (a third party tool for sending REST requests) but only under certain conditions. It works great in Postman as long as I don't submit the domain's cookie with the request. If I stick to the default settings and let it send the cookie I have the '403 forbidden' issues again. If I then manually delete the cookie all is well again for the next attempt (then it sets a new cookie and the next attempt will fail).

I assume I am having the same problem with the in-browser jQuery version of my request, but there I can not seem to get rid of the cookie so I can't get it to work. I have tried every answer provided in related questions (csrf token, jdrupal, basic auth, ...) but it's always the same issue if I make a request where cookie data is automatically attached by the browser.

Any ideas what is going wrong? Why is Drupal hating on the cookie data (which was set by Drupal itself!). Can authenticated users not use the login url anymore? Is it maybe because the /user/login page redirects to /user for authenticated users, so the request is sent to /user instead if you're already authenticated?

Can authenticated users not use the login url anymore?

No they can't, it wouldn't make sense for them to be able to (you can't login if you're already logged in).

In practical terms, this is the routing entry for the login endpoint:

user.login:
  path: '/user/login'
  defaults:
    _form: '\Drupal\user\Form\UserLoginForm'
    _title: 'Log in'
  requirements:
    _user_is_logged_in: 'FALSE'
  options:
    _maintenance_access: TRUE

As you can see from the requirements, the user cannot already be logged in to access the resource.


How do I access update.php using nginx? I would like to use Drupal 8 (beta) with nginx. It works correctly, except update.php. It doesn't find it.

After analysing .htaccess (which is not processed by nginx) I realized that there is no real update.php file; it is served by index.php.

Does anyone have a working nginx configuration (with php5-fpm) which works with Drupal 8 beta, and that makes also update.php work?

You need to set your nginx config file to rewrite 404 error to index.php

Just added this:

error_page 404 = @rewrite;
location @rewrite {
  rewrite ^ /index.php;
}


View output a custom designed teaser then full post separate design I have a design that requires and custom design for the teaser view. I need to output the custom teaser view then have the full post follow another template.

The teaser has a float left thumbnail image and a few lines of text to the right. The actual post will have many images and text.

Is this possible?

Sure it is possible.For that you need to add custom field in your content type called featured image.
While creating the views use that field first and you can have to add

float: left;

In Image field css class to align it left

For exmaple you can see my site www.techiestuffs.com which is exactly what you mentioned.The teaser has image aligned left and when you click either image or title it will leads to original content.
see the below css code i used to achieve this

  .view-recentarticles .views-field-field-image {
float: left;
padding: 3px;
border: 1px solid #C9C9C9;
white-space: nowrap;
margin-right:10px;
margin-bottom:5px;
}
.view-recentarticles {
padding:5px;
border:1px solid #ccc;
background-color:#ffffff;
}

.view-recentarticles .views-field-title {
  margin-bottom: 10px;
  padding-left:10px;
  font-size: 18px;
  line-height: 1.4;
  font-weight:bold;
  background-color:#f4f4f4;
  }
  .view-recentarticles .views-field-title a {
  transition: all 0.2s;
  -moz-transition: all 0.2s;
  -webkit-transition: all 0.2s;
  -o-transition: all 0.2s;
 }
 .view-recentarticles .views-field-title a:hover {
  color: #181818;
 -webkit-transition: all 0.2s;
  text-decoration: none;
  background-color: #f6ecdd;
 }
  .view-recentarticles .views-field-body {
  padding-bottom:5px;
  border-bottom:2px solid #f4f4f4;
  }
    .view-recentarticles .views-field-field-blog-author {
    font-size:10px;
    font-weight:bold;
  padding:5px 2px 5px 2px;
  background-color:#f4f4f4;
  }


Customizing recent blog posts block I'm including the recent blog posts block in the sidebar of my Drupal site which pulls out the 10 most recent posts in a list with the title of the post linking to the post itself. I'd like to pull out more information, specifically the "Authored by" and "Authored on" fields.

What I have at the moment:

    #post title#

What I'd like to achieve:

    #post title#

#author#

#date

The blog_page_last function in blog.pages.inc appears to be where the fields are being pulled out but I can't work out the additional field names (author, date) to enter.

There doesn't appear to be a .tpl.php file in the blog module folder and I can't find anything in blog.module or blog.pages.inc that indicates how/where the markup is set.

Thanks

The block "Recent blog posts" is in blog.module.

/**
 * Implements hook_block_view().
 *
 * Displays the most recent 10 blog titles.
 */
function blog_block_view($delta = '') {
  global $user;

  if (user_access('access content')) {
    $result = db_select('node', 'n')
      ->fields('n', array('nid', 'title', 'created'))
      ->condition('type', 'blog')
      ->condition('status', 1)
      ->orderBy('created', 'DESC')
      ->range(0, variable_get('blog_block_count', 10))
      ->addTag('node_access')
      ->execute();

    if ($node_title_list = node_title_list($result)) {
      $block['subject'] = t('Recent blog posts');
      $block['content']['blog_list'] = $node_title_list;
      $block['content']['blog_more'] = array(
        '#theme' => 'more_link',
        '#url' => 'blog',
        '#title' => t('Read the latest blog entries.'),
      );

      return $block;
    }
  }
}

So there is no .tpl.php to customize.
Using Views module to create a block which lists out recent blog posts would be a solution for you.

Hope this help,


Drupal 7 special chars not working in db_select I have implemented custom search to get some values from node.

When I'm using special chars like "/, ?, !", no result is being displayed.

Example value : "24/7" or "site?" or "test!", etc...

$search_text = '24/7';
$query->condition(db_or()
->condition('n.title', '%' . db_like($search_text) . '%', 'LIKE')
->condition('fld.body_value', '%' . db_like($search_text) . '%', 'LIKE'));

I'm running my site in Drupal 7. PHP version is 5.5.9. Using Mysql DB. OS windows.

Note:
Query is correct. Its giving proper result for other than special chars.

Edit:
$query->arguments(); is returning below image.

I was running LIKE command in phpmyadmin. Please find that screen shot below.

So what is the modification do we need to do at PDO to support this issue?

It doesn't look like anything wrong with query. I'm using drupal 7 with basic setup and one node(nid=3) has 24/7 in title & body and one node(nid=4) has only in body.

  // Make sure to decode, if the search string is part of URL.
  // $search_text = urldecode($_GET['query']);

  $search_text = '24/7';
  $query = db_select('node', 'n');
  $query->join('field_data_body', 'b', 'b.entity_id=n.nid');
  $query->fields('n', array('nid'))
    ->condition(db_or()
    ->condition('n.title', '%' . db_like($search_text) . '%', 'LIKE')
    ->condition('b.body_value', '%' . db_like($search_text) . '%', 'LIKE')
  );
  $result = $query->execute()->fetchAll();
  print_r(db_like($search_text));
  print_r($query->arguments());
  print_r($result);

and the result is:

// print_r(db_like($search_text));
24/7

// print_r($query->arguments());
Array
(
    [:db_condition_placeholder_0] => %24/7%
    [:db_condition_placeholder_1] => %24/7%
)

// print_r($result);
Array
(
    [0] => stdClass Object
        (
            [nid] => 2
        )

    [1] => stdClass Object
        (
            [nid] => 3
        )

)

Note: If you are getting the search string from URL as query string make sure, you have done urldecode() before send to SQL.


Creating a grid of referenced Commerce products I'm using Drupal 7 along with Commerce 1.x and I have created a content type that has reference field for Commerce Product entities.
And now I would like to render a grid of referenced products i.e. dedicated add to cart form for each product on the node page.
At least so far it seems like an impossible task to do. I've tried with Views, custom form template variable etc. but it always gives errors like
Notice: Undefined index: #options in function form_process_radios() (row 3188
Parameter must be an array or an object that implements Countable in function form_process_radios() (rivi 3188
Somehow it is always expecting a radio element with options (which is the default formatting) for multiple products.
However, that is not what I want and I've tried to set it as hidden element. I also can see the forms but would like to get rid of errors and create this "by the book".
<?php
function mymodule_preprocess_entity(&$variables) {

  $variables['add_to_cart_form'] = '';

  if ($variables['elements']['#entity_type'] == 'commerce_product'){

      $item = $variables['elements']['#entity'];

      if (empty($item->product_id)) {
        return;
      }

      $form_id = commerce_cart_add_to_cart_form_id([$item->product_id]);

      $line_item = commerce_product_line_item_new($item, 1, 0, [], 'custom_owner');
      $line_item->commerce_product = $item->product_id;
      $line_item->data['context']['product_ids'] = array($item->product_id);
      $line_item->data['context']['show_single_product_attributes'] = 1;

      $product_form = drupal_get_form($form_id, $line_item);

      // Trying to change from radio element to hidden
      $product_form['product_id']['#type'] = 'hidden';
      unset($product_form['product_id']['#theme_wrappers']);
      unset($product_form['product_id']['#process']);

      $form_markup = drupal_render($formp);
      $variables['add_to_cart_form'] = array('#markup' => $form_markup);

  }

}?>

This is possible out of the box without any custom code, just plain Views. The trick is to make the View based on content of whatever your node type is and set a relationship from the node to the products referenced by its product reference field. Once you have product fields available to the View, Commerce 1.x provides a per-variation Add to Cart form field to drop into the View.
I created a sample View that does this, placing it in a block on node pages of my product display node type. It uses a contextual filter to determine the node ID from the URL, joins to the products via the relationship I described above, and then shows the product title, price, and Add to Cart form in a grid:

Note that the line items added via the product Add to Cart forms do not maintain the context of the node; that's why "Product Three" is rendered as a link in my cart but Two and One are not. It would take custom code to ensure those forms have the appropriate context at this point, but that's another question.
In case you're a visual learner, here's the View I constructed to make this work:


How do I include special characters in a path alias? I'm trying to add a path alias for a node, /student-&-courses/maths, but in the URL it is displayed as www.testone.com/student-%26-courses/maths.
I unchecked the Generate automatic URL alias option manually set the path alias without adding a pattern. I enabled the Reduce strings to letters and numbers and Transliterate prior to creating alias options in the settings, but it doesn't have any effect: The special characters are not encoded in ASCII format.
How can I fix this so the URL contains special characters?

The ampersand (&) is a reserved character in URLs because it is usually input as part of the query string.  Some more info.
Most special characters can be used in URLs with the settings you described in your question, but & is an exception.  Either just live with %26 as the encoding or rewrite the title to not use the & symbol, which is reserved.
This is not a Pauthauto problem; it's a URL problem.


Remove default css file I need to remove jquery.ui.theme.css file, for this in my template.php I implement the below mentioned code:

function GNG_css_alter(&$css)
{
unset($css[drupal_get_path('module', 'misc') . '/ui/jquery.ui.theme.css']);
}

but its not working.

<?php
/**
 * Implements hook_css_alter().
 */
function seven_css_alter(&$css) {
  // Use Seven's vertical tabs style instead of the default one.
  if (isset($css['misc/vertical-tabs.css'])) {
    unset($css['misc/vertical-tabs.css']['data'] = drupal_get_path('theme', 'seven') . '/vertical- tabs.css');
  }
  // Use Seven's jQuery UI theme style instead of the default one.
  if (isset($css['misc/ui/jquery.ui.theme.css'])) {
    unset($css['misc/ui/jquery.ui.theme.css']['data'] = drupal_get_path('theme', 'seven') . '/jquery.ui.theme.css');
  }
}


Features - Is there a way to push changes back into the database I have a fairly good understanding of the way that features works:

Make changes to your test site.
Create a feature which contains the changes.
Copy the new module (which was created by features) to live.
activate the new module.
Verify that the changes now exist on the live site.

This works great, but is there a way to take the changes that are contained in the new feature module and move them into the live database?  My goal is to reduce the number of active modules I have on my live site.

Once the module generated by Features has been activated and the status on the overview page reads "Default" the changes are in the database. "Default" means that the database configuration matches the configuration defined in the module. (The status "overridden" indicates that the module generated by Features does not match the database configuration.

I think what you want to ask is, "How can I disable a Feature-generated module without losing the configuration that it provided?", which has been asked on this site before.


How do I render field outside node For custom content type page I used this:

function MYTHEME_preprocess_page(&$vars, $hook) {
    if (isset($vars['node'])) {
      // If the node type is "blog_madness" the template suggestion will be "page--blog-madness.tpl.php".
      $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
    }
}

So now it means I can use page.tpl.php for my custom content type pages. So for the default Basic Page the template page is page--page.tpl.php and I did test it and it works. Except this:

I am trying to render some field outside . So I used this: <?php print render($content['field_banner']); ?> right outside <div id="content" class="column" role="main"> but it's not printing.

I was told this has something to do with node_load. But I'm not experienced with that.

You can load node again in other place and render it fully or partially. Via block or something else. Node load is hard operation, use module entitycache to load the same nodes faster.


What are the minimum requirements for a custom Drupal 8 theme that can be enabled I'm testing creating new themes in Drupal 8 and I'd like to know the very minimum it takes to create one that can be enabled. I'm not worried about any actual styling yet.

I've created a theme folder in themes called uktheme and I currently have a uktheme.info.yml file in that folder.

the contents of that file are

name: UK Theme
type: theme
description: 'Test theme'
package: Core

regions:
  header: Header
  primary_menu: 'Primary Menu'
  feature: 'Feature'
  content: 'Content'
  page_bottom: 'Page Bottom'
  footer_first: 'Footer first'
  footer_second: 'Footer second'
  footer_third: 'Footer third'

However I receive

The website encountered an unexpected error. Please try again later.

when attempting to go into the appearance settings. I do not believe it's my folder structure and location because I successfully created another theme copying the content of Bartik.

Perhaps you've missed core.
Required params in *.info.yml are:
name
description
type
core
regions:content

Also you can check your *.info.yml for using tabs instead of spaces:

  Tabs are NOT allowed, use spaces ONLY.
  You MUST indent your properties
  and lists with 1 or more spaces.

See more in official docs: https://www.drupal.org/theme-guide/8/defining-a-theme


Practical staging of config I am successfully migrating at least the bulk of my config from dev thru stage to prod. But the process could obviously be more robust.

Current procedure:

create central (bare) repository
create dev

clone to dev machine
perform set-up (usually standard template) using separate sites/dev.mysite.com settings. No content. No real settings beyond the defaults imported from the template and the install.php process.
export config to from_dev config dir
push all to central repository.

create stage

clone to stage
perform identical setup but using sites/stage.mysite.com instead.
import config from the from_dev config dir

use drush config-edit to change the freshly created UUID's for system.site and shortcut.set.default so they match the UUID's from the dev site.
use drush config-import to duplicate the config from dev.

Basically repeat this process for any other sites in the staging tree.

Problems:

All the sites now have identical UUID.

I'm not clear on the value/purpose of UUID but as long as they are all unique within a site; I'm not sure that's a problem?
The import process does not have the ability to modify existing config objects when the change is limited to UUID. If the UUID's differ, the old object is deleted and the new (otherwise identical object) is created from scratch. This has the side effect of also deleting any content associated with the old object.

In theory, this sort of delete/replace only happens during initial setup before the sites have any data; so there's no harm. However, great care is obviously required to guarantee that no "important" object will be deleted thru the entire life of the project.

Is this an intended D8 workflow?

Should the UUID (either in the live target stage site or in the configs from dev to be imported) be edited to match before the import?

Is there anyway to instantiate a D8 stage (prod) site that is genuinely "blank" (i.e.: an initial config import would require no editing of UUID and/or deletion/recreation of config objects)?

I've been using the standard template because it includes things like Configuration Manager which facilitate the config sharing process. Note that if stage is not built with the same template as dev than the import will fail with something like (paraphrase from memory): Unable to uninstall module 'minimal' because it does not exist; Unable to install module 'standard' because it does not exist. Is there a better template for this process?

I would approach it this way:

Have a branch master:

Create 2 separate branches fed from the master (master being prod):
- stage
- test

Create a new branch abcfeature based from master, after complete, merge to stage/test.

Use domain alias's to setup different URLS in your test environment.


Clear example on how to use #theme for form API I cannot find a good example of how to accomplish custom theming on a field level within a form:

$form['test_2'] = array(
  '#type' => 'textfield',
  '#title' => t('Test Field #2'),
  '#required' => true,
  '#description' => t('This is a test field which we hook into.'),

  '#theme' => 'custom_func'
);

Inside my template.php I have:

function MYTHEME_theme() {
    return array(
      'custom_func' => array(
        'render element' => ??? // WTF goes here???
      )
    );
}

function MYTHEME_custom_func($variables) {
  return 'Something';
}

This code obviously does not work...what am I missing?

You're so close...the name of the render element is arbitrary, it's just a name so you can pick it up at the other end. Or, put more eloquently:

  The name of the renderable element or element tree to pass to the theme function. This name is used as the name of the variable that holds the renderable element or tree in preprocess and process functions.

So:

function MYTHEME_theme() {
  return array(
    'custom_func' => array(
      'render element' => 'my_element',
    ),
  );
}

function MYTHEME_custom_func($variables) {
  $element = $variables['my_element'];

  // Use the values in the $element render array to build markup.

  return $element;
}


Required taxonomy term fields for node publishing? I want to create content which has shared some aspects. I am doing this through a taxonomy reference. The taxonomy has certain fields that describe each piece of content (in my case used cars).

In my workflow, I only want the content published if the taxonomy term reference has all its fields filled out. How can I automate this workflow?

This is a workflow requirement that can be handled by Rules.

Set your user car type set to unpublished by default.
Create a rule for the event Before saving content of type User Car (or whatever your node type is called)
Add a Data value is empty condition. On the Data selector you'll want something like node:field-MYTERM_FIELD:0:field-MYREQUIRED_FIELD (it depends on your field names). Make sure to check the Negate checkbox so that the rule is triggered when the taxonomy field IS NOT empty.
Add a Publish Content action.


Using a computed field: How to extract a field value from a referenced node into field collection. (Multiple value) I have written this code inside a computed field, which has given me as result,
the referenced entity numbers how are saved in the field as an array.

I would like to know how to extract from the entity number a specific field, such as the title.

foreach ($entity->field_campos as $field) {
}
foreach ($field as $index => $valores) {
$terminos[] = $valores['value'];
}
$item2 = field_collection_item_load_multiple($terminos, $reset = FALSE);
foreach ($item2 as $indice => $values) {
$entity_field[]['value'] = $values->field_nombre_2['und'][0]['target_id'];
}

// Display code (PHP).
$display_output = $entity_field_item['value'];

I am using Drupal 7.

You can do something like this:

$referenced_titles = array();

foreach ($item2 as $indice => $values) {

  // use node_load($nid) to load the node.
  $referenced_node = node_load($values->field_nombre_2['und'][0]['target_id']);
  $referenced_titles[] = $referenced_node->title;

}


Remove users with no created nodes D7 I have a site setup where users create a node as soon as they login from the activation link sent via email. I've recently been getting tons of people signing up but not creating any nodes because the emails they register with are obviously fake so I would like to remove all the users with the role listing user that hasn't created a node withing a day of registration.

I need help doing this with Rules if at all possible please. If you have any other methods that doesn't involve complex php that would help as well.

Thanks

You can create a View that shows the users who haven't authored any nodes, and then use VBO https://www.drupal.org/project/views_bulk_operations  to delete those users.


Session Timeout after certain period of inactivity How can I logout users after a certain period of inactivity (say 20 minutes)?

You are looking for Automated Logout module.

  This module provides a site administrator the ability to log users out
  after a specified time of inactivity. It is highly customizable and
  includes "site policies" by role to enforce logout.

Features

Different timeouts based on role
Disabling of timeouts based on role
Permission for users to set their own timeout
Includes some JS mechanisms to keep uses logged in even if multiple tabs are open or if the user is working on a form for a long period of time.
Includes developer hooks to allow users to remain logged in depending on your own project specific requirements
Optional integration with Javascript Timer

(or) take a look at Session Limit

(or)

Ejector Seat

  A Drupal module to immediately log out (eject) a user whose session
  has ended


Implementing hidden content parts (as in old "Hidden Content" module) There is (long unsupported) "Hidden Content" module, allowing to insert content blocks visible by certain roles only, i.e. like below:
[hidden role="Role Name"]
   ...content visible to "Role Name" role only
[/hidden]

I browsed through related modules (from "Content Access Control" etc), but see no good match for this module's capabilities. Are there any simple means to achieve the above without either re-implementing the module for Drupal 9 or using inline PHP?
"Paragraphs Access Control" looks somewhat suitable, but it requires creating quite a complex structure only to restrict access to text blocks.

You could use Block Class module to set blocks with some useful classes like "only-role_name", etc. and hide/display it on your theme stylesheet.

Maybe even you could set a new block type and, if this type has its own css class (I'm not sure about it), use it to hide/display using, again, your theme stylesheet.

You could, too, use a new content type to create the block contents and Views to render this as blocks where you need. Views is able to restrict his view depending on roles or permissions.


Display data from web service using views I need to query data from a web service and display it in a view without storing the data in Drupal database. I am using WSData module for this purpose but I am unable to figure out how and when the webservice is getting invoked. My web service doesn't have any parameters passed and it returns a list of items. I would like to display the list as a table using views.

It would be of great help if I can get any samples or references.

You can take a look at https://www.drupal.org/project/wsdata

This module allows you to bypass the default data storage location for fields and entities and instead load the data from a web service.

This is useful when your primary data source is in another system but you want to display/use this data in your Drupal site without the hassle of syncing or importing data.


sibling taxonomy terms Drupal 7

I have a vocabulary with hierarchical terms countries and cities.

I have a view with context filter=cityA ( parent country A)

How I can display into a block all cities from country A  ( siblings of cityA from vocabulary)?

Thanks

You can try using taxonomy_get_children($termid) to get children of term and then taxonomy_get_parents($termid) and again taxonomy_get_children() to get the siblings .
The following is the code I used in such situation :

<?php

if (isset($page['#views_contextual_links_info']['views_ui']['view']->args[0])){
    $termid = $page['#views_contextual_links_info']['views_ui']['view']->args[0];
    $terms = taxonomy_get_children($termid);

    if (empty($terms)) {
        $parent = taxonomy_get_parents($termid);
        $terms = taxonomy_get_children(key($parent));
    }
}

if (isset($node->field_category['und'][0]['tid'])) {
    $termid =  $node->field_category['und'][0]['tid'];
    $terms = taxonomy_get_children($termid);
}

?>


Fallback to local images when Cloud Files breaks? I'm using the Cloud Files module which uses the Rackspace Cloud Files PHP API to store all uploaded files on Rackspace Cloud Files (a CDN). It all works very well.

However, today, Rackspace itself had an outage related to their API and it caused my entire site to break. I absolutely can't have this happen when my site is finally live. Is there any way to keep the files locally as well as in Cloud Files so that if there is a problem I can flip a setting in the admin pages and it'll start using the local files so that the site continues working while Rackspace works on the problem?

In javascript, you can listen to the image's onerror event listener.

set the source as normal. in onerror, set this.src to your local image path:

<img src="//somecdn.com/cat.jpg" onerror="this.src='/localpath/cat.jpg';" />

you could use jquery to loop over all images on the page and add the onerror event listener


Acquia Dev Desktop and Drush broken with syntax is incorrect I did a clean install of Acquia Dev Desktop (Build Nov 13th, 2017) under Windows 10. I can clone my site (Drupal 8) and then click to open my local Drush console. It opens a DOS prompt into the docroot directory. When I execute any drush commands I get "The filename, directory name, or volume label syntax is incorrect."

Here is a sample:

  C:\DevDesktop\website-dev\docroot>drush -d -d  version

  Loading drushrc "C:\Program Files (x86)\DevDesktop\tools\vendor\drush\drush\drushrc.php" into "drush" scope.   [bootstrap]

  [0.78 sec, 2.48 MB]
  Cache HIT cid: 8.1.15-commandfiles-0-61c5476a3a04a40d4bdadfd521f0641f [0.84 sec, 2.52 MB]                          [debug]

  Begin redispatch via drush_invoke_process(). [1.16 sec, 6.43 MB]                                                  [notice]

  Backend invoke: "C:\DevDesktop\website-dev\docroot\vendor\bin\drush.launcher"                            [command]
  --root="C:\DevDesktop\website-dev\docroot" --debug --verbose  version 2>&1 [1.21 sec, 6.45 MB]

  Calling proc_open("C:\DevDesktop\website-dev\docroot\vendor\bin\drush.launcher"  --root="C:\DevDesktop\website-dev\docroot" --debug --verbose  version 2>&1);

  The filename, directory name, or volume label syntax is incorrect.
  End redispatch via drush_invoke_process(). [1.24 sec, 6.44 MB]                                                    [notice]

I was also facing the same issue on windows 10 with Acquia Dev Desktop and configured existing Drupal 8 project from a client.
Following three things what I did worked for me.
I simply:

Removed directory vendor/drush
Removed directory vendor/bin
Removed line "drush/drush": "^8.1" from composer.json which is located on docroot directory.

Now, default drush is working for me as you can see the default drush version at C:\Program Files (x86)\DevDesktop\tools\composer.json.
Hopefully, this will help someone else.


How do you go to an overlay view within Drupal using drupal_goto? I want to redirect to a page with an overlay within code.  I have tried the following, which is the path in the URL.

 drupal_goto('#overlay=admin/vendor/auth-stripe');

The path I want in overlay is admin/vendor/auth-stripe.  When I remove the #overlay= it works, but I want my user to see it in overlay mode.

You cannot pass a URL fragment into drupal_goto() like that or it will get escaped and won't work properly.

From the drupal_goto() docs it says the second parameter is an array of $options that get sent through to the url() function.

Looking at the url() function docs shows that one of the allowed $options is:

  'fragment': A fragment identifier (named anchor) to append to the URL. Do not include the leading '#' character.

So you should be able to do this:

drupal_goto(current_path(), array('fragment' => 'overlay=admin/vendor/auth-stripe'));

Note the use of current_path() as the path so that the page under the overlay will be the on the user was previously on.

If you didn't want that, then this would use the front page instead of the current page (because if you pass an empty path into the url() function it uses the front page as a default):

drupal_goto('', array('fragment' => 'overlay=admin/vendor/auth-stripe'));


Is it possible to export all block's region settings to Features? I'm about use Features to deploy all configuration of my Drupal (7) site.

Now I'm wondering if there is a way to export the entire settings for block to region assignment without having to export all blocks into one big feature.

One big feature containing all blocks would create conflicts with other, more atomic feautures. Even worse, it seems only blocks that have a region assigned seem to be exportable, so I can't figure out yet how to export my defintions of disabled blocks. For example: I move a previously displayed block to the disabled region - is there a way to deploy this setting to remove the block on the staging site, too?

We abandoned managing the blocks through the normal Structure->Blocks page a long time ago. Now we use it simply to set block titles, and the individual block's settings.
For assignment onto pages we use Context module:

Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.
Think of conditions as a set of rules that are checked during page load to see what context is active. Any reactions that are associated with active contexts are then fired.

This module lets you assign blocks to regions using criteria based on more than just page paths, such as taxonomy term of the content, type of content etc. And also it allows you to react with more than just blocks as well. Also one block can be assigned to different regions using more than just 1 context.
Overall the most important thing to this question regarding Context module is, the context rules are exportable via features!


Different front page node depending on logged in? How would I go about displaying a different front page node depending on if the user is logged in or not.

For example when a user is not logged in, you would be viewing the About Page.
When a user is logged in, you would be viewing your user profile page.

There is several solutions to go about this

but the easy way out is this module

Frontpage module

but you can also make a simple  rule that says that if the user is logged in

Rules module

Node.js Alternativ solution

hope it helps you on the way


Drupal Static HTML content not rendering Hoping all is well..
I have developed a personal theme and enabled it in a drupal installation. However static html doesn't show up at all.

I have used wysiwyg with ckeditor and enabled full html and still nothing shows up after saving. This happens with nodes and blocks. Only Plain text works and of course that doesn't implement html.

This problem's just began with this project. I have tried to create a fresh website and the problem prevails. I have even tried enabling garland (one of the default drupal themes) and i am still facing the same problem.

Has anyone faced a problem like this before?

Looks like it worked out after Upgrading Mysql (from 5.1.. to 5.5..) had php (5.4.17) now its 5.4.22 (guess there's no big difference there..). Thought i'd put it here incase anyone runs into such a weird problem in the future.

Thanks everyone for trying.. Really appreciate it!


Remove  tag after form tag in user register form Drupal 7 I have added this code to template.php

function mytheme_theme(&$existing, $type, $theme, $path){
  $hooks = array();
   // Make user-register.tpl.php available
  $hooks['user_register_form'] = array (
     'render element' => 'form',
     'path' => drupal_get_path('theme','mytheme'),
     'template' => 'user-register',
     'preprocess functions' => array('mytheme_preprocess_user_register_form'),
  );
  return $hooks;
}

function mytheme_preprocess_user_register_form(&$vars) {
  $args = func_get_args();
  array_shift($args);
  $form_state['build_info']['args'] = $args;
  $vars['form'] = drupal_build_form('user_register_form', $form_state['build_info']    ['args']);
}

also I have created user-register.tpl.php with this

test

but the result is

<form class="user-info-from-cookie" enctype="multipart/form-data" action="/user/register" method="post" id="user-register-form" accept-charset="UTF-8">

    test

</form>

How I can remove the div tags between form and span.

Thanks

That <div> is actually there to ensure XHTML compliance so it shouldn't really be removed.

If that's not an issue for whatever reason, you need to override theme_form(), which is responsible for adding that <div>, and just remove it from the returned markup. The full code is quite short so I'll include it:

function MYTHEME_form($variables) {
  $element = $variables['element'];
  if (isset($element['#action'])) {
    $element['#attributes']['action'] = drupal_strip_dangerous_protocols($element['#action']);
  }
  element_set_attributes($element, array('method', 'id'));
  if (empty($element['#attributes']['accept-charset'])) {
    $element['#attributes']['accept-charset'] = "UTF-8";
  }
  return '<form' . drupal_attributes($element['#attributes']) . '>' . $element['#children'] . '</form>';
}


Save selected values from a checkbox into a field I've the next form.

  $query = "SELECT name, tid FROM taxonomy_term_data WHERE vid=2 AND language = '$language_url';";
  $result = db_query($query);
  foreach ($result as $row2) {
     $options2[$row2->tid] = t($row2->name);
  }
  $form['group_config']['municipios'] = array(
     '#type' => 'checkboxes',
     '#title' => t('Municipios'),
     '#options' => $options2,
     '#required' => TRUE,
  );

I do a query to take the differents taxonomy terms that I have.

I don't know how to obtain the values that the user has selected and save into a field.

I've done the next code but It dosn't work.

   function anuncio_datos_usuario(&$form_state,$values){
        $node = new stdClass();
        $node->title = $values['titulo'];
    $node->type = $type;
    node_object_prepare($node);
    $node->language = $values['idioma'];
    $node->uid = $userid;
    $node->status = 0; //(1 or 0): published or not
    $node->promote = 0; //(1 or 0): promoted to front page
    $node->sticky = 0;
        if(count($values['municipios']))
        foreach($values['municipios'] as $municipio){
            if($municipio!=0){
                $node->field_municipio[LANGUAGE_NONE][]['tid']= $municipio;
            }

        }
    $node = node_submit($node); // Prepare node for saving
    node_save($node);

How can I save all the selected values into the field?

Thank you.

I think you what you want is an entity reference field.

Go the manage fields for your content type and create a new field of the type entity reference. In the setting for number of values choose unlimited and as widget choose checkboxes.

This will save the values for you, and display the chosen ones when the node is edited.


Is it possible to approve an Enitity Form? Is it possible to approve a submitted Entity Form by a specific user/role ?

For example, I have a Leave Request Entity form to be submitted by the employee(role). The manager(role) will approve or disapprove the leave request.

Thanks for those who can give me some ideas.
(Im a beginner and learning drupal)

Define a field called "Approval Status" in your entity form with two values Approved / Unapproved
Be Default set it to "Unapproved"
Use Views to list your custom entities see below post for reference

How do i use views with a custom entity?

Update "Approval Status" using VBO. See this article to find out how to create simple action.


Danland theme license I have chosen the Danland theme for my drupal site.
The theme is licensed as GPL (from the license attached to theme). At the bottom of the theme on my website, there's "Theme by Danetsoft and Danang Probo Sayekti inspired by Maksimer", and I'd like to ask you if I can remove it (I won't derive and publish the theme).

I think I can, but I'm not sure.

Any module/theme hosted on Drupal.org is licensed under the GPL License v2+, which allows you to edit them, as long as you respect the license itself.

You can edit out that string. Even if you were distributing your version, you should distribute the source code too, which is the theme itself, as PHP is not compiled. You should not remove the attributions left in the comments from the previous author, though.


How can I programmatically get an entity's validation errors? I'm submitting an entity programmatically through a custom, non-entity form. How can I validate the entity before submission, and report the validation errors to the user if they exist?

This code worked for me, not sure if best approach:

    $errors = $my_entity->validate();
    //see if there were any errors
    if ($errors->count() == 0) {
      //there are no validation errors, move to next step
      $this->my_success_action($my_entity)
    }
    else {
      //there were validation errors, report them
      for($j = 0; $j < $errors->count(); $j++) {
        $error = $errors->get($j);
        //the entity field that failed validation
        $property = $error->getPropertyPath().'_my_weird_field_suffix';
        //the error message about how validation failed.
        $message = $error->getMessage();
        $form_state->setErrorByName($property, $message);
      }
    }


How to manage multisite themes from master Drupal installation I have Drupal 8 multisite to benefit from a single codebase. Also they share the same database. How can I change themes of all the other sites from my main domain/site?

Parent and child domain :

- mainsite.com
-- childsite1.com
-- childsite2.com
-- childsite3.com

The README.txt file in Drupal's /themes directory states:

  …the sites/your_site_name/themes directory
  pattern may be used to restrict themes to a specific site instance.

For instance, you might have:

- sites/all/themes/m1
- sites/childsite1.com/themes/c1
- sites/childsite2.com/themes/c2
- sites/childsite3.com/themes/c3


How do I calculate the days difference between start and end date of a date range field in Views PHP? I'm trying to get the total number of days in a date range field using Views PHP. Any help will be greatly appreciated.

I tried the code below first in "value code" then in "output code" but it didn't do anything.

$start = strtotime($row->field_start_and_end_date:value);
$stop = strtotime($row->field_start_and_end_date:value2);
$days = $stop-$start;
echo $days;

Within Views PHP, there are 2 fields. The value code field and the output code field. The first is used to calculate the value (for filtering, sorting, etc). The second is used to display the value.

So in the first field you'll have to perform your calculations and return the final value. If your field is numeric, try to only calculate the number here. Prefixes and suffixes can be added in the output field. (So the value for this field could be 3.)

In the output field you again have to return the final value. This can be the same value as calculated in the value field (there is a token for this value). But you can also append pre- and suffixes and return a string. (Here you can for instance append days to the value to have it display 3 days.)


How to upgrade to Drupal 8 from 7 with clean install? I currently have a Drupal 7 site that I want to install Drupal 8, but do a clean install. This means wiping away everything and starting with a new Drupal 8 instance. I have seen many articles on how to upgrade where the content types, fields, code, and other parts are migrated. However, I just want to upgrade to Drupal 8 without any migration of the content type, files, databases, and remove old directories that are not needed for Drupal 8.

How can I upgrade to Drupal 8 without any migration for a clean instance?

If I'm understanding your situation correctly in that you just want a new Drupal 8 website without any of the content from your existing Drupal 7 website then you would just simply install Drupal 8 from scratch, as if you didn't even have an old site.

Once the new Drupal 8 website is installed you can then create/re-create any content that you'd like.


Customized search result I have a content type let's say content type 'A', I am using view to show some of the field on some page, Now the problem is that pages generated by the content type are just a junk because I am not showing it to uses , only i am showing it using view page/block. Problem: I don't want to show those junk page in Search result  , Plz let me know how to do it?

You can achieve required customization by using Search configuration module.

additional things can be done with the modules are:

Alter the appearance of the core node search form.
Group content types for more meaningful searching
Restrict search results by the content type. This is a role based
restriction.
Restrict search results from showing individual items.
Alter the pager limit (aka number search item results per page).


Expose a custom view filter based on custom field in another node I want an user configurable boolean view filter, displaying child nodes in an hierarchy based on a value, canDisplayOthers, in the master node.  The master/children are joined by a field setID.

I tried to do a self-join, adding a view relationship based on setID, but setID is not in the list of relationship fields.

Using Php, the recipe in:

https://ohthehugemanatee.org/blog/2013/12/26/44497-people-are-wrong-how-to-never-use-views-php/

says to use a handler.  My handler would return a boolean, something like:

class mymodule_handler_field_isDisplayable extends views_handler_field {
  /**
  * Render the name field.
  */
  public function render($values) {
    $value = $this->get_value($values);
    /*
       How can I get current node ID (nid) here?

    */
  }
}

and a hook_views_data something like:

function mymodule_views_data() {
  // Basic table information.
  $data['mymodule_ToDisplay'] = array(
    'table' => array(
      'group' => t('Global'),
      'base' => array(
        'title' => t('ToDisplay')
        ),
      ),
    'name' => array(
      'title' => t('ToDisplay'),
      'field' => array(
        'handler' => 'mymodule_handler_field_isDisplayable',
      )
    ),
    'filter' => array(
    'handler' => 'views_handler_filter_boolean',
    )
  );
  return $data;
}

I can't figure out:

in mymodule_views_data, what is this thing called 'table'?
how do I get the setID or current nodeID into the mymodule_handler_field_isDisplayable function?

In curiosity;
- what is the minimal hook_views_data?
- Where is a good place to find where hook_views* parameters are explained?

I am using drupal7 and views 3

ADDITION  15 July 2014

Geoff, below, kindly mentioned that the problem would be easier if I created a master node content type.  I created a masterNodeType content type, containing the fields:

setID
canDisplay

Now, masterNodeType and childNodeType have the common field, setID, but I can't see setID when I configure the view relationship.  How do I get setID, and/or masterNodeType into the view relationship?  What is the criteria for those view relationship components?

Thanks to the clues provided by Geoff in a comment, I found the answer.
My mistake, (doing too much work), was  to create my own foreign key, test_set_id.   Drupal uses node_reference fields for such joins. Using node reference, associated content can be directly accessed after adding the relationship in the set-up view screen, without any code.
I also ended up creating an additional master parent content type, to hold some generic test_set information, and to give the child nodes something to point to.


Search API module causes server error when saving index fields I am very new to Drupal, so please let me know if I'm doing something wrong.

Using the Search API module, I would like to go change some fields of my Node Index. For example, I would like to uncheck the "Title" field so it is no longer indexed for searching. However, the problem arises when I try to save this or any other change to the fields. I get an error page saying "Your browser sent a request that this server rejected, possibly due to security scanner restrictions." and the fields remain unchanged.

Similar posts have given me the sense that the fix may be to uninstall/reinstall the module. But this module is so fundamental to everything I've been doing over the last few days. If I uninstall/reinstall the module, will it erase everything I've done?

Update: I disabled the server and then enabled it and now the index fields are working (yay) but it deleted my search (boo)

After you disable a module (not 'server' ... as in the "update" part of the question ...) and then enable it again, problems like these might get resolved. There are other situations (and modules) where some similar issues occur, and then get resolved via such disable/enable.

To avoid loosing data (like your search that got deleted), this is a possible approach you may want to consider:

look at the module's `.install) file to find out which table it created (during install).
perform a backup of the tables that are mentioned in the .install file (before uninstalling the module.
disable the module, which will also perform the steps you can see within the .install file (for uninstall now) and then enable the module again.
restore your backup of your tables related to the module.


Services custom GET operation How to create custom GET resource operation? I tried many variants in  hook_services_resources() but didn't find the solution. Is there way to do this?
I want get some data from url rest/coaching/objectives-info and it should be GET request.

I solve this problem by adding new resource with index operation. So the path became 'rest/objectives-info', not he same but suitable.


How do I clean cached paths to modules? I foolishly did this, when updating a module:

# cd /var/www/drupal7/modules
# mv MODULE MODULE.old
# wget <MODULE_URL> -O - | tar xfvz -

After refreshing the module list, I still get the old module's version because, surprise, it found the MODULE.old subdirectory first. Or last. Or whatever.

I can of course do

# rm -r MODULE.old
# ln -s MODULE MODULE.old

but that's a temporary measure at best.

How do I remove these MODULE.old directories? drush cc also tries to access them and won't run if they're not there!

The best way to do this is to disable the module, remove the '.old' folder and then re-enable the module. Unless disabling the module is destructive, this is the course of action I would recommend.

Otherwise you need to call registry_rebuild, though as you've realised you can't do this from a module because your site won't bootstrap. There is drush command made just for this case which you can find at https://drupal.org/project/registry_rebuild

If none of this works, you will need to manually edit the database ; you will need to manually edit the 'system' table and clear the system cache. Not recomended.

Whichever option you go for, make a backup of your database first!


How to add the js files to specfic modules only I am having a module and am adding the js files which is using on the top of the module file as follows :

drupal_add_js(drupal_get_path("module", "notification") . "/js/jquery.js");

But the problem is this js file appear in the whole site and makes things messy . I need this file should appear in the notification module only. Another problem is the by default D6 using the jquery.js (which is an older version 1.2.1) and  by default its taking from the sites/misc path .its taking the old $.browser function and all !! .  And when am including the latest version it makes conflict with the oldest version  . How to solve this ?

It is, of course, not possible. The problem is:

JS files, by the nature of WWW, are added to HTML output
All modules participate in creation of one HTML output
You want to add JS "only to module", but because there is no isolation between parts of HTML output, it's plainly not doable.

To address what you didn't really ask, but probably need to know:

Never just add jQuery on your own. That's pretty dangerous thing to do and pretty much always will mess things up. There is jQuery Update module to address this need. It's not perfect, but way better than anything you will be able to create yourself now - because it was tested by hundreds of thousands.


Does performing $entity->save() on field collection programmatically clears the page cache of it's node host? I am using $entity->save() on a custom hook_cron that runs every minute. Does anyone knows if by doing $entity->save() , Drupal will clear the page cache of the nodes/views/panels housing it?

I know that node_form_submit will clear ALL page caches. Sounds like what you're looking for is something like the expire module.


How do I display a list of nodes that reference a given node on the node content page? I have a central content type that is being referenced by many child content types.  The child content types all have an entity reference field pointing to the central content type.

Now, on the node page, I want to display a list of all the nodes that are referencing this particular piece of content.

It seems I can use Field View to set up a view showing the desired content, and then embed it as a field, but I'm not sure how to pass the value of the currently-being-viewed content to the view in order to make it limit the results properly.

Any advice or other ways to approach this problem?

In your view set up a contextual filter (under 'Advanced') on the entity reference field. Then configure the filter to provide a default value if the filter is missing. Select 'Content ID from UrL'.

When you display the view, it will list the children which point to the page you are currently displaying.


token_filter module: [node:nid] for custom block? Drupal: 8.1.7

Module: token_filter 8.x-1.0-beta1

I have a custom block with a Text format that has Global and entity tokens are replaced with their values enabled.

The custom block has this value:

current-page:url:unaliased :          [current-page:url:unaliased]

current-page:url:unaliased:absolute : [current-page:url:unaliased:absolute]

current-page:url:unaliased:args :     [current-page:url:unaliased:args]

current-page:url:unaliased:brief :    [current-page:url:unaliased:brief]

current-page:url:unaliased:path :     [current-page:url:unaliased:path]

current-page:url:unaliased:relative : [current-page:url:unaliased:relative]

that will render as:

current-page:url:unaliased : http://www.example.com/node/1657
current-page:url:unaliased:absolute : http://www.example.com/node/1657
current-page:url:unaliased:args : , node, 1657
current-page:url:unaliased:brief : www.example.com/node/1657
current-page:url:unaliased:path : /node/1657
current-page:url:unaliased:relative : /node/1657

I am attempting to get the Content Id (e.g. [node:nid]) from the page, but that token is not available.

Workaround using Inline Javascript:

Node Id:

which will render as:

Node Id: 1657

I tried the following:

current-page:url:unaliased:args:node : [current-page:url:unaliased:args:node]
current-page:url:unaliased:args:0 : [current-page:url:unaliased:args:1]
current-page:url:unaliased:args:1 : [current-page:url:unaliased:args:1]
current-page:url:unaliased:value:node : [current-page:url:unaliased:value:0]
current-page:url:unaliased:value:0 : [current-page:url:unaliased:value:0]
current-page:url:unaliased:value:1 : [current-page:url:unaliased:value:1]

Without modifying the module how would I get [node:nid] from within a Custom block?

[current-page:url:unaliased:args:value:1]

gives you the [node:nid] even when called from a block.

As per:

https://www.drupal.org/node/1265010

..."[current-page:url:unaliased:args:value:0] (The first value, of the array of arguments, of the unaliased URL of the current page)."


Hiding a  in mobile only I inherited a Drupal site recently that I'm having a bit of trouble with. Essentially, I need to hide a menu in a mobile view, but still remain visible on a desktop. So far, I've added this to my css file:

/* Mobile Hide */
    @media (max-width: 991px) {
        .mobile-only {
          display:none !important;
          }

          .desktop-only {
            display:block !important;
          }
        }

Using Chrome, when I apply the "mobile-only" class to the div I'm trying to disappear, it works perfectly. The only problem is I have no idea how to actually apply this class to the real div in the server's files. How can I apply this to an actual file in Drupal?

Thank you.

You shouldn't need a specific class to complete this.  Just assign the div to something like

@media (max-width: 991px) {
    #menu{display: none;}
}

If you need to add the class to the div you can use jquery.

$('div').addClass('mobile-only');


Drupal module to generate compressed xml sitemap Is there any Drupal module which can generate compressed xml sitemap like sitemap.xml.gz? The problem is I have a site with a lot of pages and the generated sitemap is very big (more than 1 MB). I have "404 not found" errors in google webmaster tools for the sitemap, but when I open the address mysite.com/sitemap.xml the sitemap is displayed after more than 5 seconds. When I test my sitemap with google PageSpeed Insights it tells me to activate compression and I will reduce the data transfer for this file with 92%.
I activated compression on Nginx and now it is compressing everything but the sitemap.  Now I am searching for a module generating compressed sitemap.
I am usung Drupal 7 with Nginx and xmlsitemap module for generating sitemap

You can separate you sitemap.xml into several sitemaps. Each of this maps will be a smaller than one big sitemap.

Go to admin/config/search/xmlsitemap/settings, in Advanced settings in Number of links in each sitemap page choose, for example, 1000 and regenerate you sitemap.


How to use a drupal footer and header on an external page Sorry if the title is not the best description, it is my first time working with Drupal. My client has a portal created on Drupal 6.22, I'm creating a concurrent website for him, and he wanted to use the same header and footer that is created on the Drupal portal on my area.

So basically I would like to know if there is a include, or reference I can add to my website that would use\compile\something that Drupal header\footer on my layout.

This may be fairly simple (with a couple of caveats, explained below). Treat it as though you were just going to use static files--i.e. so your site can simply include the contents of those files in the relevant *.tpl.php files in the theme.

The meat of the problem is that you'll need to convince Drupal to make those files for you. You can do this by creating two nodes in Drupal on the portal--call them something like 'header-include' and 'footer-include'. Take note of their node ids.

Then, assuming for the sake of demonstration that the two new nodes have node ids 1 and 2, copy the portal theme's page.tpl.php file twice, so that you have two files, page-node-1.tpl.php and page-node-2.tpl.php (see Drupal 6 Template Suggestions for more details). Modify any paths in these files that refer to the portal site.

That done, remove everything from one file except for the code and markup required to generate the header, and everything from the other file except for the code and markup required to generate the footer. Depending exactly how you need to do this, you may need to include the opening html tag and all the scripts etc. for the header, and similarly for the footer.

Clear the caches on the portal site, and you should now have two pages, header-include and footer-include that contain only the basic html code required for the header and footer respectively.

These can be included into the theme on the new site using PHP's file_get_contents() function.

Caveats

There are two points where this can go wrong:

1. Some paths may still be wrong

If there are paths in the header and footer includes that you generate (i.e. paths not hardcoded into the original page.tpl.php file), they will either include the domain of the portal site, or no domain at all. If there are any such, you will need to change how they're output at the portal (difficult), or add the relevant domain to the include at runtime (potentially expensive, though if the resulting pages will be cached, maybe not a huge concern...)

2. Include files may be accessible

This way of doing things makes the include files accessible to anyone on the portal site with the access content permission. How much of a problem this is is up to you and the client, but I don't know of a simple way to exclude them from search results in Drupal 6.