In place editor for blocks I'm trying to make certain blocks editable for users with a certain role. I'm looking for a module which would provide an in-place editor for blocks. There's a module for this called Block Edit but there isnt a drupal 7 release. Is there any other module similar to this? Thank you.

There is the Boxes module. Which supports in-place editing.

  Boxes module is a reimplementation of the custom blocks (boxes) that
  the core block module provides. It is a proof of concept for what a
  re-worked block module could do.

  The module assumes that custom blocks are configuration, and not
  content. This means that it is a reasonable action to ask for all
  blocks at one time, this is in fact exactly what the core block module
  does.

  Boxes provides an inline interface for editing blocks, allowing you to
  change the contents of blocks without going to an admin page.

  Boxes provides exportables for its blocks via the (required) Chaos
  tools module. This allows modules to provide blocks in code that can
  be overwritten in the UI.

  Chaos tools is required to use Boxes.

Be sure to look at the module page for full information.


How to create bootstrap subtheme using sass? I am using latest bootstrap version(7.x-3.8) . I want create a subtheme by using SASS but i don't know how to proceed.

Create a New Sub-theme

Copy bootstrap/starterkits/sass folder into sites/all/themes or a respective sites/*/themes folder.
Rename the folder to a unique machine readable name. This will be your sub-theme's "name". For this example and future examples we'll use subtheme.
Rename subtheme/sass.starterkit to match the folder name and append .info (e.g. subtheme/subtheme.info).
Open subtheme/subtheme.info and change the name, description and any other properties to suite your needs.
Download and extract the latest 3.x.x version of Bootstrap Framework Source Files into the root of your new sub-theme. After it has been extracted, the directory should be renamed (if needed) so it reads subtheme/bootstrap.

Compile Sass

Override default bootstrap variables in subtheme/sass/_default-variables.scss.
Edit subtheme/sass/overrides.scss as your fit to properly integrate with Drupal
Compile subtheme/scss/style.scss to subtheme/css/styles.css.

More Information : Read Drupal-Bootstrap Documentation


How to set the facet block title to the currently applied filter? I have a faceted block for the taxonomy reference field.

The faceted block displays the parent terms. When I click on a term in the faceted block then its childs displays in the faceted block. It is fine but the facet block title should be changed to its parent term name.

How will I do this?

I'm not sure about faceted, bacause i've never used it before.
But if page are reloads on click you can use hook_block_view_alter hook the common workflow of using this - get param from url and replace title depends on it.

If page doesn't reloads you can use ajax command, or something similar to achieve what's you need.


Views vs. EntityFieldQuery Why would one use entityfieldquery over views? Is there any benefit to using EntityFieldQuery over using views? Is it the performance benefit? Is it the ease of use of a API? Does it provide you more granularity?

It was recently written that there are several benefits over EFQ, entityfieldquery over other methods:

OOP - EntityFieldQuery provides an object oriented programming approach that allows you to create abstract classes to extend.
Flexibility - An advantaged arised from #1, creating your own objects allows you to modify the entitycontroller to do more things: Store field data via mongo DB, return data into blocks only, etc.

Source: http://chris-on-the-web.blogspot.com/2012/03/drupal-7-views-vs-entityfieldquery-pt1.html


Is it possible to disable the Node module? Is it possible to disable the Node module in Drupal 7?

As I understand from the interface, it is not possible. Why is the Node module is so important? What if I'm going to use only custom entities?

In Drupal 7 the answer is no, it's a piece of functionality built into the system more than required by anything else. I've heard rumors long ago maybe in Drupal 8 it would not need to be enabled by default -- but I'm not sure of that status now.

It's needed for example because it provides paths to content on the site at node/NID by non-developers -- yes Entities can do that. Drupal caters to a wide range of audiences, not just those that understand what a Node is and what an Entity is. In Drupal 8 there may be an install profile which is super minimal to even not include any content types, I'm not sure what happened regarding that ... ah in Drupal 8 they still require the Node module in the Minimal profile installer:
https://github.com/drupal/drupal/blob/8.0.x/core/profiles/minimal/minimal.info.yml

If you want to use entities then use a module like Rabbit Hole to hide any node content and do not use default nodes at all.


Drupal login using other subdomain user account with certain role I'm having a main site and few subdomain sites for different countries:

www.mydomain.com (for U.S users)
newzealand.mydomain.com
singapore.mydomain.com
australia.mydomain.com

For each site, there are roles of anonymous user, authenticated user, member.
Rules module is used to add "member" role if this is an active user, and remove "member" role if this is not an active user.

I'm going to have another subdomain, members.mydomain.com.

Only those users with "member" role in those subdomains are able to access to members.mydomain.com.

In members.mydomain.com, how am I going to retrieve the user login info and user role from different subdomain?

Are you using different databases for all sites? or the Domain Access module? https://www.drupal.org/project/domain

If you are using different databases for each site and if they are on the same server I would consider to let the sites share the users + users_roles table.
In that way all users exist on all of the sites with the same password and have the same role everywhere. You can then assign different permissions to different roles per site.


Making geolocated latitude/longitude values available to computed field in Drupal 7 I'm working on a D7 project where I need to pass a latitude/longitude value from a Location field (acquired from geolocating during import) to a Computed field.

I found the following code in the computed field documentation, which loads the field into the computed field:

$field_info = array_pop(field_get_items($entity_type, $entity, 'field_geo'));

However, if I do a dpm($field_info); all location information is there, EXCEPT lat/long.

Any way around this? Thanks!

I think I was assuming locations are geolocated on edit/changes and that's saved to DB, which appears to not be the case. At any rate, I was able to use the location ID from $field_info to load the location, which then has the lat/long data I need:

$loc = location_load_location($field_info['lid']);
$longitude = $loc['longitude'];
$latitude = $loc['latitude'];

That was annoying...


Apache Sorl Add Custom Term Indexing with Hierarchy My project was have 3 content types with taxonomy, i need to combine all the content types term field values and display with hierarchy.
My fields are :
field_peoples_rits_term,
field_publcation_rits_dev,
field_research_rits_term
I Need combine all these fields as a new field. Thanks in advance

You don't need custom code to achieve this, quoting from here:

  There's a wonderful little checkbox in the Search API workflow tab
  which enables it.

  Head to:

  admin/config/search/search_api/index/your solr server/workflow

  (You'll need to have created a server to get to this.)

  And then tick the box "Index Hierarchy".

  In callback options select the taxonomy field where you would like
  searching for the parent to include the child.


Add some html in a menu I try to add some html in "secondary nav".

A little bit like that :

          MY CUSTOM HTML

First link

Second link

(my menu is not a block).

Do you know how can it be done? By template suggestion or a function for example?

For menus that are printed by invoking theme('links__YOUR_MENU'), you can use the following code and place it in your theme's template.php file:

function YOUR_THEME_links__system_main_menu(&$variables) {
  // Copy here the code from theme_links() function and adjust it to your liking.
}

See the source for theme_links() here.

For menus in blocks, you can do that using theme_menu_tree__YOUR_MENU() override in your theme's template.php file. Here's example code that will work for the main menu:

function YOUR_THEME_menu_tree__main_menu(&$variables) {
  $your_custom_html  = '

your custom HTML

';
  return '
' . $your_custom_html . $variables['tree'] . '
';
}

This will add the content before menu links.


Is it safe to apply last update when a module has several updates available? Have an old Drupal 6 site that has a lot of available updates for modules, core and theme.

When a module has several updates available from the currently installed one to the latest, I understand it's safer to apply them in order. Can I skip this and just install the latest version of the module? Is there a way to know when it's safe, and when not? Visiting updating notes tells about bug fixed, but no info about this. Is there a way to know if the update will make changes to database, so if I have a pre-production and production enviroment, can plan accordingly?

Also for core Drupal updates, I think that in that case applying every update in order is mandatory. Am I right?

I've checked official Drupal information abaout updates, but doesn't state anything about it (it says that you can update multiple modules at the same time, but beware of dependencies between them).

Installing the latest version straight off should be fine in most cases.**

If the module updates only contain minor code changes then there's almost certainly nothing to worry about.

If the module updates contain more major changes such as alterations to the database schema then the module maintainer should be using the hook_update_N() function in a "module_name.install" file which will allow Drupal to determine which updates fall between your currently installed version and the latest version, and apply the necessary modifications in sequence, meaning no breakage should occur. Drupal core is no different to any other module in this respect, so you should also be able to update to the latest core version without any problem.

**If the module has seen a major version increase, for example, you have 6.x-1.7 installed and the latest version is 6.x-3.2, then you should check the module's project page and documentation for any compatibility notes or special instructions for updating. In some cases the versions may not be compatible and would need to be manually migrated, or some dependency may have changed, which the module maintainer should inform you about somewhere.

The only other problem I can think of is the unlikely situation where an API change has occurred in Drupal core at some point and one of your modules was abandoned and never updated to take account of the API change. In that case, you may need to find a patch in the module's issue queue, disable the module, or find an alternative module.

Also, this may be stating the obvious, but if your site is running on Drupal 6, you won't be able to install any module updates with version numbers beginning 7.x- because those are for Drupal 7 and won't be backwards compatible. You'll have to stick to the latest 6.x- version.

Having said all that, you should always carry out a test run of the update process in a testing environment before you go anywhere near the production server. Make sure to clone the live database and all the Drupal files from your production server to your test environment so that you can safely determine exactly what effects the updates will have.


How to set a specific taxonomy with Rules during feeds import? Using Feeds, Drupal creates automatically a Rule "before saving a content imported by feeds".

In my XML file I've got a unlimited value field that goes into one unlimited value field in my content type and I would like to create a rule that populates another field in my content type with one specific term grabbed from the XML field.

i.e
One item in the XML file has got terms:

Fruit, Sicily, Oranges

Another item has got other terms:

Nut, Sicily, Chestnuts

From here I need to grab just Fruit or Nuts.

So I've created two Rules:

The first one checks if the field contains the term Fruit.

Event: Before Saving a node from xml feed
Condition: Data comparision TRUE with term ID of Fruit.
Action: Here I would like to grab Fruit.

The second Rules is similar to the first one, but it checks if it contains Nut.

I've tried to set the Action with Set data value -> Target field node:field-type:Taxonomy(Name) -> Set a fixed value. It does not work.

I would like to know how to set the Action. If it's not possible using Rules, how do I achieve this aim?

Thanks in advance.

Solution

Rules

Before saving a node from xml feeds
Data comparision TRUE with rem id Fruit
Set data value -> node:field-taxonomy-type -> click on "Switch to direct mode input" and it will show the terms for that Vocabulary.


Drupal 8 Theme Header Background Image Upload I'm upgrading the Mayo theme to Drupal 8. For Drupal 7 it worked like this in theme-settings.php with hook_form_system_theme_settings_alter():

  $form['adv_header']['header_bg'] = array(
    '#type' => 'file',
    '#title' => t('Upload header background image'),
    '#size' => 40,
    '#attributes' => array('enctype' => 'multipart/form-data'),
    '#description' => t('If you don\'t jave direct access to the server, use this field to upload your header background image'),
    '#element_validate' => array('mayo_header_bg_validate'),
  );

element_validate in the above called:

/**
 * Check and save the uploaded header background image
 */
function mayo_header_bg_validate($element, &$form_state) {
  global $base_url;

  $validators = array('file_validate_is_image' => array());
  $file = file_save_upload('header_bg', $validators, "public://", FILE_EXISTS_REPLACE);

  if ($file) {
    // change file's status from temporary to permanent and update file database
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);

    $file_url = file_create_url($file->uri);
    $file_url = str_ireplace($base_url, '', $file_url);

    // set to form
    $form_state['values']['header_bg_file'] = $file_url;
  }
}

For the Drupal 8 version I have added use Drupal\Core\Form\FormStateInterface; at the top of theme-settings.php and some changes to mayo_header_bg_validate(). So far it looks like this:

/**
 * Check and save the uploaded header background image
 */
function mayo_header_bg_validate($element, FormStateInterface $form_state) {
  global $base_url;

  $validators = array('file_validate_is_image' => array());
  $file = file_save_upload('header_bg', $validators, "public://", NULL, FILE_EXISTS_REPLACE);
  if ($file) {
    //change file's status from temporary to permanent and update file database
    $file->status = FILE_STATUS_PERMANENT;
    //file_save($file);

    $file_url = file_create_url($file->uri);
    $file_url = str_ireplace($base_url, '', $file_url);

     //set to form
    //$form_state['values']['header_bg_file'] = $file_url;
    $form_state->setValue(['header_bg_file'], $file_url);

  }
}

It does upload the image to /sites/default/files and put an entry into the file_managed table. file_save() is gone for Drupal 8 and I couldn't find a change log showing how to replace it for Drupal 8. 'header_bg' just shows a value of "/" in mayo.settings.

I suggest you look at ThemeSettingsForm, which is where the code lives for the logo and favicon. Doing something similar there would work.

Note that it doesn't save the file, it just uses the file entity that it gets from the widget and puts it in a permanent place using file_unmanaged_copy().

Make sure to keep the conditional, so that you don't get a fatal error when not providing an image (I assume that's the problem with @dmouse's code example).


D8 - Paragraphs - Multilingual - Content Erasing I'm running into an issue on my D8 site where Paragraphs (module) content is erasing from a replicated node when I change the language of the replicated node.

I am using Paragraphs 8.x-1.1, Replicate 8.x-1.x-dev, Replicate UI 8.x-1.x-dev, and Drupal core is a little behind at 8.2.3.

I understand there's some issues with Paragraphs and translating and I found that others seem to have this working, but I'm wondering if there's something small (hopefully) that I'm missing in order to get this working.

A similar thread to mine can be found here regarding deleting the cloned nodes.

Thank you in advance!

It turns out the issue was that I had the "Users may translate this field" checkbox checked for the paragraph field types in my content types. Once I unchecked those I was able to replicate the node, change the language, and the paragraph content did not erase.


Hide some part of node when the field_countdown timer is zero I create a field with field_countdown. Now I want hide some part of my node text when the timer is zero.

For this when I use this code:

{% set a = 'now'|date("U") %}
{% set b = node.field_timer.value|date("U") %}
{% if a < b %}
    Show
{% else %}
    Hide
{% endif %}

Work but not currectly. And in first page send me an error.

  The website encountered an unexpected error. Please try again later.
  TypeError: DateTime::__construct() expects parameter 1 to be string,
  array given in DateTime->__construct() (line 519 of
  vendor\twig\twig\lib\Twig\Extension\Core.php).

In second way I create a field like my field_timer and just show secondes and after my timer show zero IF command work but in this way I add a field and it's not good.

How can I do this with other codes in Drupal 8 ?

You might use twig without method. It will print all configured content to be rendered without the selected fields/properties.

{% set a = 'now'|date("U") %}
{% set b = node.field_timer.value|date("U") %}
{% if a < b %}
    {# Show #}
    {{ content }}
{% else %}
    {# Hide - print the content without the field_timer #}
    {{ content|without('field_timer') }}
{% endif %}

For some cacheability issues it is recommended to always print content.


Will Drupal & Drupal Commerce run under php-cgi? For some specific reasons (experimental setup - not Apache nor nginx) want run Drupal  under php-cgi (not fast-cgi). The site should serve an very-small e-commerce site - probably Drupal Commerce.

Based on my googling Drupal can run under php-cgi, but the found links are pretty old (2009 and such),  so looking for some answers for both of current main versions - for the v7 and for the upcoming v8.

The questions are:

Will Drupal (v7 and/or v8) run under php-cgi?
Will run Drupal Commerce under php-cgi?
are here some major limitations (other than speed!) caused using Drupal (and Drupal Commerce) with php-cgi?

Core in particular, but also Commerce, is extensively covered by automated tests.

Many of those are also run in a style that simulates a users journey, not only unit tests. So if you run those, you will have exercised essentially all relevant code.

There are some things that are not covered though, such as CSS and JS, although I strongly doubt those are affected by how you run the php interpreter.

Setup a Drupal instance, enable the testing module, and execute all the tests. Go read a book (as that will take a long time), and hope that you come back to all green. :)


{{ kint() }} leads to install.php Just on certain pages, I'm led instead to /core/install.php...

This has happened to me a great number of times now, in certain twig templates.  But, I can't imagine why.  Has anyone else had this happen?  What causes it?  It just doesn't work in some templates.  I'm only asking this because I have never seen anyone ask anything like it, and it has happened to a coworker as well.

That will be caused by an overload on resources. kint() is very resource intensive. If you are calling kint in a views-view-files.html.twig template for example then it could get called multiple times and overload the system.

If you check your logs you'll find an error like this:

General error: 2006 MySQL server has gone away

The DB has been overloaded and Drupal thinks there's no install, hence ending up on the install page.

Here are three ways of limiting the kint maxLevels variable which can help avoid this. Set maxLevels to 3 or 4.

1) In settings.php:

require_once DRUPAL_ROOT . '/modules/contrib/devel/kint/kint/Kint.class.php';
Kint::$maxLevels = 3;

2) In /modules/contrib/devel/kint/kint/ duplicate the config.default.php file to config.php and modify this line:

$_kintSettings['maxLevels'] = 3;

3) In a preprocess function, add the following:

kint_require();
Kint::$maxLevels = 3;

You can also filter the kint output so it only shows the KEYS, e.g.

{{ kint(_context|keys) }}

Alternatively, use Symfony var-dumper which is a bit more lightweight:

composer require symfony/var-dumper

Visit the devel settings page and set Symfony var-dumper as the Variables Dumper.

Example usage:

{{ devel_dump() }}
{{ kpr() }}
{{ dpm() }}


Link field to path (automatically pulling Node Id) I have a view "Objects" containing type Object and having fields name and size. I have another view with more features of the Objects called "Details". I set the path of the "Details" view to details/%.

What I want to do is link the name field of the Object in the first View to its details in the latter. In "output this field as a link", what path should I put for it to automatically get that field's Node ID and plug it into the URL so that it goes to its corresponding set of details? Is that not possible? Do I have to link each name manually to its details?

Make sure to have the Token module installed.

Then, to be able to use the [nid] token, you'll have to add a Node ID field and move it before the Node name one to be output as link. The nid field you can Exclude from display.

In the node name field then, set custom path to details/[nid].


Dynamic default values in WebForm Drupal 8.x We are working on our web projects with Drupal 8 and WebForm. Now we have a small problem ...

We have a webform that allows people to sign up for a workout. We would need to provide dynamic dates, so that the exercisers can register at that time.

Starting position: There are different groups that have a workout at different times. There is a fixed number per workout group. That can not be exceeded. People can sign out or sign in.

When a workout group is full, no one can register. Therefore, we must provide a selection of possible dates. This must be reprocessed every day.

Our problem: How can we create a dynamic ad on WebForm before viewing? Using element types, templates, preprocess or any else? Any hints or tips?

You can place a webform anywhere in code, examples are a controller, a block or a preprocess hook in a theme. Put the dynamic default values in #default_data:

/src/Controller/WebformController.php

<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * A webform controller.
 */
class WebformController extends ControllerBase {

  /**
   * {@inheritdoc}
   */
  public function webform() {

    // generate dynamic default values
    $name = 'John Doe';
    $message = 'This content is generated dynamically.';

    // add this to a webform
    $build['form']  = [
      '#type' => 'webform',
      '#webform' => 'contact',
      '#default_data' => [
        'name' => $name,
        'message' => $message,
      ],
    ];

    return $build;
  }

}

mymodule.routing.yml

mymodule.webform:
  path: '/mywebform'
  defaults:
    _controller: '\Drupal\mymodule\Controller\WebformController:webform'
    _title: 'My Webform'
  requirements:
    _permission: 'access content'


Best way to translate parts of an existing site and retain page aliases What is the least complicated way to translate parts of an existing and quite big site (few hundreds of thousands nodes), without affecting the page aliases?

I am aware of different translation systems and would prefer to use Entity translation. Unfortunately, it seems that both Entity Translation and Content translation don't make it possible to retain a functioning URL structure. E. g. I have this now:

Original text's URL (the same pattern should work after translation): example.com/texto-original

After the translation work, it should have this structure:

Original text's URL (the same pattern should work after translation): example.com/texto-original
Translated text (has language parameter in the URL): example.com/en/translated-text

What I want to achieve:

There's a default language (Spanish in this example) that was used for all of the content so far. Those pages don't have language prefix in the URL (e. g. "es/") at the moment. It should stay that way.
Site should always display everything in Spanish, unless a visitor opens an URL with "en/" prefix.
On the pages that are translated, there should be a link "English", "View this page in English" or something similar.
When a visitor opens such page in English, there should also be a link "Español". If a visitor is on the English page - the interface, blocks and other entities (if translated) should be in English as well.

Sorry if I haven't explained well what I want to achieve, I'll try to explain better if something is not clear.

Thank you for any ideas.

I have found the solution and it's quite easy actually. Here are the steps necessary:

Go to languages settings: admin/config/regional/language
Edit the default language (the one that shouldn't have language prefix).
Remove the code from "Path prefix language code" field.
Go to detection options (admin/config/regional/language/configure) and select "URL" method.

That's it, it should work as I have described in the question.


Setting a field on an entity form to be required I have a multi-value entity reference field on a content entity that I am displaying using a custom form class that extends ContentEntityForm, which extends EntityForm, which extends FormBase.

I'd like to set the field to be required: when using this form, you must select at least one entity to reference. I don't want to make this an entity level constraint however, as it's not absolutely required in all circumstances.

In a form alter hook (as well as in my custom form class) I've tried setting things like

  $form['field_myfield']['widget']['#required'] = TRUE;
  $form['field_myfield']['widget']['#required'] = TRUE;
  $form['field_myfield']['widget']['0']['#required'] = TRUE;

Some of these show up when I kint the form after saving it, some are set back to FALSE, but none of these prevent the form from saving when there is no value in my field. But regardless of that, I don't see anything in FormBase, EntityForm or ContentEntityForm that will validate a required element anyway.

Do I really need to create my own validation handler? Or is it something else that I'm missing?

It is really annoying... I struggled with that several times as well. The important key is places deeper in the array. Take a look on

$form['field_ref_download']['widget'][0]['target_id']['#required']


How to avoid _0 _1 when editing a media entity and changing the file? Say I add an image using the built-in Media module.

A couple months later, I have to change the image file for some reason.  So I edit the media entity, delete the existing file, and upload the new file.  The new file has the same name as the old file.

This creates a new file, filename_0.jpg.  How can I cleanly replace the file without adding a new suffix?

Use the Media Entity File Replace module.  This is the exact use case it was created for.


not show any picture in full html ,filtered html mode when i upload or post a link image in article post or basic post not show anything but when i use the img tag and address show image!enter image description here

Based on the comments - try a module that inserts images into the body of a content type.


form submission not working I am just starting out making my module and already running into 2 problems, I believe this is being cause because the form is in a block but I am not entirely sure. This is what I have in my .module file, as you can see I have the function to output the drupal message upon submission however it simply does not do anything. I also get this error when I have the variables in my function.

Notice: Undefined variable: form in zillow_block_view() (line 33

and

Deprecated function: Call-time pass-by-reference has been deprecated in drupal_load() (line 933 of C:\xampp\htdocs\drupal\includes\bootstrap.inc).

function zillow_block_info(){
        $blocks['zillow_block'] = array(
            'info' => t('Zillow Block'),
        );
        return $blocks;
    }

function zillow_block_view($delta = ''){
    $block = array();
        switch ($delta){
    case 'zillow_block';
        $block['subject'] = t('Zillow Block');
        $block['content'] = zillow_form($form, &$zinfo);
    break;
    }
    return $block;
}

function zillow_form($form, &$zinfo){

    $form['description'] = array(
        '#type' => 'item',
        '#title' => t('Get your mortgage rates'),
    );
    $form['rates'] = array(
        '#type' => 'fieldset',
        '#title' => t('Mortgage Rates'),
        '#collapsiable' => TRUE,
        '#collapsed' => FALSE,
    );
    $form['rates']['street'] = array(
        '#type' => 'textfield',
        '#title' => t('Street Address'),
        '#default_value' => 'Street Address',
    );
    $form['rates']['city'] = array(
        '#type' => 'textfield',
        '#title' => t('City'),
        '#default_value' => 'City',
    );
    $form['rates']['zip'] = array(
        '#type' => 'textfield',
        '#title' => t('Zip Code'),
        '#required' => TRUE,
        '#default_value' => "Zip Code",
        '#description' => 'Please enter your zip code',
        '#size' => 5,
        '#maxlength' => 5,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Submit',
    );
    return $form;
}

function zillow_submit_info($form, &$zinfo){
        drupal_set_message('this is the info the form has submitted. zipcode=@zipcode',
        array('@zipcode'=>$zinfo['values']['zip']));
    }

any help is appreciated.

This line is using the deprecated pass-by-reference:

    $block['content'] = zillow_form($form, &$zinfo);

You can fix that with no ampersand:

    $block['content'] = zillow_form($form, $zinfo);

And I think your submit function should be named zillow_form_submit instead of zillow_submit_info.


Can't add js to content creation pages I'm trying to add JS to content create pages using the second function from @kiamlaluno's answer

However, this is not working for me.

I created a module with his folder structure:

add_js
  add_js.info
  add_js.module
  custom.js

add_js.info:

name = Add JS to admin pages
description = Add js to admin pages
core = 7.x

add_js.module:

<?php

    function add_js_init() {
      if (arg(0) == 'admin') {
        $path = drupal_get_path('module', 'add_js');
        drupal_add_js($path . '/custom.js');
      }
    }

custom.js:

jQuery(document).ready(function ($) {
    $("html").addClass("hello");
});

Also tried this .module file:

<?php

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'my_form':
      $form['#after_build'][] = 'mymodule_after_build';
      break;
  }
}

function mymodule_after_build($form, &$form_state) {
  $path = drupal_get_path('module', 'mymodule');
  drupal_add_js ("$path/mymodule.js");
  return $form;
}

Although I am pretty inexperienced still, I did remember to enable the module and flush the caches... :D

/**
 *  Implements hook_form_BASE_FORM_ID_alter.
 */
function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/js/custom.js';
}

In your case would be:

/**
 *  Implements hook_form_BASE_FORM_ID_alter.
 */
function add_js_form_node_form_alter(&$form, &$form_state, $form_id) {
  $form['#attached']['js'][] = drupal_get_path('module', 'add_js') . '/js/custom.js';
}

Note: This will add the JS to all of your content types node edit pages.

If you need to target a specific content type, all you gotta do is add an if statement, see:

How can I find the form ID of a form?

/**
*  Implements hook_form_BASE_FORM_ID_alter.
*/
  function add_js_form_node_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'my_form_id') {
      $form['#attached']['js'][] = drupal_get_path('module', 'add_js') . '/js/custom.js';
    }
  }

and I believe you could alternatively do this, put the my_form_id directly in the hook:

/**
*  Implements hook_form_BASE_FORM_ID_alter.
*/
  function add_js_form_my_form_id_alter(&$form, &$form_state, $form_id) {

      $form['#attached']['js'][] = drupal_get_path('module', 'add_js') . '/js/custom.js';

  }


How to define content within a custom region? I'm new to Drupal and I'm only learning. I'm required to add a custom region to my site. I understand what I must add in the .info file and set from Structure > Blocks to make it show up. What I don't understand is where do I write the content for my "custom region block"?

Say I've a region I want to call "my_region". What do I do to actually define how the "my_region" is supposed to look like?

I've tried various online reference sites and most of them just show me how to do this -

regions[header] = Header

and this-

        <?php if ($page['header']): ?>
        <?php print render($page['header']); ?>
        <?php endif; ?>

I know all that. What I don't know is how to make regions['my_region'] work.

Any references to tutorials or guides would be deeply appreciated.
Thank you

EDIT:

I've set up a region in the info file as regions['my_region'] = MyRegion.
Now I'm clueless as to where to add the contents that goes in regions['my_region'] or any other custom content that I define?

Example: If I want regions['my_region'] to include a slideshow, where do I actually create the file containing the slideshow that regions['my_region'] refers to?

Regions are nothing more than a block holders. To add content to a region, go to http://example.com/admin/structure/block (substitute example.com with your real domain of course), and just drag and drop slideshow block to "MyRegion" region.


How to apply pagination on checkbox options of form elements in Drupal? How to apply pagination on checkbox options of form elements in Drupal?

for example:

$form['display'] = array(
        '#title' => t('Type'),
        '#type' => 'checkboxes',
        '#description' => t('Please Select Type'),
        '#options' => theme('xyz',array($disclaimer_term)).theme('pager'),
    );

Is this possible to limit the number of options of checkbox?

Best option you can do it without checkbox in pagination you can enable module like multiselect widget which work like dropdown with checkbox field.


Failing to create thumbnail, medium and large images When using a new installation of Drupal 7.10, I have set the directory for public uploads to sites/uploads.

When I then add an image to a content instance, I get the original uploaded to sites/example.org/files/imagename.png as expected. However, the other images (thumbnail, medium and large) do not get created at sites/example.org/styles/*.

The directory is readable and writeable by the PHP5-FPM user, and so there should be no issue permissions wise.

Why does this happen? How can I fix it?

Right, the answer is in fact a little more subtle than I realised. Turns out that D7's imagecache replacement needs some attention in your nginx vhost. Without the 404s being sent to Drupal for the missing files, the images are not created - something I didn't realise initially, as I'd assumed they were created on upload.

location @rewrite {
    rewrite ^/(.*)$ /index.php?q=$1;
}

location ~ ^/sites/.*/files/styles/ {
    try_files $uri @rewrite;
}

It needs to be added to your server definition, and you should be ready to roll. Clearly, the path may need altering for your setup, but for mine it was.


How to disallow users from changing their emails? I need this because it makes life a bit more difficult for 'professional' spammers who just change their emails after logging in, so that the can use that very email for the next registration, after being blocked.

Appreciate your hints.

You can either force users to confirm email change or protect the email field from changes.
Both modules have D6/7 versions. Second module can lock password and some other fields as well.


Add a sticky class to node displayed via View How to add class for sticky nodes in Drupal 8, so I can theme views (sticky having different background etc).

I have seen a post that it can be done through Twig, but I cannot understand in which template should I put the lines and frankly...which lines?

You already get the sticky class on views-row in most themes if your Format Show is set to Content.

But if it's set to Fields you can do it through the interface with the help of Content: Sticky at top of lists field.

Add the Sticky at top of lists field from Content Category to your View
Under Output format setting for this field choose Custom and then enter your desired class name into the offered field:
Custom output for TRUE
node--sticky
Custom output for FALSE
[____leave empty____]
Under Rewrite results uncollapse the Replacement patterns and copy the code for this field. It will be something like {{ sticky }}.

Don't enable Rewriting, this step is just to copy the pattern.
Save the Field settings and check the views results - do you see the class name listed for nodes that you know are stickied? If yes then edit the field again and Exclude from display
Under Format: Settings paste the pattern into the Row class input field

You will now have the text you entered for the TRUE sticky state appear as one of the classes next to views-row class.


How do I create content during site installation? As part of Drupal 8 site install/deploy, I want to create content so that the site is functional and ready to use.

For example, whenever I install the site, there should be a home page node created.

How do I create content during site installation?

There are few ways in Drupal 8 to manage site default content:

Default content module allows to export/import content via drush and store the content in the structure similar to config in Drupal core.
Umami profile in Drupal core has a custom importer which loads the content stored in CSV to be important as part of module install.
Migrate CSV plugin allows to important the content from CSV using Drupal core migration API.
Single File Components could be used to provide content with components.


How do I change the date format of a single result? I have a view that gives me a list of nodes titles and when it was last updated.

I want to display the changed date with only time if it is today, otherwise I just want the date, e.g. 17.00 or 15 may 2016.

If I look at the result in views_pre_render it has a node_changed timestamp. It uses the date format set in the view. How do I change the format just for the first result?

You can create a template file and in that you can have and the template files you can get that in

if($view->row_index == 1){
   // do your stuff
}

and put your own condition


Field names returned in search snippet. How to hide? Field names are being returned in the search snippets on my search results page, like so:

  Academic Culture

  Body Text: The academic culture of your host country may be quite
  different from what you experience here at ...

The bit that reads "Body Text:" is the field name. What's weird is that the field name is only returned when the snippet is at the beginning of the field. So, depending on the search it could return something like this:

  Academic Culture

  ... academic culture of your host country may be quite
  different from what you experience here at ...

Note the absence of "Body Text:".

Is there a way to disable/hide field names in the search snippets?

There is usually a view mode for Search results, you can control the field label visibility settings there. See Admin >> Structure >> Content Types >> [Content Type] >> Manage Display >> Custom Display Settings. Activate the view modes for search and customize away.


Rewrite CCK field output without using templates The Views module has the nice option to rewrite the output of a field. This allows to adapt the output of CCK fields using Tokens without having to create a template for that view.

Is there a module that would allow a similar functionality for the "Display Fields" tab of a content type? I need to slightly modify the field output for teaser and body, but don't want to create a full template.

I'm currently using Contemplate for that, but that is more complicated than I need and unnecessary difficult if you're not familiar with the Drupal PHP API. It is also annoying that I need to modify the template every time I add an additional field to the content type, I really only need to rewrite a few fields, not the whole body or teaser.

So, what I would like to have is a simple way to rewrite each CCK field output using any token available for that content type. Does something like that exist?

Sounds like you're looking for the Custom Formatters module, very similar to Contemplate, but specifically for create Field Formatters to be used via the Display Settings page or Views.

Custom Formatters can be built with both Tokens or pure PHP code.

Additionally, Custom Formatters can be exported as native Drupal Hooks or in a custom Features exportable format.


How can I apply changes to user permissions across several sites? I am using Drupal 7, we have a total of 99 different instances of pretty much the same site.  All sites have the user roles of adm_core and mgr_center.

We are currently using drush and puppet to apply changes/updates across sites.

What I'm wondering is if there is a drush command that I can use to just give adm_core the same privileges as mgr_center?

If not does anyone have suggestions on the best method to do this across all sites short of going and changing permissions site-by-site?

I found this snippet for copying permissions from one role to another, which you can easily rewrite to a drush sql command and integrate in your current workflow.


Retrieve hidden field value & expose to .tpl file I have a field collection set up for fields that make up a slider, one of these fields is for the alignment of text in the slider & is hidden on output. I'm trying to get the value of this hidden field & use it to set a CSS class in the .tpl file, I've managed to do this but only in the .tpl file itself. If I understand it correctly it's best practise to get the value of this field in a preprocess function & expose it as a variable to the .tpl file, I'm unsure how to do this.

This is what I have written in the .tpl.php file, and it works, but from what I understand it's not best practise.

$key = key($items[0]["entity"]["field_collection_item"]);
$alignment = $items[0]["entity"]["field_collection_item"][$key]["field_image"]["#object"]->field_alignment["und"][0]["value"];

I'm using the Drupal module fences to modify output so the code above is in the field--fences-xl-slider.tpl.php file.

That could potentially break and it's pretty gnarly looking, so not the best, but I've been there!

Instead if you have the field_collection_item's ID you can do:

// I'd make a more meaningful name... like slider?
// If I understand your example, this should give you the entity Object for the field_collection_item
$entity = array_shift($items[0]["entity"]["field_collection_item"]);

$field_image_data = field_get_items('field_collection_item', $entity, 'field_image');
// I'm less sure here, it looks like the image is an entity and it has sub-fields?
// You'll probably have to dig through $image to see where the entity is kept, I'm guessing
$field_alignment_data = field_get_items('file?', $field_image_data[0]['#entity'], 'field_alignment');

// Now you should be at your field
// If safe_value exists, use that.
$alignment = $field_alignment_data[0]['value'];

This is annoying, but more legible. It's what happens when you have nested data objects, things just get kind of annoying.

The other option is you could make it a field that isn't hidden and use hide('field_alignment') in the tpl.php or template_preprocess_* function (guessing it'd be template_preprocess_entity?)


How to view the user's status? I copied the twig file from the user view in my theme.

I want to display:

"Online" if the user is logged in.
"Absent" if the user has not had any activity for more than 15 minutes.
"Offline" if the user is disconnected.

How to do this with twig ?

{#
/**
 * @file
 * Default theme implementation to present all user data.
 *
 * This template is used when viewing a registered user's page,
 * e.g., example.com/user/123. 123 being the user's ID.
 *
 * Available variables:
 * - content: A list of content items. Use 'content' to print all content, or
 *   print a subset such as 'content.field_example'. Fields attached to a user
 *   such as 'user_picture' are available as 'content.user_picture'.
 * - attributes: HTML attributes for the container element.
 * - user: A Drupal User entity.
 *
 * @see template_preprocess_user()
 *
 * @ingroup themeable
 */
#}

    {{ content.user_picture }}
    {{ user.label }}

    {% if logged_in %}
       En ligne
    {% else %}
       Hors ligne
    {% endif %}

The preceding code displays the status of the current user.

For example for comments I want to display the status of the author of the comment (not the node). I have this line of code in the comments twig file.

Can I reuse the code to obtain the status of the author of the comment ?

{{ drupal_entity('user', comment.uid.target_id, 'comment') }}

You can't know if the person is behind its pc, reading the website but you can know the last access of the user (last time he done an http request to the site I suppose, load a page, submit a comment, etc, but I'm not totally sure about that). You need to look the property "access" of the UserSession.

For example, for the current user, the code is:

$session_current_user = \Drupal::currentUser()->getAccount();
$last_access = $session_current_user->getLastAccessedTime();

The property is a timestamp. You need convert if you want display it on you're site. So, you can now calculate when you considere your user Absent and determine after how many time you considere your user Offline. You can do all these calculation in your template.php file and used your results in your twig file.


Adding fields to user registration form for admins I use the Entity Registration module and I created a registration form for specific events in a Drupal 7 site. For the registered users, the fields are name, surname, birth date, upload administrative files etc.

Is there a way for administrators to have specific fields they can fill and that are not available to registered users?

You could use hook_form_alter to accomplish this

yourmodule_regform_alter($form, $form_state) {
    global $user;
    if($user->uid!=<whatever>) {
        unset($form['field_attended'];
    }
}

If you want to use permissions, you could create your own with hook_permission

function administer_attendee_permission() {
    return array('set attendee status' => array(
      'title' => t('Set status for event attendees'),
      'description' => t('Set the status for event attendees'),
     );
}

Then your form alter changes to

yourmodule_regform_alter($form, $form_state) {
    if(!user_access('set attendee status') {
        unset($form['field_attended'];
    }
}


How to update current url of view page so that it will filter correct result? I have created view to search nodes of video from content type channel. I have set the URL as channel/%/search in view. when redirected to the page the the URL will be channel/all/channel-search?title=test. But I want to replace 'all' with 'nid' which I have got by php code. In short I want to replace channel/all/channel-search?title=test with channel/*NID*/channel-search?title=test (nid may be anything channel/26). I have written the code in views contextual filter but it is not working.

$path = $_SERVER['HTTP_REFERER'];
$filter = preg_replace('///','',parse_url($path,PHP_URL_PATH),1);
$path = drupal_lookup_path("source", $filter);
$node = menu_get_object("node", 1, $path);
$nid=$node->nid;
return $nid;

Add a new contextual filter, select 'Node: Nid', then check 'Provide default value' and in the select box choose 'Content ID from URL'


How to do core development with composer-based install? I'm using drupal-composer/drupal-project.

With that, installer-paths in composer.json installs core in web/core, it doesn't clone a full git repository.

I'd like a full repository, so I can reroll a patch for core on my dev site, within the project it will be used on, without having to clone https://git.drupal.org/project/drupal.git and configure an entirely new project…

Is this even possible?

i.e. a modification to composer.json that will install core (or anything else for that matter) as a fully functional repository (i.e. with .git directories) - so you can create new branches, run diffs against to generate patches, and so on.

I'm providing an answer to this even though it's probably off-topic and I have a heavy bias here.
For core development we shouldn't use a composer-based install pattern such as drupal-composer/drupal-project because we're modifying the software project itself. Generally composer require or create-project or init is used when we want to create a new library, project or piece of software and dependencies to it, but not when working on an existing library or framework.

At the moment the best way to get started if you are new to core development is to visit https://drupal.org/tools. Use either the ResilioSync option or download the latest quicksprint tools release instead. This is the tool set that the Core Mentoring program currently uses to get started from scratch.
This isn't the only place/work flow for core development. Many of the core/strategic initiatives, or working groups within core development, may have a preferred development environment. For instance the Javascript Modernization Initiative has excellent documentation for their unique work flow and challenges.
Of course, if you already have an environment, then cloning the repository and running composer install works as well.
Finally if Composer piques your interest, the Composer Initiative (this is probably only relevant from 2019-2021) may change the way that we can work on core. And this could be a way to contribute and answer your question.

Please ask any questions you might have in #contribute on Drupal Slack or in one of the contribution channels on either IRC or Drupal Chat.


Create categories with their own teasers and sliders I'm new to Drupal. First look at my site's structure:

Homepage

slideshow carousel - displays only selected nodes from the whole website
menu - displays links from a menu created for homepage
teaser - currently displays "promote to front page" items
footer - common to all pages (may be menu or site map)

Category

slideshow carousel - displays selected nodes only from current category
menu - displays links from a menu or subcategories with their nodes
teaser - selected nodes only from current category
footer - common to all pages (may be menu or site map)

Article

no slideshow
no menu
path to article (category breadcumb)
article title and body
footer - common to all pages (may be menu or site map)

How to divide website into categories as mentioned above?

Which modules to use? By default Drupal has Taxonomy module. Is it enough?

The simpliest way is to create custom templates like html--front.tpl.php, html--node--17.tpl.php, html--taxonomy--term--4.tpl.php, etc. but it's not flexible way. If you want to add more categories, you have to prepare another .tpl.php template.

What's the best and simple way to achieve this functionality?

More explanation:

Slideshow carousel is currently Slideshow:View module that displays all nodes with custom boolean field "promote to slider". Teaser on homepage works but I have no idea how to display it on category pages and even how to implement categories in Drupal. Any idea?

I would recommend a content type for the slideshow and the article. For the categorization do you use taxonomy and Views for filtering and sorting.
I can recommend https://www.drupal.org/node/394094


How to add default text to CKEditor? I am using CKEditor and I want ,when creating a new node, in the textarea of CKEditor to add some default text every time a user tries to create a new node.
How can I do that?
thanks

When you setup a node field, there's a default value in the form.

Simply write down the default value there, and each time a new content is created, this field will be loaded with that default value.


Stage file proxy - website under shield I want to retrieve some images from my website to my local Drupal website but my website is under .htaccess password protect so I need to enter a username and password to login. I know the password and username but when I try to get the images through stage file proxy it doesn't work and it's probably because the website is under shield. What should I add in my settings.php file in order for stage file proxy to go through the shield?

See module's INSTALL.txt file:

  If the site is using HTTP Basic Authentication (the browser popup for
  username and password) you can embed those in the url. Be sure to URL
  encode any special characters:

  For example, setting a user name of "myusername" and password as,
  "letme&in" the configuration would be the following:

  $conf['stage_file_proxy_origin'] =
  'http://myusername:letme%26in@example.com';

Another way, if you have a static IP, is to bypass the Apache auth for certain IP addresses.


Drupal Commerce Custom Line Item Types without a Product Reference Field Let me start by saying I am aware of this module: https://www.drupal.org/project/commerce_custom_product

This module works great for custom line item types that need to reference a product, however (correct me if I am wrong) this module can't be used to create custom line item types that do NOT reference a product.

I need a custom line item type, that doesn't reference a product. Which lead to the discovery of this:

http://cgit.drupalcode.org/commerce_examples/tree/line_item_example/line_item_example.module

Utilizing hook_commerce_line_item_type_info() I am able to successfully create a custom line item type, and have it automatically come with the Unit and Total price fields automatically.

All is well so far...

Now if I use the Drupal UI to add a custom field (e.g. an entity reference field, not a product reference field) to this custom line item type, I am able to do this without issue. I can add as many fields as I want.

Now for the problem...

However, when I use the admin order form and try to manually add this custom line item type to an order, the custom field(s) don't show up in the form.

I see from the documentation that I could implement the configuration, add_form and add_form_submit callbacks. But I figured any fields added through the UI would automatically show up on the form(s).

What is going on here? Must I implement the form code-side for all fields on the custom entity type?

A line item must have a product associated with it. Rules, Commerce Cart, and Commerce Shipping all depend on having the commerce_product field on a line item object.


Page title module fallback problem I'm using the Page Title module to set the <title> tags on nodes, etc.
I'm using the [current-page:page-title] token in my patterns.

According to the manual, this should let me write a custom page title on node level.

  This allows some nodes to 'inherit' the title from the node title and other nodes have the option to override the [page-title] token.
  [...] in this case, the author could override the node title and provide a separate page title [...]. Note that this field does not allow the admin to completely override the Page Title, but just the [page-title] token, which will be inserted as normal into the Pattern for that node type.

And the manual also says:

  So, basically, if you use the [page-title] (or [current-page:page-title] in Drupal 7) token in the patterns/template settings, it will take it's value in the following order:

  the value of the "Page Title" field.
  the Entity Title (eg, Node Title, User Name or Term Name), if Page
  Title field has no value (in 1).
  the value of the title returned by Drupal's "get title" system (i.e. a fallback). This is usually defined by the Menu API system.

However, when the pattern is set to [current-page:page-title] and I do NOT write anything in the Page Title feed on node level. Then the node gets no title at all. It doesn't fall back to the pattern: It simply doesn't get any title.

Have I misunderstood anything?

You need to choose a specific token context from those available such as [current-page-what?]:

[current-page-number]   The page number of the current page when viewing     paged lists.
[current-page-path] The URL alias of the current page.
[current-page-path-raw] The URL alias of the current page. Warning: Token value contains raw user input.
[current-page-title]    The title of the current page.
[current-page-url]  The URL of the current page.

You should specify your fallback global page titles under '/admin/settings/page-title' and for specific node types, such as 'story' 'page' or 'blog' for example.

You should input the page title tokens as follows;

Example 1:  [current-page-path] [page-title]
Example 2:  [page-title] | [site-name]
Example 3:  [page-title] | [site-slogan] - mysite.com

Note that you can insert symbols or text between the tokens or after.  In this case we've inserted the vertical bar '|' and a hyphen '-' plus the site name 'mysite.com' within the pattern.

I think you've understood correctly.

Although the example above relates to Drupal6, I've tried to recreate your problem in Drupal7 and can't because the default [current-page:page-title] | [site:name] always kicks in, as it should.

Have you tried completely removing the Page-Title module, running Cron, updating the database and installing the module again?


How can I use configuration management to "snapshot" config on my dev server while I try new things out? I was a heavy Features module user in Drupal 7 so I'm trying to use Configuration Management in Drupal 8 to recreate my old workflow.

In Drupal 7, when I wanted to try making changes, I would:

Add my current config to a feature (store the values of variables with Strongarm)
Export the feature.
Commit the code.
Mess around with the variables and see if I like my changes better.  If yes, update the feature.  If no, revert the feature.

The key to this workflow was that I was storing the config in code on the same dev server that I was using; in other words, I wasn't syncing between two servers, but rather using the Features module to store a snapshot of a working configuration while I made changes that would potentially need to be reversed.

I see that I can use Configuration Management to export configuration, but this is in archive format, which isn't very easy to diff.  Also, committing a bunch of archives to my git repository seems like the wrong way, and a big step backward from Drupal 7.

My question: In Drupal 8, is it possible to export configuration such that it can be committed to a git repo, then diffed and used as a "reset button" when making changes that go awry?

What I tried

In the Configuration Management documentation, it has the following solutions:

UI-based
Drush-based
File--system-based

But what I'm looking for is code-based.  I thought this might be "file-system-based", but these files are in the /files directory, which is usually exempt from git by the .gitignore file.

I would suggest to only use features for reusable components between projects. The configuration management system works quite well for me for the workflow that you are suggesting.

To export all configuration to a directory (by default ./sites/default/config)

$ drush config-export # or use the alias: drush cex

This exports your active configuration into a bazillion files, then you can add it to git as usual:

$ git add -A sites/default/config # -A includes deleted and new files
$ git commit -m "config: my config changes here"

Now you have your snapshot, you can play with your site and if you end up in a state that you are not happy with, you can always import your exported files back to the active configuration by

$ drush config-import # or the shorter: drush cim

You can also use drush config-diff name.of.config to see the differences. Or you could just export again and git diff them

If you like your new configuration better, you can just start again: export, commit, repeat.

This is also useful to push your configuration to your test server. You just need to deploy the new code with the exported configuration and import it with

$ drush @stagingsrv cim

For some advanced cases check out the config_devel module


How to map path aliases when migrating from Drupal 6 to 8? When migrating from Drupal 6 to 8 i can simply map path aliases with the mapping:

process:
  path: alias

I have the problem that the path alias is not set properly when pathauto is activated for a node-type. The alias always gets generated automatically instead of using the old alias. How can I override this behaviour?

You need to explicitly disable pathauto in your migration:

process:
  path/alias: alias
  path/pathauto:
    plugin: default_value
    default_value: false


How to add a placeholder to a form element using a twig template override I enabled twig debug and realized I needed to add block--search.html.twig to my theme.
Then I used dump(content) to see if I could add a placeholder to search input field

{% extends "core/modules/block/templates/block.html.twig" %}
{% block content %}
  {{ dump(content) }}
  {{ content }}
{% endblock %}

How can I change the content array and add a new '#placeholder'=>'bla' to the search input?

dump(content) returns something like this:

array (size=23)
  '#action' => string '/search/node' (length=24)
  '#method' => string 'get' (length=3)
  'keys' =>
    array (size=26)
      '#type' => string 'search' (length=6)
      '#title' => string 'Search' (length=6)
      ...

Altering forms in Drupal 8 is the same as in Drupal 7 - you have:

hook_form_alter()

  Perform alterations before a form is rendered.

hook_form_FORM_ID_alter()

  Provide a form-specific alteration instead of the global hook_form_alter().

Always use an alter/preprocess hook to change variables before they get to the template file, it's bad practice to change them once you're in the template file itself.


Why does #triggering_element pick the wrong element? I'm triggering an ajax-enabled button on a form but Drupal's setting $form_state['#triggering_element'] to the wrong element.

The button is a child of a #tree and is identical to other buttons in other tree-ed structures, except for its parents. But I thought this was the point of #tree.

Looking at the drupal code in form.inc it's clear that Drupal only goes on the #name property to identify the triggering element, which is automatically set to 'op' for buttons. This seems to have no idea about trees or the element's parents.

The rather scant and very old docs for tree state:

  #parents is used to create the name/ID of the form element itself.

But my button element's names are not being set to anything other than 'op'. I'm creating the buttons in a #process function for the parent element.

Example code

$form['group1'] = [
  '#prefix' => '
group1',
  '#suffix' => '
',
  '#tree' => TRUE,
  'trig' => [
    '#type' => 'submit',
    '#value' => 'ajax go',
    '#ajax' => [
      'callback' => 'mymod_ajax_callback',
      'wrapper' => 'foo',
      ],
  // Other elements part of group 1...
  ],
$form['group2'] = // The same.

A work-around is to code creating unique names for every one of these elements, but I feel I might be missing a trick/nuance?

The problem is in form_builder() where it fallbacks to the first button if no button can be found.

A comment from form_builder():

// Therefore, to be as consistent as we
// can be across browsers, if no 'triggering_element' has been identified
// yet, default it to the first button.
if (!$form_state['programmed'] && !isset($form_state['triggering_element']) && !empty($form_state['buttons'])) {
  $form_state['triggering_element'] = $form_state['buttons'][0];
}

More info can be found here: https://www.drupal.org/node/2546700#comment-11164091

There is also a patch for this problem that can be found in the link above.


Displaying HTML entities in title through a view I have a site (D7) where I need to have HTML entities in the title like the copyright, trade mark signs with the subscript tags. Like:

Product name®

The solution at the node level is simple using the page.tpl.php:

<?php print html_entity_decode($title); ?>

But in a view no matter how I try to format the title it will always return it like

Product name<sup>&reg;</sup>

I try a formatter, but they don't reach the title. Any other ideas?

Yes! You need to add the attribute 'html' => true. This is a link property in Drupal 7. If you render any link in Drupal 7 and want to add some extra HTML inside it you need to set array('html'=>true).


Change image background colour when cropping Is it possible to change the black background colour to another colour (e.g. white) when cropping an image that is smaller than the crop size?

I'm using the "image styles" settings in Drupal 7 to first scale the image to the correct width and then cropping to get the desired height. This results in some of the images having black borders that really don't look nice (and the client doesn't like).

Any other suggestions to fixing this would be appreciated.

You could try with ImageCache Actions module. Enable Imagecache Canvas Actions module that is shipped with ImageCache Actions and than change your style effects order to:

Scale
Define canvas (set your color and scale dimensions)
Crop


How to have display suite extra show up as layout options when creating blocks? What I do now is create a content item.

Choose a layout.

Create content.

Use Node as Block to show as a block.

Would it be possible to have display suite extra show up for layouts when creating a block? So the block can have layouts?

May I suggest a different setup?

I would go for DS + Bean, that would allow you full Display Suite capabilities in your Drupal.
It will effectively give you block types that you can manage like nodes (Fieldable as well as managing their Display View Modes using DS).
Plus, the world of BEAN is wonderful => https://www.drupal.org/node/1475632
And it made it into core in D8 for a reason!

Here is two quick screenshots (after 30 seconds of clicking):

Manage display for a block type

Add a new block (using a new Block Type called Standard) via Content>>Add Block>>Standard.

Hope this helped, even though it deviated from the OP a tiny bit!


How to hook into user authentication? I have a 2FA option that users can enable. I am currently writing API layer where I want to preserve this functionality but so far I haven't been able to find a point where I can hook into authentication. The \Drupal\user\UserAuth does not invoke any hooks or events so I am wondering if the only solution is to completely swap the user.auth service for a custom implementation?

PS: my thinking is that if the 2FA is enabled, I would be checking a custom header.

I'm assuming this is Drupal 8 so my answer is for Drupal 8.

You need to do two things:

Create a service provider in your custom module that extends ServiceProviderBase.  The name of this class must be your module name, in camel case, plus "ServiceProvider", i.e. MyUserAuthenticationModuleServiceProvider.  Then, implement the alter function which sets the class for the user.auth service, like this:

    public function alter(ContainerBuilder $container)
    {
        $definition = $container->getDefinition('user.auth');
        $definition- >setClass('Drupal\my_module\AuthenticationClass');
    }

The class you specify in the call to setClass above has to extend \Drupal\user\UserAuth and implement the following function, which returns true/false based on successful authentication

public function authenticate($username, $password)


drupal_set_title not changing the navigation bar title I have changed the title of a path with the drupal_set_title() function from hook_page_alter from a custom module. It works but the title in the navigation bar is still the previous one.

How can I change it too?

Sounds like you're setting the title too late in the theme building process for this to work, possibly using at the node layer which only affects the node title not the page title. What you want to make sure to do is use a preprocess_page function to set the title so this is in the header as well:

function mytheme_preprocess_page(&$vars){
    if (isset($vars['node'])) {
        drupal_set_title('YOUR TITLE');
    }
}

Alternatively, you can install the Page Title which gives you granular control over all of your page titles and is often recommended for SEO.


Create an advanced search that searches only on a field with search_api in drupal 7 I've successfully installed the search api module in drupal 7. I installed solar and it works fine. I need to create a custom search form that has various fields and those fields performs search only on the relitive field.

This means that if i have a content type with the following fields:

"job requested"

"previous exerience"

"city"

I want a searchh page with the same fields and when the user enter a value in the "city" field, it searches for that data only in that field: if I search the "city" field for "milan" I want to find only nodes with the word "milan" entered in the field "city" and not with the word "milan" entered in the body.

I think I need separete indexes for each fields, but structure the two forms?

You don't need separated indexes. In you callback handler, you need to build a new SearchApiQueryInterface instance and set conditions on the field using its condition method.

$index = search_api_index_load('custom_index_machine_name');
$query = $index->query(array(
  'language' => $GLOBALS['language']->language,
  'search id' => 'custom-search',
));
foreach($form_state['values']['filters'] as $field => $value) {
  if (!empty($value)) {
    $query->condition($field, $value);
  }
}
$result = $query->execute();


Can I have both Language and Country path prefixes? On our site, paths are all prefixed by language and country. For example:

http://example.com/en/us/about

In Drupal 7, a previous vendor implemented this by using the Persistent URL module, which rewrites all on-page URLs to include the prefix of your choice. PURL was used to add add the country as a prefix to each path. However, it fails when URL Prefix language negotiation is turned on, requiring a core hack to locale.inc to make both work together to avoid the language negotiation from stomping over our prefix:

@@ -462,7 +462,7@@ -462,7 +462,7 @@ function locale_language_url_rewrite_url(&$path, &$options) {

       case LOCALE_LANGUAGE_NEGOTIATION_URL_PREFIX:
         if (!empty($options['language']->prefix)) {
-          $options['prefix'] = $options['language']->prefix . '/';
+          $options['prefix'] = $options['language']->prefix . '/' . $options['prefix'];
         }
         break;
     }

We are rebuilding the site in Drupal 8, and this is one of the things we need to figure out. Obviously, we'd like to avoid having to reinstate some kind of core hack, but by the same token, we can't change the URL structure due to client requirements.

Is there any way we can pass and preserve both language and country information via path prefixes?

you can either use pathauto patterns or pathologic which is still -dev .. to adapt your paths.


Restrict a role to administer certain vocabularies and terms, and remove the access to creating vocabularies As far as we all know Drupal (still in D8) has a lot of issues with permissions and taxonomies.

So I give my user role the permission to Administer vocabularies and terms so he/she be able to access the page at admin/structure/taxonomy but then I want to restrict that role to certain vocabularies (then Vocabulary Permissions Per Role module comes in handy)

The only issue that remains is the Add Vocabulary permission that comes with Administer vocabularies and terms

So here's the question: How can I restrict the user from Creating new vocabulary / Editing existing vocabularies while giving access to maintain other vocabularies taxonomy terms?

"Creating a new vocabulary" is what you do using the URL admin/structure/taxonomy/add, while "Editing existing vocabularies" (say with machine name demotags) is done using the URL admin/structure/taxonomy/demotags/edit.

A possible solution to "restrict" access to these URLs (which seems to be the missing piece you are looking for) is to use the Rules module for this. To do so, have a look at my answer to the question "How to make the permissions of a module more granular?". It includes a rule (in rules export format), which you should be able to use if you apply these minor tunings to it:

Check the Rules Condition about which roles this validation should be applied for (if any, if not remove that condition).
Adapt the Rules Condition with the URLs containing visitors (to match the taxonomy related URLs like in my first paragraph).
You probably don't need the Rules Condition with the "regex" in it (you only have a few URLs to be validated). In that case, you don't need the "OR" part either.
Review the Rules Action (the message you want to show, and the redirect you want to force).


How do I get a node, or a taxonomy term URL knowing the node ID or the taxonomy term ID? I need to render the full URL from a taxonomy term ID.

The generic way is this:

$uri = entity_uri($entity_type, $entity);
$url = $uri['path'];

So for a node, $entity_type would be 'node', and $entity would be the fully loaded node object.

Taxonomy terms are also entities in D7, so the syntax would be similar.


What is the difference between an 'Attachment display' and a 'Global: View area' put into header/footer of a view? I'm trying to decide which should I use. Both can inherit contextual filters, so in my case both of them are good solutions. Except that I already have the other view that I want to put together with the first, so with Attachment I would have to redo the whole other view as a new display of the first, but with View area I could just reuse the other view.

What is the concept behind them? Are there other differences than what I noted above?

Background: View is a view,  a view can have many displays, such as page, feed, attachment, block.

With Attachment display, you can attached one display of a view to another display.   A good video demo can be found by Doug Vann (its a drupal 6 demo, that can relate to drupal 7).

With Global: View area (Drupal 7 only)  you can add a view inside a view header or footer.

This is no huge pro/con of doing it one way over another.    The only thing I can think of is templating a view and styling it. There will be different html tags and classes for you to style.


Node Load performance I have a small question.

If I use Node::Load on the route of the same node for example:
I go to site.com/node/125 and in preprocess I use Node::Load(125), would Drupal load that node all over again? Or is there some part in the code where it loads it without any performance impact?

Entities are statically cached in memory, so there is no performance impact if you load the same entity multiple times within the same request.


Using File (Field) Paths with token value from Entity Reference field I am using Drupal 8.3.1 and using the module File (Field) Paths to define the path and filename.  I want to use the value of a taxonomy field (Entity reference in CCK) in the same content type as part of the filename.  The machine name of the field is field_organization and doing [node:field_organization] produces an href link where I want is just the name of the single value it contains.  How do I get only the term's name instead?

Try to append :value to the field:

[node:field_organization:value]

For a reference field something like this:

[node:field_organization:0:entity:name]

If you want to look up all available tokens install the Token module and go to /admin/help/token.


Add conditional redirect to Views exposed filter (using BEF) I have a view showing a select list of locations. Upon selecting a location the View shows a Google Map with the locations of the current selection.

For certain items in the select list I would like to redirect away from the View to another page.

I have looked at these discussions:

https://www.drupal.org/node/1379492#comment-6273188

How to change programmatically exposed filters in views

But none of them mentions my specific case of conditional redirection.

Any clues very welcome!

A sketch of an idea, for prototyping.
Once this works for you, you could move this javascript code into a render array via form alter. Here are some links for that:

https://api.drupal.org/comment/31448#comment-31448
https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#attached

Prototyping: Inside the header area of your view you can insert a js snippet inside of a 'Global: Text area' field (use the full html text format to avoid stripping of html tags):

And here is an example snippet to get you started, I am targeting the node's status exposed filter from my sample view:

<script>
(function($) {
  $( document ).ready(function() {
    $('#edit-status').change(function() {
      switch($(this).val()) {
        case 'optionA':
          window.location = "https://www.drupal.org";
          break;
        case 'optionB':
        case 'optionC':
          // grouping option together if they have the same target url
          window.location = "https://petrakis.design";
          break;
        default:
          // default code block, simply exit
      }
    });
  });
})(jQuery);
</script>

Hope this helped!


Can't clean URL from custom query parameters I have a client whose company has different branches. The data are retrieved from a DB (not the Drupal one).
For example, the url mydrupalsite.com/branch?branchID=1 should lead to mydrupalsite.com/branch/1, mydrupalsite.com/branch?branchID=23 to mydrupalsite.com/branch/23.
I have created a page for the branches, at which the content will change slightly and dynamically, according to the branch we choose.
 I've tried using InboundPathProcessorInterface(), OutboundPathProcessorInterface() and PathProcessorAlias(), but I can't get rid of the query ?branchID=23, so I only get mydrupalsite.com/branch/23?branchID=23.

Is there any way to achieve that?

I think you can use Redirection Rules in your .htaccess file to achieve this task.

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_URI} ^(/branch)$
  RewriteCond %{QUERY_STRING} branchID=(.*)
  RewriteRule (.*) /branch/%1?  [R=301,L]
</IfModule>

Hope, this helps you.


How to prevent users of particular role to access the content view (node view) of a particular content type? I am using Content Access Module and have rebuild permissions after enabling the module.

After giving restricted access to users having role 'Data Entry Operator'.
I have a content type delivery challan for which I have ticked on the following permissions for the role ABC.
View own delivery_challan content(selected the particular permission for role 'Data Entry Operator' only ) and
View any delivery_challan content(unselected the particular permission for role 'Data Entry Operator')

Here is the screenshot of the permissions set in the content access module.

When I login as user having role Data Entry Operator , I should not be able to view the contents of type 'delivery challan'
But the issue is I am able to view the content
How can I prevent user from viewing this content??

Ok  there was a mistake from my side

the view 'any delivery_challan content' permission was given to
authenticated user.
And by default any user has role authenticated user.
So User having role 'Data Admin Operator' was able to view any delivery challan content as user also has the role 'authenticated user'
So the solution is to remove the authenticated role from the list of roles under the view any delivery challan content


How do I Import users in the database without re-hashing the password I want to import users from one database to another, without changing password.

Suppose the password is saved as $S$DfAoLR.OJWl04tkzgnZeE3TdJHlz6NxBNpArOKhQAewyyHDFDD in the database; I want to save the same value in the database of the other site.

Can anyone suggest me how to achieve this?

Do this :

<?php
require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
$old_hash = md5('password');
$hash_count_log2 = 11;

$new_hash = user_hash_password($old_hash, $hash_count_log2);

if ($new_hash) {
  // Indicate an updated password.
  $new_hash  = 'U' . $new_hash;
}
?>

or you may check LINK1 or LINK2

Or you can directly import the data from one table to another :

INSERT INTO NewTable (ID, Name, Password)
  SELECT ID, Name, md5(Password) AS Password
  FROM OldTable
  WHERE ID BETWEEN 100 to 300

Check LINK once.


Displaying Line Item Fields in a View (SQL Error) I've built a conference registration system using Commerce and Custom Line Item types, and I'm having trouble figuring out how to display my Custom Line Item fields in a View. Here's a short summary of what I've done:

The registration fields (e.g. name, email, etc.) are fields in a
custom line item type.
My product view doubles as a registration form. It displays the fields of my custom line item type as part of the add to cart
form. It also references a custom product type I created for the
conference.
Some of the fields in the custom line type are booleans that trigger rules that add additional related products to the cart (e.g. hotel accommodations, meals, etc.).

I've built a View that summarizes the store's Orders, so that the conference organizer can see all of the Order info without having to know anything about Commerce or the Drupal admin pages. When I add the Line Items to this Order View, only the products show up (both the product referenced in my view, and those added by rules) - the other fields I've created for capturing the registration data (name, email, etc) don't show up.

I've also attempted to make a View that shows only Line Items (filtered to only my Custom Line Item Type), but nothing shows up and I get the following SQL error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'commerce_line_item.uid' in 'field list'

Any help on getting my other Line Item fields to show up, or insight into this SQL error, would be MOST appreciated. Thanks!

(For some brief background, I have built other solutions using Commerce in conjunction with the Registrations module. This has caused a lot of problems, so I am attempting to recreate similar functionality without the Registration module)

I was running into the same problem too. You have to create the relationship "Commerce Line Item: Order ID" and display the field "Commerce Order: Order ID" to get around the mysql error.

You can get the view by importing the following code:

    $view = new view();
    $view->name = 'commerce_line_items';
    $view->description = '';
    $view->tag = 'default';
    $view->base_table = 'commerce_line_item';
    $view->human_name = 'Commerce Line Items';
    $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'] = 'Commerce Line Items';
    $handler->display->display_options['use_more_always'] = FALSE;
    $handler->display->display_options['access']['type'] = 'none';
    $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'] = 'default';
    $handler->display->display_options['row_plugin'] = 'fields';
    /* Relationship: Commerce Line Item: Order ID */
    $handler->display->display_options['relationships']['order_id']['id'] = 'order_id';
    $handler->display->display_options['relationships']['order_id']['table'] = 'commerce_line_item';
    $handler->display->display_options['relationships']['order_id']['field'] = 'order_id';
    /* Field: Commerce Line Item: Line item ID */
    $handler->display->display_options['fields']['line_item_id']['id'] = 'line_item_id';
    $handler->display->display_options['fields']['line_item_id']['table'] = 'commerce_line_item';
    $handler->display->display_options['fields']['line_item_id']['field'] = 'line_item_id';
    /* Field: Commerce Order: Order ID */
    $handler->display->display_options['fields']['order_id_1']['id'] = 'order_id_1';
    $handler->display->display_options['fields']['order_id_1']['table'] = 'commerce_order';
    $handler->display->display_options['fields']['order_id_1']['field'] = 'order_id';
    $handler->display->display_options['fields']['order_id_1']['relationship'] = 'order_id';
    $handler->display->display_options['fields']['order_id_1']['link_to_order'] = 'customer';


Alter markup around a webform I have been trying to alter the markup generated by my webform. .

Example changes which I would like to do:

Add the class "form-horizontal" to the classes under <form class=""/>.
Add the class "input-xxlarge" to each input field.
Remove any markup generated by the webform module (e.g. form-item, webform-component, webform-component-textarea).

I've been trying to override these values with the help of Devel. Using webform-form-[nid].tpl.php, I have the following line before I make any print statements:

$form['#attributes']['class']['0'] = 'form-horizontal';

The issue is that I can not alter the form classes. Any insight that can be shared would be highly appreciated!

Have you tried theme_form_element ?

  Returns HTML for a form element.

This hook is used to alter the thme of form element in Drupal.

Check theme_field as well.

How to theme form element in Drupal 7


Facets: Show more and Show less functionality I am interested in a "Show more" and "Show less" functionality in facets like on this page http://ethicshare.org/publications/ethics?sc=publications
How can I do that?I am using search api.
thanks

Answer:You can select the visible items of the facet on the facet display.
E.g. you can select 3 items to be visible.If the facets items are more than 3,by default will appear a Show more/Show less functionality for the facet.
Hope this is clear.
thanks


How do I get access to fields of a node that a menu item links to? For example, a menu item links to node/5. How do I retrieve that node so I can get its 'description' field?

You could use the menu_get_object() function or the arg() function. One of these 2 functions should do the trick. If i get you right ...


Should I choose Drupal 6 or Drupal 7? I want to use Drupal as a Framework for my application. Apart some modules, such as Image, Imagecache, Views, and Panels, I will make custom modules. I need the best performance and result.

What version of Drupal should I use?

While Drupal 7 is probably the "right" thing to do, there are a few good reasons to stick with Drupal 6.

One is the status of the modules you need.  Drupal 7 versions will be less mature than their Drupal 6.  They may have better features, but may also have bugs.  Some just don't have Drupal 7 versions yet.  You need to go through your modules and make this assessment yourself.

The other is how much legacy code you wish to reuse.  Yes, you can port, but that leads me to my next point.

Most of the projects I work on are sites for clients, and are firm-fixed-cost and firm-schedule.  In my case, I have to be conservative with third-part module choices.  My clients don't care if a project is late because of a bug in a module.  In their eyes, that is my responsibility.  Yes, I can debug modules and provide patches.  But, this takes time and   maintainers don't always accept patches.

All of this weighs into the version choice decision.


Why doesn't drupal.org/download give a link to the Drupal 7 version? Friend asked how to get the latest d7 version. I said go to the Download link, eg under Build > Download and Extend, or under Try Drupal > Download.

He pointed out that it only has a button for d8 download at https://www.drupal.org/download.

Why?

Most likely because they don't want people to be confused by the two different versions and want to simply funnel folks to the latest D8 version.

Here's likely the easiest download link to share for D7 enthusiasts: https://www.drupal.org/project/drupal


Create an "About the Author" box for multilingual sites I'm having a hard time figuring out how to display a simple box containing some info about the author of a node. I have tried drupal's built-in user profile manager and profile2 module but none of these work on multilingual sites as they should...

Profile2 come with a "Profile2 translation" but it seems that it can be used only for fields labels and not for fields content.

Anyone knows a workaround on how to do it?

P.S.: I use the i18n module.

Thank you!

Profile2 is based on Entity and you have 2 ways of translating entities in Drupal.

by creating an instance of the entity for each language : see https://www.drupal.org/node/1280934
by defining some fields that are translatable : see https://www.drupal.org/node/1280632


Author image not rendering in node twig file I have created node for a Article content type. And I am trying to extract out author information in node--article.html.twig file.

I am sucessfully able to fetch out Author name {{ author_name }}, author bio {{ node.Owner.field_bio.value}}.

But I am facing issue to find out author image. When I tried to print {{ kint(author_picture) }} it returned me null. But when I vistited link: http://drupal-site.com/user/2, I can see author image there. I am bit consfused on need help on showing author image in node.

Any help is appriciated.

To get the image uri value, try the following:

{{ node.Owner.user_picture.0.entity.uri.value }}


Change Boolean field status on clicking submit button I have placed an additional button to the term edit page, and when the user clicks on the additional ("Archieve") button, the status of the boolean field should change from 0 to 1 in the database.

I have written the following code for achieving the above:

function security_settings_form_alter(&$form, &$form_state, $form_id)
{
    if($form_id == 'taxonomy_form_term')
    {
        dpm($form);
        $form['actions']['push'] = array(
            '#type' => 'submit',
            '#value' => t('Archieve'),
            '#submit' => array('my_custom_submit_function'),
            '#weight' =>25
        );
    }
}

function my_custom_submit_function($form, &$form_state)
{
    $form_state['values']['field_test_button']['und'][0]['value']=1;
    db_query("UPDATE {field_data_field_test_button} SET field_test_button_value = :val WHERE entity_id = :eid",
             array(':val' => $form_state['values']['field_test_button']['und'][0]['value'], ':eid' => $form_state['values']['tid']));
    drupal_set_message(t('Your form has been archieved.'));
}

The above functionality is working fine.

But if the user clicks on the same archieve button again, its status should change from 1 to 0 in the database.

Any idea how can achieve this?

I would do it.

function my_custom_submit_function($form, &$form_state)
{
    //if value is 1, then value=0
    if ($form_state['values']['field_test_button']['und'][0]['value']==1) {
        $form_state['values']['field_test_button']['und'][0]['value']=0;
    }
    else
        //if value is 0, then value=1
        if ($form_state['values']['field_test_button']['und'][0]['value']==0) {
            $form_state['values']['field_test_button']['und'][0]['value']=1;
        }
    //$form_state['values']['field_test_button']['und'][0]['value']=1;
    db_query("UPDATE {field_data_field_test_button} SET field_test_button_value = :val WHERE entity_id = :eid",
             array(':val' => $form_state['values']['field_test_button']['und'][0]['value'], ':eid' => $form_state['values']['tid']));
    drupal_set_message(t('Your form has been archieved.'));
}


Block with entities referenced in a field from current node (of different type) I got 2 different types  of content (Place & Event).
When an Event is created you can define Place (one or more) where this Event will happened (Place are referenced in a field in Event).

With View, I can display a block with the Event attached to the current Place. But I can't display in a block the Place of the current Event (on its page).

You need to add relationship Entity Reference: Referenced Entity for field which is referencing to Place content type and you will see the Place field in fields.

Hope this will help.


display a taxonomy as an image Hi Im using taxonomies for categorize my products with drupal commerce, Im using "Brand" vocabulary for the products I want to display a thumbnail of the brand instead of the name of the brand in text, for use in views when showing the products in a catalog, or in the main page of the product display when editing the display of the product display...

Any idea. Thanks

You can use the Entity Module which will allow you to add an image field to the taxonomy.

Then instead of displaying the term->name you'll be able to display your image.

You can create a field image field_brand_logo and get it this way :

$term = taxonomy_term_load($tid);
$brand_logo = field_get_items('taxonomy_term', $term, 'field_brand_logo');
if (!empty($brand_logo)) {
   $brand_logo_img = field_view_value('taxonomy_term', $term, 'field_brand_logo', $brand_logo[0], array('type' => 'image'));
}

print render($brand_logo_img);


How to use mssql as database for my site running on redhat linux My D6 site is running on linux and I'm using Postgresql as database. but now I want to change mssql as database on windows. how I do that?

Once your new server is running, you only have to do a few things.

Dump the old database (PgSQL)
Convert the dump to MSSQL
Import the dump.

If you search on google you should be able to find tools that will allow you to export convert the dump. This is not perfect but is probably the easiest solution.

Alternatively if that doesn't work, you can create a script that from within Drupal fetches data from one database and then inserts it into the other database, effectively using Drupal/PHP to translate the dump. This is much slower and requires more work, but have less chance of failure.


How to include a form in a listing page? I am displaying a content information page. At the end of the content displaying page i need to display a form.

How shall i do it?

What have I done?

Written a menu callback in hook_menu()
Written a method to collect the information
Registered a theme in hook_theme()
Written hook_preprocess_theme() to register variables
Created a template and assign the variables

By doing all the above, I am displaying the Content Information.

What do I need to do, to display a form at the end of the content?

I have done these thing.

Created a form in a function called content_form() (including logic)
Wrote a submission function (content_form_submit()).

My only todo left is displaying the form at the content information page.

The quick and dirty way to print a form defined by hook_form is to use the drupal_get_form function:

print render(drupal_get_form('content_form'));


Twig: How to access multiple values from node reference field with number_format I'm adding fields to array:

{% for item in content.field_notes | field_target_entity %}
   {% set field_component_pages = item.field_component_pages|view|number_format %}
{% endfor %}

In my scenario the value of item.field_component_pages|view is equal "16", but when I convert it to number with number_format I get value of 1.

I presume the item.field_component_pages|view is not a real value. How can I access field field_component_pages correctly in this case?

You can get it form the value. something like item.field_component_pages.0.value properly works for you

{% for item in content.field_notes | field_target_entity %}
   {% set field_component_pages = item.field_component_pages.0.value|number_format %}
{% endfor %}


Batch processing possible without redirects? I'm using the Views Data Export module for exporting Views as .csv. Standard exports work in most cases, but with larger table only batch exports work.  The problem with batch exports is that the redirects don't work well with systems using load balancing between servers and external caching services.  I'd like to have something like the standard exporting, but processed the same way as batch processing so that PHP memory and execution time limits aren't reached.  I've been reviewing the documentation as well as the Views Data Export module, but I haven't found a way to do this yet.

Redirects work just fine if your infrastructure is set up correctly.  I will assume your issue is that you have a mount point for your public files directory - but not for your temp directory?
If you don't want to make two mount points (three, if you have a private folder), instead have one and just have three folders inside for tmp/ public/ private - then symlink tmp and public (e.g. tmp to /tmp/drupal).
The reason being is that file processes create temporary files which then can't be used by other instances if they're not shared.  The external page cache isn't a factor here as it doesn't care so much about any of this, and I'm going to assume that this is for authenticated users too - so it's actually being bypassed (further assuming it's set up correctly). The load balancer cares even less, it just bounces you between instances unless you're using sticky sessions.  Every instance should have access to the same database, files and cache - there won't be any problem.