Creating special RSS channels How can I create RSS channels for certain content type or it's subtype (certain taxonomy terms from that content type, so that users can effectively filter the information they need).

thank you

You can build RSS feeds easily with views, after creating your first display (generally a page), you can click "+Add" and add a feed display, then you configure your fields and you're almost done.

In the "Filter Criteria" section you select your Content Types and or the taxonomy you want to target.


print theme_get_setting in php-as-css file I'm trying to print out settings from my theme's theme-settings.php into a file called custom.php. Below is the code I'm using in custom.php:

<?php
    header("Content-type: text/css; charset: UTF-8");
define('DRUPAL_ROOT', '/path/to/my/drupal/installation');
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
?>

body {
    background: url(<?php print (theme_get_setting('theme_custom_background_path')) ?>);
?>;

This is what the result is when the page is rendered in the browser:

body {
    background: url();
}

I'm obviously missing something here -- theme_get_setting isn't working. I'm not sure what kind of code I need to link this file to my theme.

Does anyone know if there is a way to get custom.php to recognize the settings I've defined in my theme's theme-settings.php file with theme_get_setting? I feel like I'm so close but just missing a few lines of code.

At the end of the day if I absolutely need to, I can just print the settings out inline within the head section of html.tpl.php - but I'd much rather include them in a separate stylesheet with the .php extension.

Any suggestions?

Below code worked for me ! Make sure there is a value for setting "theme_custom_background_path" in your theme settings. For example i can able to get logo path of theme using below code

Created a file called get_setting.php inside my Drupal Root
Copy pasted below code
Executed in browser.

Code

define('DRUPAL_ROOT', getcwd());
include_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$theme_settings = theme_get_setting('logo');
print "body { background: url(" . $theme_settings . ");}";


Make node only accesible by path alias I was wondering if it's possible to make nodes without path alias not accessible. By this I mean that visiting /node/$nid/ users will not be able to see its content, but if that node has an path alias (e.g. /myarticle/my-article-name/) the node will be visible using the path alias.

Is it possible to achieve it with code?

By researching, I found that I can do this in hook_menu() with either
 $items['node/%node']['page callback'] = 'drupal_not_found'; or $items['node/%node']['access'] = FALSE;.

The problem is that I can't access with /node/$nid/ and without /myarticle/my-article-name/, it raises permission denied.

hook_menu() is not the hook to alter the routes defined from other modules, but in this case not even hook_menu_alter() would help.

When users access a page using a path alias, Drupal gets the normal path (i.e. the path to which the path alias points) before rendering the page. So, for Drupal, users are always visiting /node/$nid, not /myarticle/my-article-name/. In fact, drupal_path_initialize() (called at bootstrap time) contains the following code.

  if (empty($_GET['q'])) {
    $_GET['q'] = variable_get('site_frontpage', 'node');
  }
  $_GET['q'] = drupal_get_normal_path($_GET['q']);

drupal_get_normal_path() is the function converting the path alias in the internal path.

In this case, a redirect from /node/$nid to /myarticle/my-article-name/ is, IMO, the solution. The Global Redirect module already does that, as the project page describes.

  Checks the current URL for an alias and does a 301 redirect to it if it is not being used.
  Checks the current URL for a trailing slash, removes it if present and repeats check 1 with the new request.

Also, notice the Why? section on that page.

  Once enabled, an alias provides a nice clean URL for a path on a site. However Drupal does not remove the old path (eg node/1234). The problem is that you now have two URLs representing the same content. This is dangerous territory for duplicate pages which can get you sandboxed by the search engines!


Welcome email body not changing to reflect account settings I'm in /admin/config/people/accounts and have changed the text that new users will be sent when signing up accounts, but the body of the messages remain the same, although the subject line is changing, so I know it's having some account. I have cleared the cache many times ;).

I'm using Mailsystem and HTMLmail as well as Profile2... not sure if they would affect these emails.

The password reset email does work, but not the account creation Welcome message.

I have confirmed that user_mail_register_no_approval_required_body is set correctly in the variables table in the database, but that call is never being made.

I'm looking through user.module and user.admin.inc trying to determine how this is all supposed to work. Even changing the hardcoded message in _user_mail_text() (user.module line 2589) hasn't had an affect.

I have a functioning hook_mail in my module so I added the correct key from user.module to that (register_no_approval_required_body) with no luck.

I have tried to regenerate the issue you have specified 'Welcome email body not changing to reflect account settings' in D7. Although, particular use case has not been specified, I have tried all the three scinarios releted to 'Welcome email' here 'admin/config/people/accounts' :

Welcome (new user created by administrator)
Welcome (awaiting approval)
Welcome (no approval required)

Also, 'Account activation' for 'Welcome (awaiting approval)' use case.

but could not regenerate the issue. At the most it can be that you have made changes in one scinario & tried to check in another.

Hope it helps.


Display only the terms in the filter set using Views I have got a view where I am displaying a view in a block.  Basically, I want to display a list of nodes that have a few specific terms associated with it.  So, for example, I want to show all nodes that have one of the following terms (red, blue, green, white).  So, my block should display two fields with the following criteria:

Fields
Content: Title (Title)
Content: Tags (Tags)

Filter criteria
Content: Published (Yes)
Content: Has taxonomy term (or Black, Blue, ...)

Sort criteria
Content revision: Updated date (desc)

My problem is, the result is looking fine, where it is displaying a list of all the nodes that fit the filters.  However, I would only like to display the term in the result set and not all the terms that the node is associated with.  So, right now, this is the what the block looks like:

|Title        |  Tags

|Node 3     |  red, horses, yellow, dogs
|Node 5     | black, white, green, cats, rain, purple

|Node 6     | camel, case, blue

I would like the block to look like this:

|Title        |  Tags

|Node 3     |  red
|Node 5     | white, green

|Node 6     | blue

So, in essence, display only those terms that are part of the result set.  How can I accomplish this with Views?  Any help would be greatly appreciated.

I have played around with the configurations in Views, like @Mohammed Shammem said, and I have gotten it to display only the colors I want.  It is however, still displaying in separate lines despite selecting Group by Title under the Format settings option.  So, now it looks like this:

Tags    Title
White   Node 1
Blue    Node 1
Black   Node 1
Red     Node 1
Green   Node 1

I am close enough, but would appreciate more help on getting the tags in one row.

The relevant screen shots:

I would suggest doing the following.

Instead of displaying all the tags in one line display it in different lines. That is in the multiple filed settings you would choose it to display it on different rows. The result would be something like this

node 3 | red
node 5 | white
node 5 | green

Without the filtered nodes.

Now you would group it with the title field so that it would be displayed together.

To do the grouping you would do the following.

Click on the settings link towards the right of Format :

This would bring up a screen as shown below. you would select the field you want to group from the dropdown Grouping field Nr.1


Cache problem on entity view mode teaser I'm using two slightly different versions of a teaser of a node on two different pages. It's the same fields used for both, but different HTML around each field.

In both cases, I get the renderable array of my node this way :

$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$vars['renderable_node'] = $view_builder->view($referenced_node, 'teaser');

What I would like to have :

Page Node 1
Node 3 teaser version 1
Page Node 2
Node 3 teaser version 2

The problem is when I flush caches, the cache is set for the first time rendering the teaser of my node, but on my other page it render the same version.

Here is what I have then :

Page Node 1
Node 3 teaser version 1
Page Node 2
Node 3 teaser version 1

I looked into ['#cache']['max-age'] but I don't really want to set it to 0 because it's not appropriate for obvious performance reasons.

I see that there is also ['#cache']['keys'], ['#cache']['context'] and ['#cache']['tags'] but not sure what to do.

I ran into the same problem recently.
Adding a key to the ['#cache']['keys'] array as unique id solved my cache problem.
For your case it should be like this :

$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$vars['renderable_node'] = $view_builder->view($referenced_node, 'teaser');
$vars['renderable_node']['#cache']['keys'][] = "page_1";

On your second call to the teaser node then it should be like this :

$view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
$vars['renderable_node'] = $view_builder->view($referenced_node, 'teaser');
$vars['renderable_node']['#cache']['keys'][] = "page_2";


How to fetch form state value of a form on clicking custom button? How to fetch form state value of a form on clicking custom mobile verification(required field in register form) button ajax based suppose I want to show mobile number(Form_state value) of form on clicking ajax based button named mobile verification. Here's the code:

 if($form_id == 'user_register_form')
 {

        $form['mybutton'] = array(
        '#type' => 'button',
        '#name' => 'mybutton',
        '#value' => 'Mobile Verification',
        '#title' => t('Mobile Verification'),
        //'#submit' => array('my_ajax_callback'),
        '#prefix' => '
X
<form action="#">
                        Enter OTP

                        <input type="text" class="otp" name="otp" value="">

                        <input type="submit" class="otp_submit" value="Submit">
                        </form>

',
        '#weight' => 19,
        '#ajax' => array(
                'event' => 'click',
                'callback' => 'my_ajax_callback',
                'method' => 'replace',
                'wrapper' => 'form-wrapper',
          ),
        );

}

function my_ajax_callback(&$form, &$form_state,$form_id) {

     echo '
';
     print_r($form_state);
     die;
   // return $form;
 }

In short i just want without saving form data can we show form_state value on clicking ajax based button in popup form.

The above code not working for me not able to get form_state value

In that case, you can create a container in the form, and fill it with the values after AJAX has been fired. Then you only need to return that container in your ajax callback.

if($form_id == 'user_register_form')
{
  $form['mybutton'] = array(
    // ...
    '#ajax' => array(
      'callback' => 'my_ajax_callback',
      'wrapper' => 'form_state_values_wrapper',
    ),
  );

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

  if(isset($form_state_, $form_state['values']))
  {
    $form['form_state_values']['#markup'] = '
' . print_r($form_state['values'], TRUE) . '
',
  }

}

function my_ajax_callback(&$form, &$form_state,$form_id) {
  return $form['form_state_values'];
}


Create a list of events where an event can have more than one date I am looking to create a view list of upcoming events but where each event may have more than one date as below:

Event 1 - 12th Jan

Event 2 - 12th Feb

Event 3 - 12th Mar

Event 1 - 12th Apr

Event 4 - 12th May

Event 5 - 12th Jun

Event is a content type with a Date field of multiple number values.

Add the date field and then in that fields settings uncheck Display all values in the same row (found in the Multiple Field Settings section).


Add radio buttons and text field together to theme-settings.php I want to integrate a CSS switcher into my theme, but without the Color module. So I want a radio button list, (or a select list, or dropdown, doesn't really matter), with a list of different styles, and then I also wanted a 'Custom' option, so that the user could input a hex code instead of picking a style.

I know how to create a radio list, but how can I add a 'custom' text field too? Any ideas?

And then... what would go in page.tpl.php if the user has selected 'custom'?

I think the select_or_other module is what you are looking for. it let's you create a select box or checkboxes with textfield as last option.


How do I add custom tab in the user profile page? I need to add a custom tab in user profile page. I defined my route like below:

mymodule.routing.yml

mymodule.account:
path: '/user/{user}/custom'
defaults:
  _form: '\Drupal\mymodule\Form\MyModuleUserSettingsForm'
  _title: 'Custom Settings'
  user: \d+
requirements:
  _permission: 'access content'

mymodule.links.task.yml

mymodule.account:
  title: Mymodule Settings
  route_name: mymodule.account
  base_route: entity.user.canonical

mymodule.links.menu.yml

mymodule.account:
  title: My module Settings
  parent: entity.user.canonical
  route_name: mymodule.account

Then after clear cache tab is appearing in the profile page. But when I open the url /user/1/custom I see the page not found message.

Your problem is in the mymodule.routing.yml file, the big problem is the place of user: \d+, this line must be under the requirements: section, the other problem is the indentation. So the final code should be:

mymodule.account:
  path: '/user/{user}/custom'
  defaults:
    _form: '\Drupal\mymodule\Form\MyModuleUserSettingsForm'
    _title: 'Custom Settings'
  requirements:
    _permission: 'access content'
    user: \d+

And of course you need the form class definition in src/Form/MyModuleUserSettingsForm.php

<?php

namespace Drupal\mymodule\Form;

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

/**
 * Class MyModuleUserSettingsForm.
 *
 * @package Drupal\mymodule\Form
 */
class MyModuleUserSettingsForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'simple_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['title'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Title'),
      '#maxlength' => 64,
      '#size' => 64,
      '#required' => TRUE,
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => t('Submit'),
    ];

    return $form;
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {  }

}

And a mymodule.info.yml file to complete your module (in this case named mymodule)

name: My Module
type: module
description: 'My module'
core: 8.x
package: Custom

Reference:
Structure of routes


Modal window open once when user visits website I'm trying to build simple modal window using jquery ui implementation in my custom module. I want to show this modal once when user visit my website. I choose implementation with cookie.
How to make this modal appears once to user when he visit my website? should I use hook_init?

this is my codes:

mymodule.module

/* menu callback */
function mymodule_menu() {
    $items['mymodule-popup'] = array(
        'title' => 'Join Club',
        'page callback' => 'mymodule_ajax_register',
        'page arguments' => array(1),
        'access callback' => TRUE,
        'type' => MENU_CALLBACK
    );

    return $items;
}

function mymodule_ajax_register() {
    $path = drupal_get_path('module', 'mymodule');
    drupal_add_library('system', 'ui.dialog', false);
    drupal_add_library('system', 'ui.draggable', false);
    drupal_add_js($path.'/mymodule.js');

    $output = '';
    $webform_nid = 30;
    $node = node_load($webform_nid);
    $submission = (object) array();
    $webform = drupal_get_form('webform_client_form_'.$webform_nid, $node, $submission);
    $output .= '
';
    $output .= drupal_render($webform);
    $output .= '
';

    return $output;
}

mymodule.js

(function ($) {
$(document).ready(function(){
    $('#popup').dialog({
        height: 'auto',
        width: 700,
        autoOpen: false,
        modal: true,
    resizable: false
    });

    $('a').click(function(){
        var status = false;
        if(this.className !== 'lightbox-processed'){
            if(!getCookie('newspopup')){
                setCookie('newspopup', 'true', 1);
                $('#popup').dialog('open');
            }else{status = true;}
            if(this.className === 'ui-dialog-titlebar-close ui-corner-all ui-state-hover'){
                $('#popup').dialog('close');
                status = true;
            }else{
            }
        }
        if(this.id === 'bottomNavClose'){
            $('#popup').dialog('close');
        }
        return status;
    });

    function setCookie(name,value,days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        }
        else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
    }

    function getCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)===' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }

    function deleteCookie(name) {
        setCookie(name,"",-1);
    }
});
})(jQuery);

with those codes, when user visit myweb.com/mymodule-popup then click any link/url, modal window (pop up window) will appears.

How to make modal window appears once every time user visit my website?

I need advise from you guys, Thanks before.

Why invent a new module while there are existing, well-supported ones?

Two existing modules:

The popup_message does what you want and has a lot of features and a large installed base.
popup_announcement - this is a relatively new module with full html support, but with only a few downloads.


How do I render the absolute URL of a referenced entity in a simplenews newsletter? When I send a node as a simplenews newsletter I use the node's Email: HTML display.
One of the fields in this view is a label of a referenced entity to be rendered as a Link to the referenced entity.
Drupal renders it as a link with a relative / site-local URL. I want it to be rendered as an absolute / external URL.

For what it's worth:
In the render array the link is stored in
$variable['items']['0']['content']['#url'] which is a Drupal\Core\Url with a protected external property of false

I can't see anything in the Url interface that would change external to true or indeed whether this is the thing to do.

external and absolute are different:

external is an url without internal route. You can't change this property. This is set when you create an url.

absolute is an option, which you can set at any time in the url object:

$url->setAbsolute();

Or set to false:

$url->setAbsolute(FALSE);

And this will change how the url is generated absolute or relative.


How to edit image field output from template My goal is to edit the output of a specific field in a view.

There is an image field, and I would like to specify how it is output. So that instead of

I can output something like

I'd like to be able to edit the output freely and just have access to the image path for this specific view.

I am currently editing

views-view-field--com-retheme-home-news--field-image.tpl.php

However I'm not sure how to actually access the path to the image. Using

<?php print $output; ?>

Only prints out what it would have before.

I understand that I could change the field itself to only present the path, however that isn't an option since there is already a lot of content taking advantage of how the field is already setup.

You need to install the Image URL Formatter module

Then in your view, click on your image field and select url as the formatter, so it prints the url rather than the image.

Option A) In the rewrite results field, use the token for your image field.

Example:

Option B) if you want to use the .tpl.php file, put this inside it.

<img src='<?php print $fields["field_image"]->content; ?>' class='yay-we-did-it'>


How to get Views field value in View twig template if the Views field is set to 'Exclude from display'? I have a Views fields twig template where I want to print the Views fields values manually.

For example, using: {{ fields.body.content }}

But this only works if the Views field is not excluded from the display.

Is there a way for me to print Views fields values if they are hidden (excluded from display)?

You shall do it like this:

{{ row._entity.field_myfield.value }}


Access field data in views row template (views 3) So I checked Google for the past 2 hours because apparently something that was fairly simple back in the Views 2 days has changed in Views 3 (D7)... All attempts failed.

I have a view set to display as HTML list showing fields. One of those fields is an image field. I want to use the URL to the image file as inline style background-image on the LI element of the particular row.

In Views 2 I would have set the field to be excluded from display and then created a views template for the row and then used the $row variable to access the field information for the particular row. In Views 3 there only seems to be the $title and $options variable available and $row outputs only the rendered HTML for the whole row.

Long story short: How can I access the field data from inside a views-view-list--myview--page.tpl.php?

If anyone can help out, it is greatly appreciated.

This is pretty simple. All you need to do is go through following steps, which will let you create a same type of view which I have created on my system: The trick is to use relationship from field_image.

Create a simple view of articles (I created page), by default this will have a field_image. I am exporting a view below, import it.
In theme information override style output from "views-view-list.tpl.php". I am attaching code for both.

View:

$view = new view();
$view->name = 'article_view';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Article View';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Article View';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'list';
$handler->display->display_options['row_plugin'] = 'fields';
$handler->display->display_options['row_options']['default_field_elements'] = FALSE;
/* Relationship: Content: Image (field_image:fid) */
$handler->display->display_options['relationships']['field_image_fid']['id'] = 'field_image_fid';
$handler->display->display_options['relationships']['field_image_fid']['table'] = 'field_data_field_image';
$handler->display->display_options['relationships']['field_image_fid']['field'] = 'field_image_fid';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['title']['element_label_colon'] = FALSE;
/* Field: File: Path */
$handler->display->display_options['fields']['uri']['id'] = 'uri';
$handler->display->display_options['fields']['uri']['table'] = 'file_managed';
$handler->display->display_options['fields']['uri']['field'] = 'uri';
$handler->display->display_options['fields']['uri']['relationship'] = 'field_image_fid';
$handler->display->display_options['fields']['uri']['label'] = '';
$handler->display->display_options['fields']['uri']['element_label_colon'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'article' => 'article',
);

/* Display: Article List */
$handler = $view->new_display('page', 'Article List', 'article_list');
$handler->display->display_options['path'] = 'article-view';

Now the overridden template:

<?php

/**
 * @file
 * Default simple view template to display a list of rows.
 *
 * - $title : The title of this group of rows.  May be empty.
 * - $options['type'] will either be ul or ol.
 * @ingroup views_templates
 */

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

<?php print $title; ?>

  <?php endif; ?>
  <?php print $list_type_prefix; ?>
    <?php foreach ($rows as $id => $row): ?>
      <li class="<?php print $classes_array[$id]; ?>" style="background-image:url(<?php print file_create_url($view->result[$id]->file_managed_field_data_field_image_uri); ?>);"><?php print $row; ?>

    <?php endforeach; ?>
  <?php print $list_type_suffix; ?>
<?php print $wrapper_suffix; ?>

This will do the trick for you. Let me know if you face some issues.


What is the purpose of url('', array('prefix' => &$prefix)) in drupal_add_js()? I was looking at the code of drupal_add_js(), and noticed the following code.

  // url() generates the prefix using hook_url_outbound_alter(). Instead of
  // running the hook_url_outbound_alter() again here, extract the prefix
  // from url().
  url('', array('prefix' => &$prefix));

I tried executing the following code, from the Devel module.

dsm(url('', array('prefix' => &$prefix)));
dsm($prefix);

The output was "/dr72/" for the first dsm(), but nothing for the second one.

Looking at the HTML of the front page in my test page, I notice the following JavaScript code.

jQuery.extend(Drupal.settings, {"basePath":"\/dr72\/","pathPrefix":"", /* … */ });

What is the purpose of that code in drupal_add_js() work? How it is supposed to work?

Modules can implement hook_url_outbound_alter() to change to change generated URL's. The most typical example of that are language prefixes.

If you have two languages enabled with path prefixes, english at /en and german at /de, then pathPrefix will either be /de or /en. Since there is no actual API to get that prefix, it uses that trick.

The hook invokes locale_url_outbound_alter(), which in turn invokes the defined url_rewrite callbacks of the enabled language negotation types. In case of the path prefix, that is locale_language_url_rewrite_url which changes the prefix at the end of the function.

The reason for doing this is that it allows ajax calls and other javascript requests (for example the admin overlay) to do that request in the current language, so that strings returned by those requests are in the expected language.


If else for main menu im trying to do a if else statement for the main menu, i have something like this but i dont know where to begin.

<?php if ( !$is_front ) : ?>
function bartik_links__system_main_menu($variables) {
  $output = '';
  foreach ($variables['links'] as $link) {
    $output .= l('<h2>'. check_plain($link['title']) .'</h2>', $link['href'], $link);
  }
  return $output;
}

<?php else: ?>

function bartik_links__system_main_menu($variables) {
  $output = '';
  foreach ($variables['links'] as $link) {
    $output .= l(''. check_plain($link['title']) .'', $link['href'], $link);
  }
  return $output;
}
<?php endif ?>

as you can see i want the tags on the front page and if it isnt then i want the tags to disappear.

Not sure where/when this function is called, but here's your code with some fixes:

function bartik_links__system_main_menu($variables) {
    $output = '';
    $prefix = drupal_is_front_page() ? '' : '<h2>';
    $suffix = drupal_is_front_page() ? '' : '</h2>';

    foreach ($variables['links'] as $link) {
        $output .= l($prefix.check_plain($link['title']).$suffix, $link['href'], $link);
    }
    return $output;
}


White Screen of Death on Cron, fixed with update.php One installation of Drupal has been fine for a long time, but has started developing a WSOD on most (maybe all) cron invocations.

Looking through Drupal's log messages, I see a few normal cron messages, and then this:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, no array or string given in theme_get_registry() (line 277 of theme.inc).
Warning: array_keys() expects parameter 1 to be array, null given in ThemeRegistry->initializeRegistry() (line 413 of theme.inc).
Warning: array_fill_keys() expects parameter 1 to be array, null given in ThemeRegistry->initializeRegistry() (line 413 of theme.inc)
Warning: PHP Shutdown: Argument #1 is not an array in ThemeRegistry->set() (line 457 of theme.inc).

I then see the following repeated many hundreds of times, once for each theme hook, it seems:

Theme <hook name> not found. Warning: array_key_exists() expects
parameter 2 to be array, null given in ThemeRegistry->offsetExists()
(line 421 of theme.inc).

So that is repeated a few hundred times, where <hook name> is every theme hook in the entire Drupal installation.

It has been running a custom theme, but that theme has behaved fine for ages. In fact, I have not made many recent site changes. I've only updated Drupal to 7.52.

Any ideas how to proceed?

Looks like an issue with either a theme hook implementation, or call to a theme function. In particular seems related to theme_block

While it could be something else, I'd suggest making sure you have the file block.tpl.php in your base and sub-theme directories and then clear cache.

Other possibilities are a file permission issue, make sure the files are readable by the webserver


How to hide or keep away /node I want to avoid the URL pointing to a node on my site contains the "node" part (e.g. http://example.com/node/1). Is it possible?

You need the Path module for URL aliases. (It is a Drupal core module.)

Once the module is enabled, you can edit a node, and set a path alias for the node. Now, you can access your node through the path alias you just created.
Drupal will use the path alias you set as URL for the node, except for sub-paths (e.g. node/1/edit).


Changing vertical alignment of teasers to horizontal I use the theme 'Business' and the standard setting of it is that the teasers of the articles I put on the front page are aligned vertically, but I'd like to have them horizontally in blocks of three--next to each other--instead.

Now I would like to know if it's possible to change this, probably by changing some of the css code (If explained in detail I think I should be able to do this, but I'm rather inexperienced..) and otherwise perhaps with a module I haven't found yet?

I'd be very much obliged.

Edit to answer Volker's question:

I create the teasers automatically when I make a new page: In the menu settings there's an option to 'Promote to front page', which I do and then the link, the image and the first paragraph appear on the front page.

I think you'll have to investigate a bit further into your site structure generally. ;)

Assuming that you have content types of articles and basic pages on your frontpage, you could try something like this in your CSS:

.node-promoted {
float: left;
margin-right: 20px;
max-width: 280px;

}

"node-promoted" is the class one of several classes of teasers of articles and/or basic pages promoted to frontpage. You can use the almighty Firebug-Addon for FF to find this out ...


Print title of block group to allow for collapsible group Currently I am working on a site where I need groups of blocks which should be collapsible. The blocks are grouped by using block group module. For the collapsible part I am using collapsiblock.
By default the block group is rendered in a simple div, which I change by applying a template to add the title. But the title is not available as a variable, because block group module uses the title field only for administration and thus the $title variables are all empty.

Does anybody know how to access the variable in a template file?

I'm about to do something similar, but I imagine you could do a preprocess and populate the variable yourself.

-- EDIT --

As a matter of fact, I am sure of it. Just did it myself.

In template.php write a hook_preprocess_region() function.

function mytheme_preprocess_region(&$variables) {
  if ($variables['region'] == 'blockgroup_regionname') {
    $variables['title'] = 'Title';
  }
}

Then just in your template.

<?php if ($title): ?>

<?php print $title; ?>

<?php endif; ?>

Which in turn should make the variable available to whatever else you are trying to do. SHOULD anyway. Good luck!


Why is the recommended release of my module not proposed in Drupal updates? For my contributed module I've previously published several releases without any issue.

Most recent releases were successively 7.x-2.0rc2 then 7.x-2.0 and 7.x-2.1.

As of 7.x-2.1 the following happens:

for all Drupal sites having this module installed with an older release, the admin/reports/updates list doesn't mention the newest release (even after refreshing):

for a site currently in 7.x-2.0rc2 it proposes 7x-2.0
for a site currently in 7.x-2.0 it tells it's up to date

(may be not related but) simultaneously I noticed that the git repository summary doesn't show the labels for the tags corresponding to the 2 new releases, in its Age list

However at the same time:

the project page shows the right last release in Recommended releases (and downloading it gives the right content too)
the git repository summary shows the involved releases in its Tag list

BTW I noticed that some other older releases are also shown in Tag list while missing in Age list, so the git behaviour might not be relevant for this issue

Anynay keep wondering why the recommended release of my module is not proposed in Drupal updates?

Immediately after posting my question, I'd pushed a new 7.x-2.2 release, and it didn't change anything: all involved sites keeped reporting 7.x-2.0 as the most recent release.

But today I noticed that it suddenly changed (without any intervention in git nor in my module's page): now the sites correctly report 7.x-2.2 as the most recent release.

So I tend to think that the response to my question is merely: there is some variable latency in the way Drupal.org makes the information available for the admin/reports/updates/check page underlying mechanism to work.

Moreover it worth mention that also the git Age list now shows all release tags, while some of them were previously missing.


How to find hooks being called by a Drupal page? I am looking at module code, and this is one of my first time working with Drupal modules. How can I find which hooks are being called by the page that I am working on at the moment? I saw this suggestion, but I don't want to hack core like it suggests. I think I might be able to do it with the devel module, but I am not sure how.

Use hook_module_implements_alter and do the drupal set message in here. You'll need to use a FAKE cache for the cache_bootstrap bin.

In your settings.php

if (!class_exists('DrupalFakeCache')) {
  $conf['cache_backends'][] = 'includes/cache-install.inc';
}
$conf['cache_class_cache_bootstrap'] = 'DrupalFakeCache';

I will say that hacking core in this case is the preferred way to do this. The person who wrote that linked article is a core maintainer; so they know what there talking about. Using hook_module_implements_alter with a fake cache backend will only make this fire on the first run of that hook. Additional calls to the hook will not be caught due to the static cache. Not using the static cache would require hacking core in this case.


How to setup custom breadcrumbs with taxonomy? I have content types that use taxonomy to categorize content. The Pathauto url alias structure is 'content type' / 'taxonomy term' For example:

Food/japanese - where food is the content type and japanese categorizes it.

I am using Custom breadcrumbs with great success except for when viewing a taxonomy page at it's alias. breadcrumbs don't work at all. The term does not show up, the parent does not show up, nothing happens. I have the 'custom breadcrumbs taxonomy' module enabled.

I saw that enabling that sub module created a place where I could create a custom path for each term. Technically I could go through and create a path, but I have 100s, if not over 1000 different terms and more added all the time. It would not be possible to use the term.

This would be very easy if I could just specify 'content type' / 'term' like I do for Path auto. One entry could take care of every situation. Is this possible? anyone know how I can configure this correctly?

Not sure if this is the best solution, but you can do that always with theme_breadcrumb() function in your theme like this:

function YOUR_THEME_breadcrumb($vars) {
    $breadcrumb = $vars['breadcrumb'];
    if (count($breadcrumb)) {
        if (arg(0)=='taxonomy' && arg(1)=='term') {
            $term = taxonomy_term_load(arg(2));
            if ($term->vid==YOUR_VOCABULARY_VID) {
                $breadcrumb[] = l('Your landing page', 'landing-page-url');
            }
        }
        return '

'.implode('&raquo;

', $breadcrumb).'

';
    }
}

I'm assuming you're using D7.


Sanitizing Query Results Data In my customized module, I have queried a database value, Jocelyn D. Napiñas. It contains ñ that causes my code to break. Is there any way I can display it? I tried the following code.

$data;  //Contains `Jocelyn D. Napiñas`

drupal_convert_to_utf8($data, 'us_ascii'); //Returns false

check_plain($data); //Returns ''

How will I display it as Jocelyn D. Napiñas?

According to drupal_convert_to_utf8 it required Requires the iconv, GNU recode or mbstring PHP extension to work,  make sure mbstring Php extension installed(Go to /admin/reports/status and take a look at your unicode library) if not installed install it and try again

 drupal_convert_to_utf8($data , 'us-ascii');

if not worked  according to mb convert encoding you can let Php detect encdoing with AUTO, so  use

drupal_convert_to_utf8($data, 'auto');

Also  I can suggest another solution for you

iconv(mb_detect_encoding($data, mb_detect_order(), true), "UTF-8", $data);


Removing cached reference to missing table: services_user? When trying to update user profiles via the Services module (not via drupal) - calling mysite.com/drupalgap/user/1.json as a POST with correct parameters -  I'm getting the following error:

  500 Internal Server Error :  An error occurred (42S02): SQLSTATE[42S02]:  Base table or view not found: 1146 Table 'mydbname.services_user' doesn't exist

I've cleared all my caches but the problem persists. In fact, the cache table rebuilds itself with the a serialized reference to a services_user table in schema row. The line is huge, but here's the part with that reference:

s:13:"services_user";a:3:{s:6:"fields";a:3:{s:3:"uid";a:3:{s:4:"type";s:3:"int";s:8:"unsigned";b:1;s:8:"not null";b:1;}s:7:"created";a:3:{s:4:"type";s:3:"int";s:8:"not null";b:1;s:7:"default";i:0;}s:7:"changed";a:3:{s:4:"type";s:3:"int";s:8:"not null";b:1;s:7:"default";i:0;}}s:6:"module";s:8:"services";s:4:"name";s:13:"services_user";}s:8:"smart_ip";a:5:{s:6:"fields";a:8:{s:8:"geoip_id";a:3:{s:4:"type";s:3:"int";s:4:"size";s:3:"big";s:8:"not null";b:1;}s:6:"ip_ref";a:3:{s:4:"type";s:3:"int";s:4:"size";s:3:"big";s:8:"not null";b:1;}s:12:"country_code";a:3:{s:4:"type";s:7:"varchar";s:6:"length";i:3;s:8:"not null";b:1;}s:6:"region";a:3:{s:4:"type";s:7:"varchar";s:6:"length";i:3;s:8:"not null";b:0;}s:4:"city";a:3:{s:4:"type";s:7:"varchar";s:6:"length";i:128;s:8:"not null";b:0;}s:3:"zip";a:3:{s:4:"type";s:7:"varchar";s:6:"length";i:8;s:8:"not null";b:0;}s:8:"latitude";a:3:{s:4:"type";s:5:"float";s:4:"size";s:3:"big";s:8:"not null";b:1;}s:9:"longitude";a:3:{s:4:"type";s:5:"float";s:4:"size";s:3:"big";s:8:"not null";b:1;}}

I currently have two Services configured. One is drupalgap and the other is my own custom for specialized queries and API needs. I've tried enabling / disabling a variety of resources in both my Service endpoints. Both have session authentication enabled, use a REST server, return json formats, and include a variety of resources including all of those user system, drupalgap_user, and user.

What should i do about this missing 'services_user' table?

That table was added in Services 7.x-3.10; it sounds like one of three things has happened:

You've updated the module but not run the database updates. If you have drush run drush updb, or visit /update.php to go through the process.
You've already run the updates but something went wrong
The table was removed accidentally (maybe by a backup restore)

In either of the last two cases, you can install the table manually with:

$schema = drupal_get_schema_unprocessed('services');
db_create_table('services_user', $schema['services_user']);

or

module_load_include('install', 'services');
services_update_7402();


How do I add an Organic group to my main menu? I have read the documentation for Organic Groups Version 7.x.1.x (is there any more/better?) and created a group type "group content" and a group.

Question (and it may not be an OG question because I am a total n00b) - how do I add a top level menu "Groups" to my main menu? Specifically, what do I add for "path? ?

And then how do I add a group or two as sub-items to that menu?

Thanks a 1,000,000 in advance

I love the new screeencast for OG, it explains it really well.

When you install OG it creates a few "views" that you can use. "OG list" view shows you a list of all the groups (you might have to enable the view if it's disabled).

Then create your menu item "groups" and use "group-list" as the path.

You can add specific "group nodes" to a sub-menu by editing the nodes and using the "provide menu link" feature. I believe not every theme uses submenus, for example Bartik doesn't by default.


How do I delete an orphaned paragraph node? I have a paragraph node which seems to have gone rogue, since it does exist (I found it doing a search using Search API), but it does not appear as content, so I cannot delete it from the user interface.

How can I properly remove it?

In Drupal 8, you can still use entity_delete_multiple(), but it is marked as deprecated and it is going to be removed from Drupal 9.

It makes easy to remove those entities using Drush, for example, with the following code.

drush php-eval 'entity_delete_multiple("paragraph", [$id]);'

Even using code that works on Drupal 9, you would delete those entities in a single command line.

drush php-eval '$storage_handler = \Drupal::entityTypeManager()->getStorage($entity_type); $entities = $storage_handler->loadMultiple([$id]); $storage_handler->delete($entities);'

Replace $id with the ID of the entity you are going to delete. You can also delete multiple entities at once replacing [$id] with an array of IDs.


how to change "username" text located in registration form how i can change "username" text, located in registration form.. i need to change it to "Organization Name" and everywhere of my website "username" text should replace with "Organization Name". How to do it?
Thanks

The way to modify the user registration form is to add a hook_form_alter() function to your theme to change the form variables and add a theme hook to use a custom use-register.tpl.php file. There are numerous tutorials and responses here on stackexchange (for example) that can guide you on this process, but if all you're trying to change is one string, you should try the string overrides module, which allows you to easily replace anything passed through the t() function (ex. "username" --> "organization").


File upload error "Files must be less than x MB" despite file being smaller than x I have a file field called Video for a content type called Tutorial Video.
My settings are thus:

Allowed file extensions:
txt, mp4
Maximum upload size:
[empty]

The maximum upload section also has this text:

Enter a value like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes) in order to restrict the allowed file size. If left empty the file sizes will be limited only by PHP's maximum post and file upload sizes (current limit 100 MB).

When I try to upload a 62MB MP4 video the Video field has (underneath the File Upload button) the following text:

Files must be less than 100 MB.
Allowed file types: txt mp4.

After I select the file and hit upload I get the following error message:

An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (100 MB) that this server supports.

I have requested my host upgrade my limits. They said they have set it to 250mb. I edited my php.ini and changed that to 500mb. I'm lost...

The upload_max_filesize parameter in php.ini (or accessed elsewhere) must follow the file size naming that PHP understands:

upload_max_filesize = 100MB  // NO
upload_max_filesize = 100 MB // NO
upload_max_filesize = 100 M  // NO
upload_max_filesize = 100M   // YES

Also keep in mind that many shared hosts will cap this value at a higher level.  So ask your host and use something reasonable like 25M or 50M - just putting in a ridiculously high value like 500M won't necessarily help you.


i18n translate vocabulary field description I want to localise vocabulary fields especially description field. Does it exist some function like i18n_taxonomy_localize_terms( taxonomy_term_load($tid) for taxonomy_vocabulary_load($vid). Or maybe some different method.

Thanks

You can localize the taxonomy description field out-of-the-box with the Entity Translation module.  While Entity Translation can be used in combination with the i18n suite of modules, note that you cannot use Entity Translation for taxonomy in conjunction with the i18n Taxonomy translation module; you must select one or the other.

If you use Entity Translation, to translate the taxonomy term names you will also need the Title module.


Smart paging rendering pager different from the Devel model I am on Drupal 7 and I have the Smart Paging module enabled. When theming my module, I want the page numbers to appear as regular links. This seems to be the natural behavior. Here is the HTML available on the Devel module on the render section for [smart_paging]:

Páginas

1

2

3

próx ›

fim »

The problem is that the links to the pages 1, 2, 3... are being replaced with a select list box with the options Page 1, Page 2, Page 3. I don't know how to change that behavior and make the links render as... links, exactly the way the HTML is showing.

I am using the Omega theme and I know it is not the theme replacing my pager because if I switch to another theme, the same change is applied to the pager... Do you know where I can configure the pager display? Do I have to go to template.php? Thank you.

I found the solution: go to the Smart Paging settings page and uncheck "Use javascript pager as progressive enhancement for Drupal native pager"... as simple as that...


what is drupal 6's version of hook_user_cancel for drupal7? I'm trying to execute some custom code in drupal 6 after i ban/block a user.  What would be the appropriate way to do this?  I tried using hook_user specifically looking for an 'update' $op when I block a user, but no 'update' operation seems to get passed into my hook, only 'load' gets passed.  I guess the equivalent of this in Drupal 7 would be hook_user_cancel.

hook_user() has an operation for delete, it does however lack an option for ban or block. In this case you should use the rules module and implement a custom action that gets called when a user is banned, the action being in your custom code. There's a few Drupalcon presentations on Rules, Conditions and Actions available on Drupal.org.


Form state redirect to previous page I have a custom form which can be accessed from different places inside the website. The form itself is inside the admin overlay.
When the form is submitted, I want the user (administrator) to return to the place where he accessed the form. The form can also be accessed from within the overlay.
Inside the submit handler I use a form redirect to return but I don't have a clue how to determine the url of the previous page to return to.

// $_SERVER['REDIRECT_URL']?
$redirect = 'set redirect url'
$form_state['redirect'] = $redirect;

If I'm not wrong by default the form redirect the user in the page where it was generate. But, if you want change it you can use the function drupal_get_destination and add it to your action="" simply by changing the $form['#action'] in your code.


Left join query between two custom tables Hi I'm trying to create a join query between two custom tables. One is publish_options with a pubid as the primary key. The other is publish_options_bundles with a referring field pubid to the first table.

The problem I'm having is that the results returned are as such:

Array
(
    [0] => stdClass Object
        (
            [__CLASS__] => stdClass
            [pubid] => 51
            [title] => Promote to blog
            [created] => 1549262900
            [modified] => 1549262900
            [bundle] => article
        )

    [1] => stdClass Object
        (
            [__CLASS__] => stdClass
            [pubid] => 51
            [title] => Promote to blog
            [created] => 1549262900
            [modified] => 1549262900
            [bundle] => gallery
        )

    [2] => stdClass Object
        (
            [__CLASS__] => stdClass
            [pubid] => 51
            [title] => Promote to blog
            [created] => 1549262900
            [modified] => 1549262900
            [bundle] => page
        )

)

I would like it to return like:

(
  [__CLASS__] => stdClass
  [pubid] => 51
  [title] => Promote to blog
  [created] => 1549262900
  [modified] => 1549262900
  [bundles] => [
    page,
    article,
    gallery,
  ]
)

The code I've come with is below.

$query = $this->connection->select('publishing_options', 'po')
      ->fields('po')
      ->condition('po.pubid', $id);
    $query->leftJoin('publishing_options_bundles', 'pob', 'po.pubid = pob.pubid');
    $query->fields('pob', ['bundle']);

    $result = $query->execute()->fetchAll();

Any help would be greatly appreciated as I am completely stumped now.

Thank you in advance.

I found the way to do what I wanted.

The modified query:

    $query = $this->connection->select('publishing_options', 'po')
      ->fields('po')
      ->condition('po.pubid', $id);
    $query->join('publishing_options_bundles', 'pob', 'po.pubid = pob.pubid');
    $query->addExpression('GROUP_CONCAT(DISTINCT pob.bundle)', 'bundles');
    $query->groupBy(['po.pubid']);
    $result = $query->execute()->fetch();

I added the groupBy() methond and the addExpression() method with a GROUP_CONCAT

The results:

stdClass Object
(
    [__CLASS__] => stdClass
    [pubid] => 51
    [title] => Promote to blog
    [created] => 1549262900
    [modified] => 1549262900
    [bundles] => article,gallery,page
)


How to render the same field twice but with different name/id attribute? I have overriden user-register.tpl.php and in it I would like to render same checkbox twice (so that I can submit if either of them have been checked and they are the same I just need to display them twice).

Example:

   print render($form['field_add_option']);

   print render($form['field_add_option']);

But this gives same field with same id with same name which is to be expected. Is there a way to change name and id of field before rendering?

I have tried to change the name like (before the second one)
$form['field_add_option']['und']['#name'] = 'test1';

But the label for and name of checkbox are still the same.

The select element don't have #name atribute (Form API Reference). You can implement the hook_form_alter() in a custom module.

/**
  * Implements hook_form_alter().
 */
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'YOUR_FORM_ID') {
    //here you can make the copy
    $form['field_add_option_copy'] = $form['field_add_option'];
  }
}

You can read this: Creating modules - a tutorial: Drupal 7.x


Slideshow Question - Slider for images uploaded to a node I am building a review web page. I want to be able to upload 3-5 pictures for the product to be reviewed and have those images displayed as a slideshow within the product node. Pictures are uploaded and stored as a CCK field.

I have been able to get the Views Nivo Slider to get to work for my homepage slider, but I'm not sure it if is possible to use it to build a slideshow for fields within the same node.

Is there a way to use Views Nivo Slider to showcase the uploaded images for the product node? If not, can you recommend another slideshow module?

While I haven't specifically used Views Nivo Slider, I have used Views Slideshow to display uploaded CCK images in a view. The trick here is to use Arguments (or Contextual Filters, depending on which Views UI you're using) from the current nid, with a view that is set to display image fields.


Take action on first vote only I'm using Drupal 7 with the FiveStar module to let users vote on a certain node type. When the user votes, I have a workflow rule that grants them some points to reward them for casting their vote.

The problem I'm running into is that if the user votes more than once on a given node, they are granted points again, each time they vote. There is currently no filter to check that they have already voted before awarding the points.

I could use some help building a workflow rule filter that checks to make sure the user has not already voted on the particular node.

Conceptually I would like to query the votingapi table for any records with the given node ID and given user ID and pass only if zero records are returned. But not sure how to do this in Drupal. Trying to avoid hard-coding a query too.

Thanks
BH

No need to hardcode a query. The voting api module provides some helper function for this.

The function you need is votingapi_select_votes($criteria = array(), $limit = 0)

The $criteria parameter takes a decent amount of options.

Here are the options:

$criteria['vote_id']  (If this is set, all other keys are skipped)
$criteria['entity_id']
$criteria['entity_type']
$criteria['value_type']
$criteria['tag']
$criteria['uid']
$criteria['vote_source']
$criteria['timestamp']   (If this is set, records with timestamps
                          GREATER THAN the set value will be selected.)

In your case you really want to pass in the 'entity_id', 'entity_type' and 'uid' to check if the user has voted in that particular content item before awarding him points.

This is the same way we prevent a user from voting multiple times in the same item with Fivestar.

Hope this helps.


drush sql-dump with --gzip from remote to local machine I can use drush sql-dump to get the production db from my remote server and save it to my local machine no problem using:

  drush @site-live sql-dump > /home/backups/my_db_backup.sql

but i want to enable the --gzip option to make the process faster which i've tried with

  drush @site-live sql-dump --gzip > /home/backups/my_db_backup.sql.gz

but i get this error from archive manager in Ubuntu:

  gzip: /home/backups/my_db_backup.sql.gz: not in gzip format

For starters...can i actually use --gzip with sql-dump?

UPDATE: the problem appears to be that "stdin: is not a tty" is being appended to the first line of the file whether it is a plain .sql or a .sql.gz file

Here are few checks you should do:

make sure that your gzip program is in your $PATH (just check if you've gzip command),
disable any drush verbose messages to avoid printing any extra lines from  terminal which could break the compression,
temporary use -vd to check how the command look like (Executing or Backend invoke) and make sure you've --gzip in your argument list, if it's not - you're getting the plain version of it for some reason (so you can redirect to .sql file instead)

If your --gzip is not invoked, even you're specifying one and gzip is configured correctly, then it's probably a drush bug. I think this could depend on PHP version which you're using as I've the same problem with PHP 5.5.


How sensitive is a site's UUID? I have set up continuous integration for a Drupal site. After every git push the site is built remotely from scratch in a Docker container. It runs a site install, sets the site's UUID to import the configs, creates some sample content and then runs Behat tests.

For simplicity I'd simply commit the UUID in a text file and then import it like so:

drush cset system.site uuid "$(< sites/default/uuid.txt)"

The underlying question I have is if it's OK – from a security point of perspective - to commit a site's UUID into a public Git repo? Does that create any vulnerabilities to my site?

Sorry, only after I created the question it came to my mind that the UUID itself already may be present inside a config YAML. And indeed it is. Inside system.site.yml. So, I guess when it's OK to have it printed inside a config YAML – with the purpose to get version tracked – it's no problem to have it inside a text file as well.


How to utilise watchdog or how to debug webform error I have a webform that integrates into CiviCRM such that the webform is used to save data into the Civi system.  The following error is generated when hitting submit (although data is saved in the results tab of the form):

The lease helpful error message in the word - unless you only have one field =/

Any ideas as to how I can decipher which field is causing the issue e.g. use Watchdog or something to see what the query is or why the error is appearing.  I don't have access to the mySQL server logs.

Thanks for taking the time to looking into the issue Jay Chand and Ziftman.

Turns out that if you go into the admin panel in CiviCRM there is a debugging option where you can turn on callback on errors and thus gain more insight into error messages such as the one I mention above.


Drupal Commerce Line Items I want use drupal commerce's line items in the following case.

I have 3 Products. (Product A, Product B, Product C).
I want to add line items to these 3 different products. So Product A will have the following structure.
Product A -> Line Item A-1, Line Item A-2
Product B will have the structure as              ,
Product B -> Line Item B-1, Line Item B-2

Now, This is okay with me. But if I want to add line items to the first level of line items. How can it be possible ?

The case is,
If I want to add 2 Line items to Line Item A-1. So the Product A will have a final structure as,

                              Product A
                      ___________|____________
                     |                       |
                Line Item A-1           Line Item A-2
          ___________|____________
         |                       |
     Child Line Item A-1(i)   Child Line Item A-1(ii)

I hope I am able to tell you my problem. Please help me on this.

Judging from your question you seem very confused about line items and what they are used for.

Line items are used to link products to an order. The whole idea is that some data you want to fetch from the product directly, like it's title, media etc, while some data you need to copy, like the price and sometimes you need to add data, like the address for a subscription and quantity.

The reason you need to copy the price, is that if you ever change the price of the product you want to preserve the old orders which is why you need to store the price for each purchase.

There is nothing technical that will hinder you to create a relationship from products to line items or from line items to line items, but it won't make much sense to do so, and will most likely result in some strange bugs, as line items are used for orders to store info about products, and commerce expects this.


Form altered select field is submitting the wrong values I created a content type in a module called travel_page.

In Drupal, I added a new empty List(text) field called English_side_menu

Now I want to populate the List text dynamically.

I did:

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

  // $english_side_menu_list has been initialed here

  $form['field_english_side_menu']['und']['#options'] = $english_side_menu_list;
  dpm( $form['field_english_side_menu']);

}

Every thing is working fine, except the value that appears for the select once I submit the button, is the rank of the selection instead of the text selected.

Do you have an idea what is wrong in the code?

Thanks.

For dynamic list text no need of form alter for a content type.

You can achieve this goal using Content Construction Kit (CCK) module.

Install this module and configure field as below image

and define function statement like

function _options_english_side_menu(){
    $english_side_menu_list = array('1' => 'value1', '2' => 'value2');
    return $english_side_menu_list;
}

Using this function you can assign dynamic list to list text.


How to optionally redirect to a payment page after adding a node? I want to add an option to the node add form so that the user who creates the node can choose if the node will be " promoted " or not. If the promoted option is selected, then I want to redirect the user to a payment page, so that the option charges can be payed.

Any suggestions about how to do so?

Step 1a: Optional redirect to payment page

Add a Boolean field to each content type for which you want to offer such "Promoted" option, say its allowed options are Yes or No.

Then use the Rules module like so:

Event: After saving a node
Condition: (both conditions must be true)

Entity has field "Promoted"
Data Comparison "Promoted" = "Yes"

Action: Perform a page Redirect to your Payment Page

Step 1b: Limit node access while payment is not completed

To wait for the payment to be completed (and not "submit" the node yet), you could use the Content Access module, and the Content Access Rules Integrations module.

So that "After saving content" (= Event), you "Give 'authenticated user' the permission to 'view own content' for the specific node" (= Action). This additional "Action" can be added is a 2nd action to the same rumle suggested above.

This would be a variation of what is explained in this article also (within "Access Control Customized for Your Needs").

Step 2: Promote the node (after payment)

After the payment is received, you could use that "Event" to trigger another rule, which basically consists of these actions:

Mark the node as "Promoted".
Remove the node access restriction, so that all appropriate roles can view the node.

Step 3: Stop the promotion of the node

If at some point in the future the "Promoted" node no longer should be promoted, then you could use the Rules Scheduler ( a sub-module of the Rules scheduler) to trigger a rule to no longer mark the node as "Promoted.

Note: If you're not familiar (enough/yet) with Rules, the checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.


How to modify the language switcher block to only use the language code instead of its full name? In the Language selection block, I have only the possibility to use the full language name. How can I change it to use the language code, for example FR instead of French?

One possible solution would be to insert this snippet in your .theme file

In this example I am using bartik as a theme.

/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function bartik_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'language_block:language_interface') {
    foreach ($variables['content']['#links'] as $key => $value) {
      $variables['content']['#links'][$key]['title'] = strtoupper($key);
    }
  }
}

Please, let me know if this solution works for you.

Best regards,

Oleg


Send to 403 page if all Selection Rules aren't met for all Variants I have a couple Variants set up for my node type with Selection Rules via Page Manager. If for some reason none of the rules are met for all the variants, it renders the node using the default node system instead of sending to a 404.  How can I send the user to a 403 page instead?

I took care of this using hook_node_view(). This will only run if it is using the node system.

/**
 * Implements hook_node_view().
 */
function mymodule_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'collection' && $view_mode == 'full') {
    drupal_access_denied();
    drupal_exit();
  }
}


How to establish a relation among two content types in drupal 7 Consider there are two CCK's Products and Reviews(reviews for a product) how to relate them?

There can be any number of reviews for a product. Hence i may want to retrieve all the reviews that belongs to a particular product OR Create a Review OR Delete OR Update.

Is there any module in drupal to accomplish this?

UPDATE

I tried this using Entity Reference module

First I created a REVIEWS CCK with the following fields
Name, Email, Review, Rating, Product(This is the Entity Reference, So that it helps to determine the Product to which the review is belonged to).

Products CCk

Product Name, Product Description, Product Cost

Consider there are 3 products A, B, C and i want to review for Product A. I must add all the fields such as Name, email etc and have to select a Product from Drop down

This is Better. But the interesting point is How can i Retrieve all the reviews that belongs to Product A ?

If i create a VIEW to list all the Products i cannot get It's reviews.
Similarly if i create a view to list all Reviews i will get only product name but not its details.

Do any one have any Idea how to solve this?

Many Thanks.

It looks like you need Entity reference module:

  Provides a field type that can reference arbitrary entities

Just add product reference to review content type.


Add a "footer" to each group? I'd like to build a custom "Add more" link under each group by in a view. I'd also need the node ID of the group by field as a token.
Is this possible?

If you need nid of current node as token, then just add Content: Nid in field list, and check exclude from display before saving it. Move this field at the top of the list & you will be able to use it as token in any other field under Rewrite Result.

But if you want to use nid of entityreference field as token, then you need to a Relationship under Advance tab in your view. Then after follow the same process which I explained in first paragraph. But this time you will have to use your added relationship.

For custom Add More link, just add Global: Custom text in field list & put HTML for this Add More link.


Set datetime timezone when posting data via JSON api I'm using core JSON api to POST/PATCH data from an Android App to my Drupal 8 site. When I need to fill a datetime field I use the next JSON, for example, 2020-02-20T13:15:00. But with this format, this time is UTC, but I need Europe/Madrid timezone. How should I do it?

In DateTimeNormalizer, the inferface format is RFC3339, which is Y-m-d\TH:i:sP as an input format string.  It also accepts the ISO8601 PHP string, which is Y-m-d\TH:i:sO

Try using strings like in your request '2020-02-20T13:15:00+01:00'.

What I suspect is happening, is that since you aren't specifying the UTC offset, it is being interpreted as '+00:00'

The denormalizer also allepts a format string with the request to parse the value.  I believe it is called format

See also DateTimeNormalizerTest and EntityTestDatetimeTest for some more examples.


Count results in Views using aggregation Is it possible to count results (e.g. count the nodes of the content type x) in a view, using aggregation (not programmatically)?

Yes, it is possible in Views 3 out of the box.
The idea is the same as in SQL aggregations. Lets see an example:

Edit your view and enable Views aggregations:

Remove default sort criteria.
Add fields “Content: Type” and “Content: Nid”:

Select COUNT function for Content: Nid:

To see what happens just turn on checkbox “Show the SQL query” at global Views settings page.

SELECT node.type AS node_type, COUNT(node.nid) AS nid
FROM
{node} node
WHERE (( (node.status = '1') ))
GROUP BY node_type
LIMIT 10 OFFSET 0

So, we are grouping nodes by node_type and calculating count for this groups.


Passing context to a block field of a display suite node I have a view that displays results of nodes.  In these nodes, I have a block field via Display Suite (a table view from Commerce Add To Cart Extras).  The block View renders fine in a full node display, since I can easily pass the contextual filter, but I need this block field to also render in the node when it's a teaser as a result of a View.

I tried looking at the Views default from context module, but I can't seem to get it.  How can I get my views in my teaser to just know what the context is within its particular node?

I hope this makes sense.

The way to do it:

Enable Views content pane (views_content, part of ctools I think)
Create a Views display using content pane instead of block display type.
Configure a contextual filter, but don't give it a default value.
Configure the content pane "argument settings" to take a node id from url.
In Display Suite, create a "Dynamic field". Move it into one of the layout regions.
Click the cog-wheel icon in the dynamic field, choose content to display, you find your newly created Views display under "Views panes".

Good luck!


Cached variable remains after truncating cache table I updated a row in the variables table to change the value of a variable. Then I truncated the cache table. But a call to variable_get() still returns the original value.

I thought that the variables were cached in the cache table, so where could this original value be hiding?

EDIT: I waited a few minutes and tried again and it was OK. So the immediate problem is solved, but I would like to understand what happened. Is there another layer of caching? It seems there must be since it could not have gotten that value by querying either cache (empty) or variable (containing new value).

Got it - the call to variable_get() was during the bootstrap process, so cache_bootstrap table also needed to be truncated.


Un-promote all other nodes when one node is promoted to front page I have an instance for a specific content type that at any given time there can only be ONE item promoted to the front page. I have a view that looks for this value and displays the item in a block on the front page if it is promoted. The problem is that it is setup to only show ONE item, so the editor has to remember to go and UN-promote any other node after they promote the one they want. I'm trying to figure out a way that when the user clicks the promote to front page check box on the node edit form and saves the node, all other nodes are auto un-promoted. I tried to hook into hook_node_presave, but I can't seem to get the query right to un-promote all the other nodes, because I am using revisions, so I'm not entirely sure what to update.

This is what I have right now that is not working, I think because I am using revisions:

function MY_MODULE_node_presave($node){
  if ($node->type == 'career' && $node->promote == 1) {
    $sql = "
    UPDATE {node} n
    SET n.promote = 0
    WHERE n.type = 'career'
    ";
    db_query($sql);
  }
}

In the views, you can simply sort the view by updated date on filtered promoted nodes. I think this will solve the issue without any custom code. This might not work in all cases. It will fail when content writer promotes a new node, then updates old promoted node.

You can use below code. For your specific case, you can use $base_root to apply the change on a particular site only.

function MY_MODULE_node_presave($node){
  // if $base_root is equal to my.specific.domain.site, then perform the db_update.
  if ($node->type == 'career' && $node->promote == 1) {
    $update = db_update('node')
      ->fields(array('promote' => 0))
      ->condition('node.promote', 1, '=')
      ->condition('node.type', 'career', '=')
      ->condition('node.nid', $node->nid, '<>');
    $update.execute();
    // Do this if you still face the problem. Also please comment if node_revision update was necessary.
    // $update = db_update('node_revision')
    //   ->fields(array('promote' => 0))
    //   ->condition('node.promote', 1, '=')
    //   ->condition('node.type', 'career', '=')
    //   ->condition('node.nid', $node->nid, '<>');
    // $update.execute();
  }
}


Does trusted_host_patterns support sub-directories? My site is installed in a sub-directory:

http://example.com/cms

When I define trusted_host_patterns, the following is OK:

$settings['trusted_host_patterns'] = array(
  '^example\.com$',
);

However, I cannot enforce the host pattern with a sub-directory, i.e.:

$settings['trusted_host_patterns'] = array(
  '^example\.com/cms$',
);

Does trusted_host_patterns support sub-directories?

Those patterns are used to check the host passed in the headers, so they cannot contain a subdirectory, since that is not passed as host. See the code in Request::getHost().

public function getHost()
 {
  if ($this->isFromTrustedProxy() && self::$trustedHeaders[self::HEADER_CLIENT_HOST] && $host = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_HOST])) {
    $elements = explode(',', $host);

    $host = $elements[count($elements) - 1];
  }
  elseif (!$host = $this->headers->get('HOST')) {
    if (!$host = $this->server->get('SERVER_NAME')) {
      $host = $this->server->get('SERVER_ADDR', '');
    }
  }

  // trim and remove port number from host
  // host is lowercase as per RFC 952/2181
  $host = strtolower(preg_replace('/:\d+$/', '', trim($host)));

  // as the host can come from the user (HTTP_HOST and depending on the configuration, SERVER_NAME too can come from the user)
  // check that it does not contain forbidden characters (see RFC 952 and RFC 2181)
  // use preg_replace() instead of preg_match() to prevent DoS attacks with long host names
  if ($host && '' !== preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/', '', $host)) {
    throw new \UnexpectedValueException(sprintf('Invalid Host "%s"', $host));
  }

  if (count(self::$trustedHostPatterns) > 0) {
    // to avoid host header injection attacks, you should provide a list of trusted host patterns

    if (in_array($host, self::$trustedHosts)) {
      return $host;
    }

    foreach (self::$trustedHostPatterns as $pattern) {
      if (preg_match($pattern, $host)) {
        self::$trustedHosts[] = $host;

        return $host;
      }
    }

    throw new \UnexpectedValueException(sprintf('Untrusted Host "%s"', $host));
  }

  return $host;
}


How do I define the block visibility for content types and term pages? I have a block and I want to show it for specific content types and taxonomy terms. There is no common pattern for those pages.

For example, the URLs could be the following ones:

http://example.com/rolling-stones (a taxonomy term page)
http://example.com/drupal/rolling-stones (a Basic node)
http://example.com/rolling-stones-part-1 (an Article node)
http://example.com/demo-content (a Demo node)

I don't want to show the block on the Demo content type, but on nodes of the content types, and term pages, without cloning/replicating the block.

How can I achieve this?

If you control the code for the block, then it really is a simple matter of:

Defining the correct cache contexts (path probably)
In the build method, determining the context (getting current node, tax info from the node, and the like.)
Deciding what to output for the context
If you don't want to display it, return and empty build array (or NULL).

If you don't control the block content (e.g. view or 3rd party module), you can do the same as above and use the various methods to render the block from code.


Prevent Drupal from auto-caching pages in all translations After clearing the cache, Drupal generates cached versions of every node/page that gets visited. Which is fine.

However – if I visit the German version of a node/page, not only the german version will be cached, but also all the translations of that specific node.

(Normally, this wouldn’t be a problem, but I have a custom input filter working which detects the current language and changes things in the text accordingly. This input filter has only access of the current system language, not the language of the currently filtered node. Which leads to wrong results.)

Can I prevent the automatic caching of node translations?

So there is a function called drupal_page_is_cacheable() which you can call, on a site, in order to avoid the caching, so you could for example call that on your uncachable filter.


impossible to save source code in wysiwyg blocks if  does not contains some strings It is impossible to use an icon as anchor  in wysiwyg blocks.

The content is lost when editing back a block

it only works for strings

 some text

If this only happens when a Text format is associated with a WYSIWYG profile, regardless of the format's Text filters or the Editor assigned to it, then try using a non-breaking space (&nbsp;) as the anchor text:

&nbsp;


JS error(s) with Media-7.x-2.0alpha4 and CKEditor I'm working on a production site that is using Media-7.x-2.0-unstable6, File entity-7.x-2.0-unstable6, and Wysiwyg-7.x-2.2 (with the CKEditor 3.6.3.7474 library installed). This is fine for inserting images into content types that have an image field, but I am attempting to upgrade Media to a more recent version that allows for WYSIWYG integration and insertion of images and other media directly into the body field.

I updated a local copy of the site to Media-7.x-2.0-alpha4 and File entity-7.x-2.0-beta1. Clicking on the "Add media" CKEditor button brings up the media browser in the normal way. Selecting an image and clicking on the "Submit" button brings up the "Embedding [filename]" dialog, but clicking on the "Submit" button does nothing. The firebug console shows TypeError: CKEDITOR.instances[this.field] is undefined in line 244 of /sites/all/modules/wysiwyg/editors/js/ckeditor-3.0.js (i.e. return CKEDITOR.instances[this.field].getData();).

I then disabled Wysiwyg and installed CKEditor-7.x-1.16. I still see the same behavior ("Submit" button does nothing), but now the JavaScript error is TypeError: Drupal.wysiwyg is undefined in line 45 of /sites/all/modules/media/modules/media_wysiwyg/js/media_wysiwyg.format_form.js (i.e. if (Drupal.wysiwyg.instances[field.key]) {).

I have disabled almost all contrib modules (except for those required by media and file_entity, and a few other innocuous ones that are required by some of the content fields), and the problem persists.

Since Media-7.x-2.0-alpha4, File entity-7.x-2.0-beta1, and CKEditor-7.x-1.16 on a Drupal 7 clean install work fine in my hands, I have a sneaky feeling that there may be cruft in the database that is screwing things up. However, my JavaScript is on the weak side, and I have no clue how Drupal and JavaScript interact, so I'm not sure where to even begin looking for the problem. Any hints on how I can solve this issue? (short of doing a complete rebuild of the site, which might not be a bad idea, actually...)

Thanks in advance!

For CKEditor: At first glance, it seems that commenting out the following lines in media/modules/media_wysiwyg/js/media_wysiwyg.format_form.js allows the button to work again...

      // Get all the values
      var ret = {};

      $.each($('#media-wysiwyg-format-form .fieldset-wrapper *').serializeArray(), function (i, field) {
        ret[field.name] = field.value;

        // When a field uses a WYSIWYG format, the value needs to be extracted.
        if (field.name.match(/\[format\]/i)) {
          field.name = field.name.replace(/\[format\]/i, '[value]');
          field.key  = 'edit-' + field.name.replace(/[_\[]/g, '-').replace(/[\]]/g, '');

//          if (Drupal.wysiwyg.instances[field.key]) {
//            // Retrieve the content from the WYSIWYG instance.
//            ret[field.name] = Drupal.wysiwyg.instances[field.key].getContent();
//            // Escape the double-quotes and encode it to play nicely within JSON.
//            ret[field.name] = encodeURIComponent(ret[field.name].replace(/"/g, '\\"'));
//          }
        }
      });

  return ret;

Be careful though, this is not a permanent solution as you should never hack core.


Can't send email with Bulk Operation? Drupal 6 site running on remote server.

I created a View of the User type. Then I create a display to show all users of my site.
I set the Style of the display to Bulk Operation and in Selected operations I checked: Send e-mail (system_send_email_action)

In Fields I added the User: E-mail E-mail and other fields

Now I go to the path where I can see my users, I select one user (John) and click in send email under Bulk operation. I continue to complete a send the email and finally I get the message: 1 rows processed in about 23 ms:
Performed Send E-mail on user John.

I understand that the email is sent to John user email from the administration site email.

But I don't receive the email. The email is not really sent.

I have a Webform node in my site which send email with no problems. So, I know there is nothing wrong with my server setting.

Thanks for any help

Just given it a quick test with VBO 1.10, and as you said, emails are not being sent. Also, got "Cannot use %author token in this context." error in log.

See this issue - http://drupal.org/node/1003354 - "Can't sent email (or 'send tokenized email') on a user view. Reverting to 6.x-1.9 works" - seems that 1.9 should work better, or - if dev is acceptable to you - 6.x-1.x-dev

Or use Views Send instead (http://drupal.org/project/views_send)


Retain values during myform_validate() In Drupal 6, I have a custom form validation function, where:

I copy the value from field A to field B, if field B is empty.
I call form_set_error() when the field B contains more than X characters.

Validation works fine, and the error is set. The problem is that the value in field B is not retained when the form is rebuilt: field B remains empty. I want to keep the value in field B after validation (when the error is set) to make it easy for users to edit it down to the right length.

My validation function looks like this:

function myform_validate($form, &$form_state) {
  if (empty($form_state['values']['field_b']['0']['value'])) {
        $form_state['values']['field_b']['0']['value'] = $form_state['values']['field_a']['0']['value'];
      }
      if (strlen($form_state['values']['field_b']['0']['value']) > 260) {
        form_set_error('field_b', 'Text in field b is too long');
      }
    }
  }
}

Any suggestions on how to retain the value in field B when the form is rebuilt?

If you want to set a form value from within your validation callback you'll need to use something like form_set_value. Values that are assigned directly in the manner shown above will not be retained, but that function should do the trick! It's specifically intended for this purpose - setting a form value during the validation phase.

For example:

function myform_validate($form, &$form_state) {
  if (empty($form_state['values']['field_b'])) {
        // Note that the $form array - not $form_state - is used in the first parameter.
        // The second parameter is the value you are setting.
        // Third just pass the $form_state array itself, which will be altered by form_set_vaue().
        form_set_value($form['field_b'], $form_state['values']['field_a'], $form_state);
      }
      if (strlen($form_state['values']['field_b']) > 260) {
        form_set_error('field_b', 'Text in field b is too long');
      }
    }
  }
}


Drupal 8: How to get the ['third_party_settings'] of an image field inside hook_preprocess_image_formatter(&$variables) I have a custom module that requires that I pass variables to my image-formatter template via hook_preprocess_hook(), in this case hook_preprocess_image_formatter().

From within the preprocessor, I would like to acquire $field_display['third_party_settings']['My_Module']

I should be able to do that by exposing the #view_mode and the #field_name of the ImageObject I am preprocessing. I may even be able to hard-code #view_mode = 'full' in which case all I need to do is exposed the #field_name in my processor to acquire the ['third_party_settings']. Any ideas?

EDIT: I forgot to mention that I will be heavily depending on the data that is contained in the image object that is contained within $variables['item'] to acquire the info needed for this. A gist of part of that object can be found at the following url with data containing the field_name: https://gist.github.com/awasson/55ad5da56076e5cb57dd8f3aa68a05f0

Thanks!

Although this is pretty specific, it may help someone else with a similar problem.

The answer is in getFieldDefinition() object of $variables['item'].

In order to acquire the field name of an image object from within HOOK_preprocess_image_formatter(&$variables) which is a variation of HOOK_preprocess_HOOK(), you would use:

$field_name = $variables['item']->getFieldDefinition()->getName();

Used within the context of a module file it would look something like the following:

/**
 * Implements hook_preprocess_HOOK()
 * This allows us to pass attributes to the image_formatter template.
 */
 function MY_MODULE_preprocess_image_formatter(&$variables) {
   // Get the field name
   $field_name = $variables['item']->getFieldDefinition()->getName();
 }


Drupal 7 - Get pages created from custom modules listed under Entity reference field I'm using Drupal 7 Entity Reference field in one of the content types. I want to populate the Auto complete field with pages created using my custom module.

Currently in the options, it is showing only the content types that are existing. How can I achieve this?

why don't you serve regular nodes of a new content-type in your hook_menu callback ? so you could easily reference them !

$html = node_view(node_load(948));


Is there any way to know if a string is not translated? I have my own module that I want to translate to some languages. I use the t function and also I have my lang.po files.

I try to update the lang.po files every time I use the t function but maybe I forget to update some text string.

Is there any way to know if there are some t-strings without translation in the lang.po files?

I can go to admin/config/regional/translate/translate but I only need to check the strings of my module.

Install l10n_client then flush your cache.

If you switch to any other language you'll see a small box with blue bg in the bottom right. Click it and in the left it'll show all translated & untranslated strings. The green ones have been translated, while other ones you'll need to. Just select one and add the translation there itself.


How to make content translation available for front page? On my front page I have a language selector (English / French). The default language is French. The translation works only in the content of page (in the views) i want make the translation work in the front page.

Can someone help me please to do this? I have tried several times but could not get it to work ...

The relative URL to display as the front page is specified within admin/config/system/site-information . If you want to be able to specify a value for it that is different for each of the site's languages, make sure you have made it a "multilingual" variable (it should say "This is a multilingual variable.") in the description of that variable on that page.

Refer to the community documentation about Variable translation for details about how to translate text and settings that are stored in Drupal as variables. Here is a quote from that page:

  The Variable translation module, part of the Internationalization (i18n) package, allows you to translate text and settings that are stored in Drupal as variables. These variables include text such as 'site name' and 'site slogan', as well as settings like 'Default front page' and 'Default 404 page'.

The Variable translation module has a dependency on the Variable module.

And these are the specific steps required to make a variable multilangual (mentioned on that community page):

Enable the Variable translation module included with the Internationalization package
Go to Administration > Configuration > Regional and language > Multilingual settings
Click on the Variables tab
Select the variables that will be multilingual
Click Save configuration button

Obviously, in this case in step 4 the variable to be selected is "Default front frontpage", within "Site information".

Finally, this is what remains to be done (another quote from that same page):

  Once you have the correct settings, they'll be marked with "This is a multilingual variable" when you go to the corresponding administration pages (Figure 2). You must switch the site language while in the administration pages to set the variables for each language. A language switcher link will appear at the top of each administrative page that has multilingual variables.

"That's all" what's needed to specify a language specific value for the frontpage of your site ...


Menu token not working properly I am Using menu token module to access pages related particular user, I am getting issue while selecting path in token menu using replacement patterns. can any one explains on what basis it will take the link and direct to the page. i tried to use [node:content-type:name], As there are so many content types created in my site, so how it will take the specific content type which is related with the node.

kindly suggest me if there are alternatives for this..

Make sure you've chosen the right method under "MENU TOKEN OPTIONS":

With this options enabled, I was able to create a menu item using the token [node:content-type:name]


Commerce: Diffrent text to add to cart button in product list and in product page i try to modify the add to cart button text in commerce so i can have diffrent text in product list and diffrent text in product page.

Is it possible to do this with form_alter?

I tried to use something like node type but no success.

function custom_addtocart_form_alter(&$form, &$form_state, $form_id) {

    if ((substr($form_id, 0, 30) == 'commerce_cart_add_to_cart_form') && $node->type == 'product_display') {
    $form['submit']['#value'] = t('Buy');
    }
}

Thanks

You should be able to use $node->type if you add this first

$node = menu_get_object();

Remember to check if $node is NULL and $node->type is set.

Also if you're wanting to use the "add to cart" hook_FORM_ID_alter() then the function name needs to be something like

custom_form_commerce_cart_add_to_cart_form_alter()


template for a view? I created a view which is viewable at http://mysite.com/branch-locator.   The view is being displayed by my page.tpl.php.  How do I override this and use a new template file called branchlocator.tpl.php to display my view?

How specific do you need to be with the name of your template file? You should be able to create a page--branch-locator.tpl.php that gets picked up by Drupal's auto-detection mechanism. At least, that would have worked in D6 (minus the extra hyphen after page).


Add "webforms like" values to profile.module select list Is there a module that can allow me to add custom values to select list items in the Profiles module in Drupal 6, like webforms does it. For example:

my_value_1 | my_text_1
my_value_2 | my_text_2

which will create a select list

<select>
<option value="my_value_1">my_text_1</option>
<option value="my_value_2">my_text_2</option>
</select>

Try Content Profile module. Using this module you can create user profile where you can add cck fields to the user profile content type.

  This module builds user profiles as content (aka nodes), which opens
  the opportunity to use all the powerful modules for content for user
  profiles too, e.g. the Content Construction Kit (CCK). It's intended
  to be simple and useful, but extensible by further modules.


What could happen if cache_form is stored in Memcache? I have been tuning cache settings for a large site. I updated memcahed settings and set cache_form to be stored in the Database, cache_form started growing and the amount of transactions along with mysql bin logs, and replicator logs started to eat disk space enormously (I have a database about that is ~ 300GB ). Also, the cron is running fine. So I switched back to Memcache. I need to understand what happens when I have cache forms in a volatile cache?
Also, If this is not an ideal solution, what could I do?

Memcache will drop cache content to make room for new cache objects.

That may be a problem if using a single memcache server instance for several cache bins.

cache_form needs to be more persistent to avoid losing form build validation data.

You could have a dedicated memcache server instance/port for cache_form and that would work ok, provided the service isn't restarted. However, in practice, servers need occasional reboot which could cause loss of user form data.

Usually cache_form is stored in the database as it provides the semi-persistent storage required there.

If cache_form isn't working properly, your users will experience "This form has been outdated" and other form validation errors.


How to execute ajax into block view I'm in Drupal 7. I would like to execute an ajax function in my front-page. I've defined the block view in my ".module" file. When I change the selected option, the log gets two errors:

1.

  Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'test_services_search_form' not found or invalid function name in drupal_retrieve_form() (line 842 of /var/www/html/test/html/includes/form.inc).

2.

  Notice: Undefined index: test_services_search_form in drupal_retrieve_form() (line 807 of /var/www/html/test/html/includes/form.inc).

test.module

function test_services_block_info() {
  $blocks['test_services_search_form'] = [
    'info' => t('Plan your trip'),
  ];
  return $blocks;
}

function test_services_block_view($delta = '') {
  $block = [];
  switch ($delta) {
    case 'test_services_search_form':
      module_load_include('inc', 'test_services', 'includes/test');
      $form             = drupal_get_form('test_services_search_form');
      $block['content'] = render($form);
      break;
  }
  return $block;
}

test.inc

<?php

/**
 * @file
 * TEST - File search inc.
 */

/**
 * Implements hook_form().
 */
function test_services_search_form($form, &$form_state) {
  $form['search'] = [
    '#type' => 'container',
  ];

  // Transfer.
  $form['search']['transfer'] = [
    '#ajax'       => [
      'callback' => 'test_services_search_transfer_callback',
    ],
    '#attributes' => [
      'class'    => ['js-select2', 'cancel'],
      'required' => TRUE,
    ],
    '#title'      => t('Transfer'),
    '#options'    => [
      0 => t('Direct trip'),
      1 => t('Stopover trip'),
    ],
    '#type'       => 'select',
  ];

  return $form;
}

/**
 * Callback handler for the direct/transfer trip select.
 */
function test_services_search_transfer_callback($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}

/**
 * Callback function.
 */
function test_services_search_form_callback($form, &$form_state) {
  return $form;
}

The point is disable three fields if option two is selected, It's possible execute AJAX into a block view, and if so, what is going on? Why Drupal is not going into the function of the AJAX callback?

I've defined the block view. When I change the selected option, the log gets two errors.

It seems the error happens after you submitting the block. So the file loads fine on view, but not when the form is processed which should have information where to look for it.

So you should define your form using hook_forms.

  By default, when drupal_get_form() is called, the system will look for a function with the same name as the form ID, and use that function to build the form. If no such function is found, Drupal calls this hook.

Also, when you working with the forms, instead of drupal_get_form($form_id), you can consider using form_load_include() to make sure the include file is loaded whenever the form is processed.

  Use this function instead of module_load_include() from inside a form constructor or any form processing logic as it ensures that the include file is loaded whenever the form is processed. In contrast to using module_load_include() directly, form_load_include() makes sure the include file is correctly loaded also if the form is cached.