How can to make required the fields keywords and description of the metatags module? I have a content type and I am interested in make required the field keyword and field description of the metatags module?  anyone knows how can I do it?

The field title is not required.
The field keywords is required
The field metatags is required.

I am working on drupal 7.

Thanks a lot!!

I was trying this code:

function mymodule_form_alter(&$form, &$form_state) {
    if ($form['#form_id'] = 'article_node_form') {
        $form['#validate'][] = 'mymodule_form_validate_fields_metatags';
    }
}

function mymodule_validate_fields_metatags ($form, &$form_state) {
     if (($form['#metatags']['metatags']['description']['value']) == '') {
        form_set_error('Description', t('The field Description is required'));
      }
      if (($form['#metatags']['metatags']['keywords']['value']) == '') {
        form_set_error('', t('The field Keywords is required'));
      }

 }

this code generate an error : NOtice: undefined index.

I have tried this code and not print dsm:

mymodule_form_alter(&$form, &$form_state) {
    if ($form['#form_id'] = 'article_node_form') {
        $form['#validate'][] = 'mymodule_form_validate_fields_metatags';
    }
}

function mymodule_form_validate_fields_metatags ($form, &$form_state) {
dsm("hello");

 }

if no print hello how can test the form_state?  I don't understand what is my error.  Thanks for your help in advance.

You can use code similar to the following in a custom module/theme:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['metatags'])) {
    if (isset($form['metatags']['description']['value'])) {
      $form['metatags']['description']['value']['#required'] = TRUE;
    }
    if (isset($form['metatags']['keywords']['value'])) {
      $form['metatags']['keywords']['value']['#required'] = TRUE;
    }
  }
}


Search only for the currently active language How can I restrict the results from a default search in Drupal 7, to bring only the nodes that are in the current language?

My website has a three language switcher; the user chooses what language he wants to use when viewing the site. If he searches something, the result page bring results from other languages. Today I have only 3 enabled languages, but we plan to expand this to 6 or more.

There's a really elegant way to do this using the apparently undocumented hook_query_node_access_alter():

function yourmodule_query_node_access_alter(QueryAlterableInterface $query) {
  $search = FALSE;
  $node = FALSE;

  // Even though we know the node alias is going to be "n", by checking for the
  // search_index table we make sure we're on the search page. Omitting this step will
  // break the default admin/content page.
  foreach ($query->getTables() as $alias => $table) {
    if ($table['table'] == 'search_index') {
      $search = $alias;
    }
    elseif ($table['table'] == 'node') {
      $node = $alias;
    }
  }

  // Make sure we're on the search page.
  if ($node && $search) {
    $db_and = db_and();
    // I guess you *could* use global $language here instead but this is safer.
    $language = i18n_language_interface();
    $lang = $language->language;

    $db_and->condition($node . '.language', $lang, '=');
    $query->condition($db_and);
  }
}

Note: this code is 100% based on the excellent Search Config module.

User's vs Content language

Some sites might have language detection configured to show the interface in the user's preferred language, while the page content is shown based on the URL or content language.

In that case, consider replacing

$language = i18n_language_interface();

with

$language = i18n_language_content();


Show specific fields in a list to everybody, but only registered user can see that node My Drupal version is 7.50.

I want to show to anonymous user a list with a specific fields (title, image, body abstract), but when you click in title, the content of that node would only be available to registred users.

I tried combining Views to make that list with "Node Access" to limit access to node... but I'm lost. Surely, I'm doing something wrong.

Any suggestion about it? Thanx!

I think Field Permissions is right module for you.

  Features

  Enable field permissions on any entity, not just nodes.
  Role-based field permissions allowing different viewing patterned based on what access the user has.
  Author-level permissions allow viewing and editing of fields based on who the entity owner is.
  Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields
  where this feature is needed.
  Field permissions overview


Content types - custom view I know there is option to preview content type after save. But i want to customise that preview by my css..i want to use image i upload to content type as background and put text on it from content as well. I am learning about modules/themes but i dont know the right way to do this. Opinion of someone experienced would be nice. Thanks a lot!

You need to use tokens and custom CSS in the view.  Takes a little fiddling to get it perfect, because Drupal throws in a bit of it's XHTML.


Deleting the files associated with my node is VERY slow I've got a node which has around 50 files associated with it. The files are stored on Rackspace Cloud Files. Interacting with Cloud Files was very slow, but I've fixed that now and the actual delete operations are running very quickly now. However, there is sometimes a gap of 3-5 seconds between each attempt to delete a file. I added some logging to the unlink() method so I could track how fast the requests were happening.. here is an abbreviation snippet of the log:

[11:55:31 2012] starting to delete rcf://videos/thumbnails/1702/thumbnail-1702_0001.png
[11:55:31 2012] deletion complete

[11:55:36 2012] starting to delete rcf://videos/thumbnails/1702/thumbnail-1702_0002.png
[11:55:36 2012] deletion complete

[11:55:40 2012] starting to delete rcf://videos/thumbnails/1702/thumbnail-1702_0003.png
[11:55:40 2012] deletion complete

So, each delete operation is taking essentially no time, but in between each call to unlink() there is 4-5 seconds. This continues for the remaining files, so it takes SOOO long to delete a node and I'm in danger of the php process being killed for running too long.

Why would drupal be so slow in between file deletes? What might cause this? Where can I look to determine what is taking so long?

I edited the cloudfiles.php API from Rackspace to uncomment the following line:

define('RACKSPACE_SERVICENET', 1);

That automatically causes the API to connect over the private network which is a lot faster than accessing cloudfiles via the public network.

This is only usable if you are hosting your site on a Rackspace server though.


How to use hook_form_alter to change the cancel link I am trying to accomplish a very simple thing - changing the cancel link in the invite_withdraw_form function - with no success. The function is in this file http://cgit.drupalcode.org/invite/tree/includes/invite.pages.inc#n120 So my custom function looks likes this now:

function my_custom_module_form_invite_withdraw_form_alter($form, &$form_state) {
  debug($form['actions']['cancel']);
  $uid = $form['invite']['#value']->uid;
  $cancel = 'user/'.$uid.'/invites/pending';
  $form['actions']['cancel'] = array(
    '#type' => 'link',
    '#title' => 'Cancel',
    '#href' => $cancel,
    '#options' => array ('path' => $cancel),
  );
  debug($form['actions']['cancel']);
}

It hooks successfully, because I see output of two debugs, the second of which confirms the array has changed from:

array (
  '#type' => 'link',
  '#title' => 'Cancel',
  '#href' => '<front>',
  '#options' =>
  array (
    'path' => '<front>',
  ),
)

to

array (
  '#type' => 'link',
  '#title' => 'Cancel',
  '#href' => 'user/1/invites/pending',
  '#options' =>
  array (
    'path' => 'user/1/invites/pending',
  ),
)

but for some reason when I click the Cancel button it keeps redirecting me to the front page. What I am doing wrong and what is the right code?

I think you're just missing an ampersand (&) in front of $form in the first line of your code.


Favicon settings missing on subtheme config Using Drupal 8 W3CSS Theme 8.x-1.17, I created a subtheme. The subtheme works fine, but on the settings page, the entire #edit-favicon div is hidden; style="display: none" has been added. I can't figure out why this is happening. However, on the parent theme, the favicon is being displayed. In subtheme.info.yml, features and favicon are set to true.
settings:
  features:
    favicon: true

Try setting:
settings:
    features:
        favicon: true
    favicon:
        use_default: false


Load login / register block in custom template I've created my own homepage template [page--front.html.twig] and want to add the drupal default login and register form. I was looking for something like

{% include 'themes/bootstrap/templates/block--system-login.html.twig' %}

But it looks like none of these kind of blocks exist.

If I go to user/login and take a look into the source code (with devel enabled) I also do not see any block hint:

<div class="region region-content">

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'block' -->
<!-- FILE NAME SUGGESTIONS:
   * block--flowers-content.html.twig
   * block--system-main-block.html.twig
   x block--system.html.twig
   * block.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/bootstrap/templates/block--system.html.twig' -->

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'form' -->
<!-- BEGIN OUTPUT from 'core/modules/system/templates/form.html.twig' -->
<form class="user-login-form" data-drupal-selector="user-login-form" action="/user/login" method="post" id="user-login-form" accept-charset="UTF-8">

How can I add the login and register form in my (homepage)-Template? I did not find any useful information related to Drupal 8.

Any help is much appreciated. Thanks!

The user/login page is different from the the user login block. To add the user login form to an arbitrary page, then you would need to add the user login block to a region you want, and configure it to display only on the front page. This can be done using the Block administration page (documentation).


use entityQuery within a Block plugin I'm attempting to use queries within a block plugin to avoid using views for performance purposes.

namespace Drupal\my_plugins\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\Query;

/**
 * @Block(
 *   id = "basic_text",
 *   admin_label = @Translation("Basic Block")
 * )
 */

class Basic extends BlockBase {

    /**
     * {@inheritdoc}
     */
    public function defaultConfiguration() {
        return array(
            'bodytext-submit' => $this->t('Enter text here'),
            'layout' => array('pane-type-submit' => 'box'),
            );
    }

    /**
     * {@inheritdoc}
     */
    public function blockForm($form, FormStateInterface $form_state){
        include 'StyleForm.php';

        $form['bodytext'] = array(
          '#type' => 'text_format',
          '#title' => $this->t('Block contents'),
          '#format' => 'full_html',
          '#description' => $this->t('This text will appear in the block.'),
          '#default_value' => $this->configuration['bodytext-submit'],
        );
        return $form;
    }

    public function blockSubmit($form, FormStateInterface $form_state) {
        $this->configuration['bodytext-submit']  = $form_state->getValue('bodytext');
        }

    public function build(){
        $query = \Drupal::entityQuery('node');
        $nids = $query->execute();
        return array(
            '#type' => 'markup',
            '#markup' => $this->configuration['bodytext-submit']['value'],
        );
    }
}

I ultimately want to be able to perform a query and display a list of nodes that fulfill a certain requirement. As a test I performed an empty query for all nodes without displaying any of the results. But when I add

$query = \Drupal::entityQuery('node');
$nids = $query->execute();

to the build() function. It makes it so I can't render the block. I would like to be able to perform entity queries and display the results within the block.

There are brackets missing:

$nids = $query->execute();

In my block this works:

 public function build() {
   $query = \Drupal::entityQuery('node');
   $nids = $query->execute();

  $build = [
   '#theme' => 'item_list',
   '#items' => $nids,
  ];

 return $build;
}


Make private pdf files Non-Downloadable via absolute url links In a content type I have option for pdf file upload, the uploaded files are stored in private folder.

The uploaded file has absolute url of http://example.com/system/files/abc.pdf

At the moment anyone with the absolute url can download the file (no matter the user roles, access and permissions)

I want to redirect visitors to the front page of the website (instead of downloading) if they use the absolute url of pdf in browser to download it.

So far I tried something with JavaScript something like:

$(document).ready(function() {
  if(window.location.href.indexOf(".pdf") > -1) {
    $(location).attr('href', window.location.protocol + "//" + window.location.host); // Redirect to front page
  }
});

Usually this would do the trick if it was rendered webpage where javaScript is loaded, but it doesn't work with pdf files (as javaScript is not loaded while clicking the absolute url of the pdf file).

I have already tried private files download permission module, but that doesn't do what I want, as my downloadable links are accessible to Anonymous users as well.

Any hints, suggestions, how to accomplish this?

It should be as easy as adding an implementation of hook_file_download() to a custom module:

function MYMODULE_file_download($file) {
  // Add whatever other conditions you need to this, e.g. test the
  // file extension for .pdf
  if (user_is_anonymous()) {
    // Deny
    return -1;
  }

  // Allow
  return file_get_content_headers($file);
}


aegir migration did not update database I am working with aegir 3 (hostmaster-7.x-3.130). After migration of Drupal website from an older platform (drupal version 8.3.7) to a newer version (drupal 8.5.0). Website is sucessfully verified after migration (all drupal modules are updatet as expected). No Error or Warning. Task queue turns green.

However, I figure out that database (as well as drupal entity) updates did not run during the migration, so I have to run "drush updb" and "drush entup" manuelly after the aegir migration.

How can I get aegir-migration automatically updating the database (entity) etc.?

Many thanks and regards

Tom

These operations should be running automatically so there's nothing for you to do; this is clearly a bug.  Let's continue the discussion in the bug report at Aegir migration did not update database.  Hopefully we can track down the problem over there.


Get the total value of the users vote in Rate module I  have added rate module to enable voting on comments and content. But I want to get the total no. of vote got by a users comment and give badges based on that. I have no clue how to do it.

You need to do custom coding to achieve above functionality. Assigning User Badges on Cron run will be a good option. Below steps will help you to solve the problem.

Create a custom module
Implement hook_cron
Get list of users who doesn't have comment votes badge.
Get above list of users comment score using custom query
Loop through results and check for your condition to assign badge
Assign badge using user-badges API. Look into user badges module where it assigns badge to user to figure out logic to assign badge!

Hope it helps :-)


Add javascript to a specific node I want to add some extra javascript (few files stored in my account, and some inline javascript) for a specific node. Based on the answer to this question, I tried adding a few files to the node alias "insert-pub" by doing this in the template.php in /themes/garland (just trying out the garland theme for now):

  function garland_preprocess_node(&$vars) {
     // The line below was already there.
     $vars['submitted'] = $vars['date'] . ' â€” ' . $vars['name'];
     // Added the lines below.
     // Want to include my javascript files and inline scripts for specific nodes.
     $node =& $vars['node'];
     debug($node);
     debug($node->type);
     if ($node->type == 'insert-pub')
     {
          drupal_add_js('/sites/all/scripts/MyLib.js', array('type' => 'file', 'scope' => 'header'));
          drupal_add_js('/sites/all/scripts/Utils.js', array('type' => 'file', 'scope' => 'header'));
          drupal_add_js('var MyAjaxLib=new MyLib();
               function loadInput(){ alert("Hello"); }', 'inline');
     }
}

But I never see the links to the JS files or inline JS scripts in the source of the page, when I load the page in the browser by going to [www.mysite.com/insert-pub]. Where am I going wrong? Even the debug() calls above does not seem to print anything in the browser.

I am a Drupal 7 newbie, so looking forward to some hand-holding. Thanks.

The node type will always have an underscore as the separator (not a dash) between words so the test would be:

if ($node->type == 'insert_pub') {
  // ...
}

But it seems from your question you want to test the URL alias of the node, not the type. To do that you need to use drupal_get_path_alias() to get the node's alias, and see if it matches:

$current_node_alias = drupal_get_path_alias("node/$node->nid");
if ($current_node_alias == 'insert-pub') {
  drupal_add_js('...
}

Make sure you've cleared Drupal's caches so the new preprocess hook can be picked up by the system. That's the only reason I can think of to explain the calls to debug() not working, as they should.


Services CSRF Token request security A Drupal website that my company is maintaining has a REST endpoint, using Drupal Services (likely not that relevant). One of the systems that I'm writing has to write changes in the system to that website over REST. To do this, we first have to 'login' to the system, for which we get a session token and id, and then have to get a CSRF token from this same website. To get this token, we have to make a request to the website, giving the token and id we got earlier. After this, we can use the token and id, combined with the CSRF token, to make edit requests.

But why does having to request this CSRF token first make this system any more secure?

If you are using the services module and the user login endpoint, when you perform the login trough your app you should receive:

sessid
session_name
token
user

(This can be investigated further checking the source code here.)

To make all subsequent calls keeping alive the session you just opened (i.e. as a registered user), you need to send the cookie session value and the csrf token value.

For example:

$ curl http://example.com/app/v1/endpoint --header "Content-type: application/json" --header "Accept: application/json" --header "X-CSRF-Token: X-_xz1fu5eSyHeBPqExAPDg4CdZKlHdiW6Lr7SP3N3Y" --header "Cookie: SESS40c98733719ab6b30c22a4545524a6cc=VWcWeGkTF7xgeMyoQwx5CGPHzIhttUUwmcwq_usiimk"

In theory you shouldn't need to make an extra call just to get the CSRF token, because it is already returned in the first response.


How to implement properly a view of nodes displaying other referenced nodes with no duplications? I know that this has been asked several times with different variations, but I cannot seem to find an optimal solution, so here we go again:

I have a content type 'Parent' and a content type 'Child'. The relation between the two is one-to-many i.e. there is a field within the 'Parent' CT called 'children' which is of type 'Entity Reference' and allows for multiple values. Now, I want to create a view that will fetch 'Parent' nodes and for each resulting row I want to display the respective children nodes. Something like this:

    -----------
    Parent 1
    - Child 1
    - Child 2
    -----------
    Parent 2
    - Child 3
    - Child 4
    ----------

Solutions I have found and explored so far:

1. Use a Relationship for the 'Child' nodes within the 'Parent' view

OK, I can now use the 'Child' node fields, but instead of having them grouped within the 'Parent' node row, I end up with one row per relationship and duplicate content

    -----------
    Parent 1
    - Child 1
    -----------
    Parent 1
    - Child 2
    ----------

How should I remove the duplicate content?

1.1 Use a 'distinct' in query options. Naturally, it does not work, because distinct is applied to the whole row and since parent-child field tables are joined, each row IS actually distinct

1.2 Use aggregation. Again the desired result cannot be achieved, since by grouping by Parent nid I will only get the first Child node reference

1.3 Use module views_distinct. OK, this seems to do the job, but it breaks the pager and the results counter as processing is done after the respective view queries have been executed

2. Use a views_field_view, so that respective 'Child' nodes are fetched by a separate view (via Contexual filter) and embedded gracefully within the 'Parent' node row.

OK, this definitely does the job, and I get no duplicates since the child field tables no longer participate in the Parent view query, BUT:

it is not performance optimal
performance gets worse considering that my project has 30 different views (for different content types) that need to function similar to the 'Parent' view in this example
since I already have 30 "main" views, I would hate to create another 30 ones only to be used as field views for the "main" ones

3. Do the job manually: use a 'Global: Custom text' field, use the template "views-view-field--parents--nothing-1.tpl.php" and implement the whole logic there i.e. re-load the Parent node, get the Child node ids, load the Child nodes and print their desired fields. OK, this does the job too, BUT:

it is not exactly the "Drupal way" of coding against views
once again, there are performance issues since I bypass Drupal and load stuff on my own
once again, I will have to implement 30 template files named like "*nothing_1" for each of my views

So, my question is the following:

Is there a solution for this issue other than the ones that I mention here? If not, then which one should I choose and how to overcome its disadvantages?

You can fetch the 'Parent' nodes with their 'Children' nodes with the default functionality of views and without the use of Relationships, Aggregation or other modules.

The Steps Are:

Create a view of 'Parent' content type.
In the 'Fields' section add the field 'Content: Title' and the field 'Content: Children(Appears in: node:parent)'.
In the 'settings' of the 'Format' section  select as 'Grouping field Nr.1' the 'Content: Title' field.
In the field 'Content: Children' select the display format that you want.
Finally 'Exclude' from display the 'Title' field.

Enjoy


Bootstrap CDN over-rides my custom CSS files I have a modest site that I was hired to help customize with some CSS features, however I am noticing a problem.

Bootstrap has its own mini-file that tells it what to style its navigation bars with and at the moment, because of that, my nav bar text is grey. Its contrast compared what the site owner wants is very poor and so I attempted to change this to black.

However in doing so, because I am using CDN, bootstrap files seem to override my custom CSS template files. Is there a way to resolve this issue? I have searched for answers but have yet to find any, please help. Thank you.

Your custom css needs to be more targeted to override the default boostrap css. On line 38 replace ".navbar-nav" with the following:

.navbar-default .navbar-nav>li>a


I get an AJAX error when I install Drupal 7: Why? I tried to install Drupal 7.10, and when the installation has done 28/29 modules, an error occured:

  An AJAX HTTP error occurred.
  HTTP Result Code: 200
  Debugging information follows.
  Path: http://localhost/drupal/install.php?profile=standard&locale=en&id=1&op=do
  StatusText: OK
  ResponseText: ( ! )
  Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\www\drupal\includes\database\mysql\database.inc on line 153
  Call Stack:

Time Memory Function Location
10.0004371192     {main}()                             ..\install.php:0
20.0043834504     install_drupal()                     ..\install.php:26
30.95958976424    install_run_tasks()                  ..\install.core.inc:79
41.929419997120   install_run_task()                   ..\install.core.inc:342
51.930720117440   _batch_page()                        ..\install.core.inc:452
61.931520124560   _batch_do()                          ..\batch.inc:80
71.931520124560   _batch_process()                     ..\batch.inc:161
81.933320214776   call_user_func_array()               ..\batch.inc:284
91.933320214800   _install_module_batch()              ..\batch.inc:284
101.933320215000  module_enable()                      ..\install.core.inc:1538
112.990422114008  module_invoke()                      ..\module.inc:448
122.990422114224  call_user_func_array()               ..\module.inc:794
132.990422114360  standard_install()                   ..\module.inc:794
1420.519725138960 user_role_grant_permissions()        ..\standard.install:400
1529.936125151208 MergeQuery->execute()                ..\user.module:3030
1629.938825159880 DatabaseTransaction->__destruct()    ..\user.module:3030
1729.938825159880 DatabaseConnection->popTransaction() ..\database.inc:1872
1829.938825159912 DatabaseConnection_mysql->popCommittableTransactions() ..\database.inc:1105

Can anyone help me to fix it?

The problem is the  maximum execution time being exceeded. To fix this, you should change the maximum execution time in your php.ini file. Click on the Wamp icon on the taskbar, select PHP -> php.ini, find "max_execution_time" and change it from 30 to like 100-300, to make sure even the slower scripts get their job done before the timeout.

Remember to restart the server after you change the settings.


OAuth expires_in time I want to add the expires_in time to the database when a user authorizes linkedin to store the token. https://www.drupal.org/project/linkedin

I have added token_expires

$sql = array(
    'uid' => $account->uid,
    'token_key' => $oauth['oauth_token'],
    'token_secret' => $oauth['oauth_token_secret'],
    'type' => 'access',
    **'token_expires' => $oauth['oauth_token_expires'],**

and have modified the query, but it does not store the record.

$uid = db_query("SELECT uid FROM {linkedin_token} WHERE token_key = :token_key AND token_secret = :token_secret AND type = :type ", array(':token_key' => $oauth['oauth_token'], ':token_secret' => $oauth['oauth_token_secret'], ':type' => 'access', ':token_expires' => $oauth['oauth_expires_in']))->fetchField();

I would like to store the expiration time to the database that is returned from OAuth

It appears to me that you are directly editing the sources of the linkedin module. This is considered bad practise, as any module update will remove your changes and subsequently lead to unexpected errors in your Drupal.

The reason why the queries do not work is that the corresponding database fields are missing.

You have to do several steps:

Create your own custom module. (I use MYMODULE as name in the following examples; alter that to your module's name.)

Add the linkedin module as dependency to your custom module's .info file, to make sure your changes will be removed before the linkedin module will be uninstalled:

dependencies[] = linkedin

Implement hook_install() within your module's .install file to add the field to the database:

/**
 * Implements hook_install().
 */
function MYMODULE_install() {
  // Add additional field to table 'linkedin_token'.
  if (db_table_exists('linkedin_token') && !db_field_exists('linkedin_token', 'token_expires')) {
    db_add_field(
      'linkedin_token',
      'token_expires',
      array(
        'type' => 'int', // I suppose, you will save a unix timestamp.
        'description' => 'Token expiry date/time',
      )
    );
  }
}

Implement hook_uninstall() within your module's .install file to remove the field from the database when your module will be uninstalled:

/**
 * Implements hook_uninstall().
 */
function MYMODULE_uninstall() {
  // Remove additional field from table 'linkedin_token'.
  if (db_table_exists('linkedin_token') && db_field_exists('linkedin_token', 'token_expires')) {
    db_drop_field(
      'linkedin_token',
      'token_expires'
    );
  }
}

Implement hook_schema_alter() within your .module file to publish your changes to Drupals database schema information:

/**
 * Implements hook_schema_alter().
 */
function MYMODULE_schema_alter(&$schema) {
  $schema['linkedin_token']['fields']['token_expires'] = array(
    'type' => 'int',
    'description' => 'Token expiry date/time',
  );
}

Copy over the altered functions / code snippets from the linkedin module to your module, and rename the functions to MYMODULE_your_function_name. Afterwards restore the original module's source code.

Implement hook_menu_alter() to alter the menu callbacks of the linkedin module to point to your customized functions. (Refer to function linkedin_menu() to identify the items of question.)

/**
 * Implements hook_menu_alter().
 */
function MYMODULE_menu_alter(&$items) {
  if (isset($items['the path of the menu callback to alter'])) {
    $items['the path of the menu callback to alter']['page callback'] => 'MYMODULE_your_function_name';
  }
  // Repeat the above step for every menu callback you like to change.
}

An additional note: Try rewriting as less as possible code from the original module's functions and check whether you can utilize hooks or do a call to the original function as well to make sure the application won't break once the original module is updated.


REST API POST: User is not authorized despite being admin I'm working on a quick script as a proof of concept to POST content to my Drupal instance using the REST API.

The user I'm trying to post as is an Administrator, but I get an error that they don't have permission to create the Content.

Here's the simple script I'm using so far (removed a lot of debug and extra code for brevity). It gets a CSRF token, constructs the JSON body and POST's the request to the REST endpoint to create a piece of content of the game type.

<?php

$autoloader = require_once __DIR__ . '/../../vendor/autoload.php';
use GuzzleHttp\Client;

$client = new Client([ 'base_uri' => $url ]);

$csrfResponse = $client->request('GET', '/rest/session/token');
$csrfToken = trim($csrfResponse->getBody());

$jsonPayload = [
    'type' => 'game',
    'title' => [[ 'value' => 'Test Game ' . strtotime('now') ]],
];

$postResponse = $client->request('POST', '/entity/node?_format=json', [
    'auth' => [$user, $password],
    'body' => json_encode($jsonPayload),
    'headers' => [
        'Content-Type' => 'application/json',
        'X-CSRF-Token' => $csrfToken
    ]
]);

debug("Status Code: " . $postResponse->getStatusCode());
debug($postResponse->getBody());

Problem: I get 403 Forbidden response telling me:

{"message":"You are not authorized to create this node entity of bundle game."}

This despite the fact that the user is an Admin (and I even tried giving them explicit permission to Create and Review contents of the Game type). I get the same error if I put in a bogus username and password as well.

The answers suggested in the related question about "403 Forbidden when creating a page with RESTful API" did not work for me.

My problem was that the Basic Auth module was not enabled. I only found that out by chance as I was scrolling through the enabled modules, as the error message above didn't indicate how authentication was being done.


After restoring the database from the live site to development site, the administrator users fails to log in I want to refresh my DEV site with data from LIVE site.
(both sites have same modules because I play with new modules on my DEV site before I install/enable modules on the LIVE site).

I have set the database configuration to be exactly the same (except localhost for my dev site).
So I dump my database from live site and restore it on my dev site.
(I know I miss some files but I don't care about that.)
All is fine: I can view the dev site with data from the live site, until I try to login as administrator. There is no way to login, no error message; I am simply not logged in.
The password for the administrator user is the same on both the sites, of course.

I checked the hash of the passwords which are different in table users.
I assumed it was due to some salt, so I also copied the salt from sites/default/settings.php
It does not help: The administrator login is still impossible.
Then I reset the admin password on my dev site as explained in http://drupal.org/node/1023428, but it doesn't help: There is no way to log in.

What did I miss?

When login fails, you shall get the following error message:

  Sorry, unrecognized username or password. Have you forgotten your password?

You say:

  There is no way to login, no error message; simply I am not logged in.

This suggest that the problem is not with the admin passord, but something else (i.e. your restored site is somehow munged).  In that case, you need to start restoring it from scratch.

Resetting the password will not help if the site is munged, but for the record:

There are several ways to reset the Drupal admin password.  Here they are, sorted from the simplest to use to most difficult:

Request a reset password link sent via e-mail (the most used method).
drush upwd admin --password=<new_password> (as already mentioned by develkar).
./scripts/password-hash.sh <new_password> (as you've found out yourself).

Usually, all of these works.  The shell-script method (#3) is very similar to the drush method (#2), but unlike drush, the shell-script method requires you to insert the generated password hash in the database yourself (using phpMyAdmin or similar tool).


Dropdown field listing all roles Is there a way to populate a content type field with the custom roles registered in Drupal (minus authenticated and anonymous)???

I have googled and found only quick hacks using custom modules, etc. Any ideas?

If your looking for a module then there is Role Field that creates a new field type that allows you to choose from the list of roles.


How to show in different positions exposed filters in a View? I would like to design my view in this way:

EXPOSED FILTER1             EXPOSED FILTER2

                            MyView resulting output...........
EXPOSED FILTER 3            ............................

EXPOSED FILTER 4

Which is the cleanest way to do it? I would like to avoid to absolute positioning items in css.

Another way to do this is using Panels or cTools Page Manager (comes with cTools, you'll find the Page Manager UI under Structure > Pages in D7). It takes a bit of learning but, like Views, it's very powerful and once you're used to it you won't want to go back. Here's the basic step by step:

Give your view a Context view display. A "Context view" is a type of View Display like a "View block" or a "View page" or an "Attachment view" etc. Create one with the "Add" button at the top of the View edit page.
Load it as a Context in Panels or Page Manager. These are systems for placing content that you can think of as like a smarter, more powerful version of Drupal's Blocks system. The thing that is special about Context views, is that systems built on cTools contexts (like Panels and Page Manager) can load the view early on in the process, analyse it so they know what types of data to expect, and do smart things with that fine-grained data. In the Contexts page for your Page Manager page or Panel, add a context, choose Views, then find the right view.
Choose a layout on the Layouts page. In your case, a "2-column layout" should allow you to create the exact layout you are looking.
Place each part of the view as Content. Because cTools is loading the View as a context, and because cTools knows what Views are and how to make sense of them, it knows exactly what elements of the view it's going to get (unlike a Views block where it can only dump down the whole rendered block as one unit). When you go to Content in the Panels / Page Manager interface, you'll find a 'Views Context' vertical tab with various bits of your view in it, including th exposed flters. You can place each of these anywhere in your view (multiple times if needed), and configure them where appropriate. Some things this allows you to do:

(as per the question) Place each individual exposed filter anywhere you want on the page, seperate to the 'View row' option which contains the View results. For your layout, if you chose a 2-column layout, you can add three exposed filters using the cog icon on the left column, add the fourth to the right column, then add "View row" (no limit or offset in settings page) to get the results of the view. All this is editable: you can drag and drop, disable and enable, edit, add CSS classes, etc
Place the Header or Footer of a view anywhere on the page seperate to the View content
Build sophisticated grids with your Views content, placing the Views Row content type lots of times with different limits and offsets. For example, you can have a column showing the first row with custom classes making it highlighted, then a column showing rows 2-5, then alongside that column a column showing rows 6-10...


How to add more Fields using Form Api I want to add an add more button to an element in Drupal form (using Drupal Form API). Should I make it with javascript (append a new element) and check for $_POST in submission or is there another solution in Drupal API.

This is my code for that field, I want users to be able to upload more than one image:

$form['product'] = array(
  '#title' => t('product'),
  '#type' => 'managed_file',
  '#required' => TRUE,
  '#default_value' => variable_get('product', ''),
  '#upload_location' => 'public://',
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
    'file_validate_size' => array(0.6*1024*1024),
  ),
);

Use Drupal's AJAX Form functionality to add elements to a form from the client.

If you try to update a Drupal form with JavaScript on the client side, it will not be submitted correctly. Drupal knows what was in the form when it was sent to the client, and expects that same structure to be sent back. Therefore, you need to use AJAX to tell Drupal the form is updated (with more fields, etc.).


Dashboard like module that works with Panels Dashboard module lets users change the dashboard according to their preferences. IS there a similar module which does the same for panels.

For example.

An admin user decides which blocks should be available on a particular page.
Each user can decide the order in which these blocks should be shown for him and whether they should be shown at all.

Dashboardify

  Dashboardify is a module for creating complex dashboards.

  Each user with proper permissions can add any block to dashboard and
  rearrange blocks order on his or her dashboard page. There is one
  dashboard with predefined regions available for each user. User can
  add unlimited instances of the same block which can be useful for
  views blocks with different contextual filters applied. Along with
  block information module stores data what contextual filters were used
  while adding block to dashboard. Block order is autosave via AJAX.

Panel Dashboard

  Allows users to locally rearrange and roll up panes on the panel and
  save the state per account. Global state of the panel is not modified
  in the process.

Total Control Admin Dashboard

  The Total Control Admin Dashboard creates a default panel page with
  useful administration tools. Its purpose is to create a central
  location from which a Drupal site can be properly cared for. Several
  overview panes are included for site stats and quick reference.
  Several administration panes are provided with quick links to content
  types, menus, taxonomy, and other scattered locations of important
  Drupal site administration. Several views panes are also provided as
  well as full-page comprehensive versions of the views with bulk
  operations. Each views panel pane is customizable via it's pane
  settings, or override the default views provided to suit your own
  needs.


Prepopulate a custom user field on registration? I have created a custom field on the user entity. I would like to prepopulate this field with the value 0. So, when the user goes to their account page after registration the field is already filled in, which they are then free to change. Just like the username and email. The only way I can think to do this is to alter the registration form. I added this to my module, but when I created a new user, a new row did not appear in the field table. My module function:

function MYMODULE_form_user_register_alter(&$form, &$form_state, $form_id) {
  $form['account']['field_MYFIELD'][LANGUAGE_NONE][0] = array(
    '#type' => 'value',
    '#value' => 0,
  );
}

Where am I going wrong, or is there a better approach. Thanks.

Value field is only used for hidden purpose, it will not populate to user. Check below link

https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#val


Path associated to Views I used Pathauto to create URLs for my nodes like gallery/[node:title].

I created a view with an argument, and the path is gallery/% (% is the node title), but when I point my browser to that URL, I get the standard node, not the view.

How can I override the paths to get my view on that path?
How can I increase the weight of views.module?

I think the best option here is to actually let Panels take care of this. Install panels, create a variant of the node view panel for the specific node type(s) you want, and then place the view on the panel page. There are a few other options (hook_menu_alter(), using hook_url_alter() to rewrite the node links rather than using pathauto), but I would definitely go the panels route.


Unable to override theme function I am trying to override the 'link_field' theme function in the Link module. I've put this function in my template.php of my active theme and have cleared the cache, but its not overriding. What am I doing wrong?

 function tma_corp_link_field($vars) {
  dpm($vars);
  drupal_add_css(drupal_get_path('module', 'link') . '/link.css');
  $element = $vars['element'];
  // Prefix single value link fields with the name of the field.
  if (empty($element['#field']['multiple'])) {
    if (isset($element['url']) && !isset($element['title'])) {
      $element['url']['#title_display'] = 'invisible';
    }
  }

  $output = '';
  $output .= '
';
  if (isset($element['title'])) {
    $output .= '
' .      drupal_render($element['title']) . '
';
  }
  $output .= '
' . drupal_render($element['url']) . '
';
  $output .= '
';
  if (!empty($element['attributes']['target'])) {
    $output .= '
' . drupal_render($element['attributes']['target']) . '
';
  }
  if (!empty($element['attributes']['title'])) {
   $output .= '
' . drupal_render($element['attributes']['title']) . '
';
  }
  if (!empty($element['attributes']['class'])) {
   $output .= '
' . drupal_render($element['attributes']['class']) . '
';
  }
  dpm($element);
  return $output;
 }

So to help keep your theme files cleaner, the preference is to place theme overrides in a custom module. This allows you to switch themes without having copy, paste, and rename a bunch of code.

Also this may be your only choice if, for example, you're trying to override a theme function that's being called from an admin page, you have an admin theme enabled, and you don't want to bother with creating a subtheme for your admin theme.

The workaround here is to use hook_theme_registry_alter(); see this page on Drupal Stack Exchange.


Overlay zoomed image in node? How can I implement a zoom functionality on my content nodes? Like I need to put a zoom button next to my image and clicking it brings a floating zoomed image over the page like it's done here. I'm using Drupal Commerce.

I know that it can be done through Colorbox or Lightbox2 but these modules only function in Views (or not?). How can I put this functionality on my node (product page)?

I have themed my custom node.tpl.php template for the product display page.

I have achieved this on a node before using Fancybox by setting up an image preset for your thumb size that opens with Fancybox. For the image to link to Fancybox you need select a Fancybox image preset under display settings for full node within your content type.

Make sure you initialize the plugin before activation using the appropriate jQuery selector.


How to migrate multilingual content from CSV to Drupal 8? I come from read Using the new Drupal 8 Migration API / Module and Content Migration: CSV to Drupal 8 the process to create a migration is very clear and its works, but I can't find how to migrate content to a Multilingual site. In the Migrate API overview I can't find any information about this.

So, how can I migrate multilingual content?

UPDATE:
I found an example: https://github.com/drupal/drupal/tree/8.3.x/core/modules/migrate/tests/modules/migrate_external_translated_test

I was able for the moment to migrate the english content but not the translations.

you need both migration-tasks, the yml files in the migration folder:

migrate.migration.external_translated_test_node.yml
migrate.migration.external_translated_test_node_translation.yml

Then in the Plugin (MigrateExternalTranslatedTestSource.php), you need to read your .csv (in initializeIterator()) into the structure of the import array:

  /**
   * The data to import.
   *
   * @var array
   */
   protected $import = [
    ['name' => 'cat', 'title' => 'Cat', 'lang' => 'English'],
    ['name' => 'cat', 'title' => 'Chat', 'lang' => 'French'],
    ['name' => 'cat', 'title' => 'Gato', 'lang' => 'Spanish'],
    ['name' => 'dog', 'title' => 'Dog', 'lang' => 'English'],
    ['name' => 'dog', 'title' => 'Chien', 'lang' => 'French'],
    ['name' => 'monkey', 'title' => 'Monkey', 'lang' => 'English'],
   ];


Ignore Special Characters from Expose Filter How I can ignore special characters from expose filter.for example: I have a view with expose filter ( Title ) but if I write the text without special characters it returns ( No Result ) & if write the text with those special characters I have resulted.

Note: When I created the node I wrote the Title with special characters

Example: I created a node with Title (i'ts)
if I searched in expose filter by using (its) it returns(No Result) but if I wrote (i'ts) it works fine

in hook_form_alter function you can check the expose form and write your below function.

function clean($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

return preg_replace('/[^A-Za-z0-9-]/', '', $string); // Removes special chars.
}

assign value to form value array.


How can I avoid users can change the "Make revision" field? My users can edit any content, but I really need to know what they did. I need revisions.
I tried the Hide revision module, but when the Make revision field is unchecked, the revision isn't created. They see that field, they uncheck it, and the revision isn't created.
How can I avoid they uncheck that field?

You can try Hide Revision field module with this patch. See issue [#3001097]


Appache solr results multi sites search sorting based on specific feild i have four sites and use appache solr module to execute search indexing in these four sites ,
all is ok with me , but the results sort not as i want

i want to sort by fields ......for ex:- get all result that have [field 1] first , then get all results that have [ field 2] ....

in my case , i have some results from [ field 1] then [ field 2] then [field 1] , ....
for note (my field type is taxonomy term and all contents in all four sites are the same )

Thanks

A quick Solution may be to use Apache Solr Sort Module.

  Per environment setting of grouping per content type/taxonomy/field
  value/... Allow for a custom amount of items per group (global)

But the best way is to setup a Apache Solr View :

Search API, has a Solr integration module, which will allow you to setup a View with exposed filters and full text search. With the flexibility of Views, you should be able to setup the view to allow the users to sort as they wish.


JavaScript running before page fully loaded I can not figure out why JavaScript is running before the page is loaded.  The specific thing I'm waiting on is some images so that I can get their height.

The JavaScript is loaded via hook_preprocess_page(): drupal_add_js(path_to_theme(). '/js/smooth-accordion.js');.

Thanks for any help!

(function ($) {

Drupal.behaviors.listen_to_open = function(item) {
    // item height
    var bodyHeight = item.find('.accordion-body-inner').height();
    var imgHeight = item.find('.multi-image-wrapper li:first img');
    var targetHeight = bodyHeight > imgHeight ? bodyHeight : imgHeight;
    console.log(imgHeight.height());
    item.find('.product-showcase-open').click(
        function(){
            item.find('.multi-image-wrapper').animate({
                height: targetHeight + "px",
            })
            event.preventDefault();
        }
    )
}

Drupal.behaviors.smoothAccordion = {
    attach: function (context, settings) {
                    alert('doh'); // alerts before any text or images appear on page
        var $items = $('.accordion-item-wrapper');
        $items.each(
            function() {
                Drupal.behaviors.listen_to_open($(this));
            }
        )
    }
}
}(jQuery));

Drupal attach behaviors get called from a jQuery ready() callback upon initial page load (it is a little more complicated than that, though).  This means that the DOM is ready, but replaced elements may not be done loading.  Images are considered replaced elements, so your have a loading bug.

I get around these by using something like imageloaded, or manually attaching via $(window).bind('load', ...);, which will run when the whole page is done loading (including images).


How to rotate views in module? I have created a views that works as a slider (title, image, read more).

And now I need some slideshow sow it rotates the views content from newsest to oldest with some transition animation.

I want to use the existing Views I have created and styled already, just to fade out fade in or some more fancy animation.

Any advice how to do that? Any views additional module that can do that?

Try Views Slideshow

  Views Slideshow can be used to create a slideshow of any content (not
  just images) that can appear in a View. Powered by jQuery, it is
  heavily customizable: you may choose slideshow settings for each View
  you create.


How to count the total number of cores in apache solr 3.5? I am using apache solr 3.5 for one of my Drupal 7 sites. As per a requirement i am supposed to count the total number of cores present in the solr. I am using multicore instance. Is there any option by which i can get the number of cores?

You can find it in your server where solr is hosted in /admin, you will see every core or if you've access to the server you will find it in.

/var/lib/solr/cores/ each folder can be a core.


Entity alteration to prevent entity from being indexed by search_api I'm using search_api/search_api_solr, and would like to be able to exclude certain nodes from being indexed by Solr at all.  In looking at search_api.api.php, I see this text:

  Please be aware that generally preventing the indexing of certain items is
  deprecated. This is better done with data alterations, which can easily be
  configured and only added to indexes where this behaviour is wanted.
  If your module will use this hook to reject certain items from indexing,
  please document this clearly to avoid confusion.

I'm just getting into the whole entity API, so it's not so "easy" for me to do this.  I'm thinking that he's referring to hook_entity_property_info_alter(), and I've used that to add a property to an entity so it is available as a facet and field available in search results.  However, I'm not seeing how to alter the entity so that I can control whether it is indexed by search_api or not.  Can someone point me in the right direction?

Thanks.

When he says "better done with data alterations" he is referring to the "Data Alterations" fieldset / section in the "Workflow" tab for each index in the UI and that is accessible in code through hook_search_api_alter_callback_info().

You can see a patch that uses this (it doesn't use the hook but the original function because it is being added to the actual search_api module but you get the idea) to not index unpublished nodes: http://drupal.org/node/1507882

I think his audience for this comment is other contributed module makers. You can imagine it would be extremely confusing for a user if certain items didn't get indexed because a module they turned on used that hook.

If you are trying to exclude nodes from being indexed (be aware that you can use the "Node Access" data alteration which will keep unpublished nodes from being returned for searches for users who don't have content editing access) you can use that hook checking for the node ids and unsetting them as in the example function.


Complex order form presented as series of linked screens [Somewhat new to Drupal Commerce and Webform; trying my best to construct this question in a clear way]: The project involves order forms for a combination of fee-charged workshops and also a series of no-fee workshops where the person needs to make 2 choices among 6 options but must rank them by preference (in case they can't get their top choice). So there are several kinds of choices the person needs to specify. Then the form needs to collect a wide variety of info, not just basic contact info. Finally it needs to collect payment for the items requiring it.

I already have a Webformbased structure that does all these things. (Although maybe not very efficiently.) It all exists on one page, using collapsible fieldsets to keep the initial view of the page simple and to have everything in one place. It makes sense to me, but for the new user I think it may be confusing.

I am thinking, it would be "better UX" if the various parts of this ordering process were divided into smaller chunks. I am thinking, either pages or maybe modal windows that are clearly and boldly identified as Step 1, Step 2, etc. and with the option to go back if desired. The results from each page or modal window would of course need to be compiled as part of the same order.

Is there a path to this sort of order form structure via existing modules, or is this a custom code project?

It was a lack of useful earlier search results that led to posting the question. But often the query just needs the right search term. In this case, it's exactly "multistep" or "multi-step." That finds this, which along with the ensuing discussion and comments, answers the question quite well:
https://www.drupal.org/node/324779

So, the capability was already there in Webforms, I just hadn't seen how to use it.


How can I create a collapsible block from page content using .tpl file? I'm using the FlickrGallery module - http://drupal.org/project/flickrgallery and its basic functionality is pretty great - it automatically pulls in photosets from the Flickr account and displays everything using shadowbox, which means it'll work on iPhones, iPads, etc. Once the user uploads a photoset on Flickr, it simply appears on the site - no fuss, no muss. And it's also domain-sensitive, so different subsites can have different galleries. Like I said, pretty great - except for one major issue:

The module works outside of Drupal's content system - it simply pulls in a page and everything's hardcoded. The problem is that the page displays all photosets and there's no way to limit the photosets displayed, by paging or otherwise.

I want to create a multimedia page with collapsible blocks for photos and video - the video is no problem using Collapsiblock, but with a large number of photosets, the user will need to scroll down to the bottom of the page to see all available content.

Here's my question: How would I place the page content into a collapsible block using the module's .tpl file? Any ideas greatly appreciated - this is my first post on Drupal Answers!

Here's the existing template (with a few mods):

<?php
/*
 * Available vars:
 * - $description: Containing the description of the FlickrGallery module you provided at the settings page
 * - $albums: Array that contains the image and titles with links
 */
?>

<?php print $description; ?>

    <?php foreach ($albums as $key => $album) : ?>

        <?php print $album['image_link']; ?>

        <?php print $album['title_link'];  ?>

<?php print $album['total'] . t(' Pictures'); ?>

    <?php endforeach; ?>

It would be great to call the code for collapsiblock - thanks for any ideas here!

i'm pretty sure all the core js and css files should handle both the collapsing and styling of the fieldset. you could simply add the fieldset into your code. however, if it is not added in by default for some reason you can use the following addition to your function code.

drupal_add_js('misc/collapse.js');
drupal_add_js('misc/form.js')

Below should be an opened fieldset example.

    <?php print $description; ?>

    <?php foreach ($albums as $key => $album) : ?>
     <fieldset class=" collapsible collapsed">
     <legend>More Info</legend>

         <?php print $album['image_link']; ?>

         <?php print $album['title_link'];  ?>

         <?php print $album['total'] . t(' Pictures'); ?>

   </fieldset>
  <?php endforeach; ?>

To have it closed simply add collapsed to your class like <fieldset class="collapsible collapsed">


Array of items as contextual filter in Views I need to create a View which displays content of users that their username should be passed as contextual filter. The number of parameters (usernames) are not specified but the View must include every username that is passed via url, as an example

example.com/some-path/user1
example.com/some-path/user1/user2
example.com/some-path/user3/user2/user12

the view must include all of pathes like the above ones and filter the contents but I really have no idea how to implement this using Views UI. I can do this programmatically by looping through each component of the url but I don't want to use such methods.

All you need to check "Allow multiple values" true by click on More toggle part of contextual filters field works well.

example.com/some-path/user3,user2,user12


Exporting and importing a view from a custom module From my understanding you can export your views and content types to a module so that you can replicate the view and content type on another server. My question is, if I export the view to a module and write the views api in my module, will the view/content type show up under the structure menu, if so would any changes made there be reflected back in the code of the module, or does this require another export and saving the output back into the module code?

Thanks

Content types and Views are 2 different things. It's your job as a module developer to keep the two in sync over time.

Some modules can help with this such as the Features module, if you dont want to track all this by hand every time.


How can I change the title tag in header of just one page? I tried Page Title module however it seems that it can configure page titles only on the content type level.

I can make a temple for this page and write the title directly in there but I don't feel like overriding the template file just for the title tag.

Is there any other way to set the title to just one specific page (node view page)?

You can manage this in template.php file.

function MYTHEMENAME_preprocess_page(&$vars) {
    $vars['title'] = $custom_title;
    $vars['head_title'] = $custom_title;
}

Just put the condition in the page like for specific path, content type etc. and change the title of the page.

function mytheme_preprocess_page(&$vars){
    if (isset($vars['node']) && $vars['node']->type == 'news'){
        drupal_set_title('News');
    }
}


drupal 7: showing main menu links to anonymous users I have successfully enabled the toboggan present login form on access denied (403), however am not sure how i can set my links to be visible to anonymous users. I used views to create the pages and limited access to users with view published content privileges. Problem is if i do not allow anonymous users to view published content in the permissions section the links will not show.

I have tried content access and ACL but they allow anonymous users to view the content. And i can't use the path /?q=user in the text field, titled, Page Not Found 403(access deneid). Any suggestions?

Summary -: I want to show main menu links to pages (e.g. articles) to anonymous users but i want them to be redirected to the log in page when they click the links.

First you need to install the Chaos tool suite (ctools) module, and enable the Page Manager module, and go to admin/structure/pages

Then we need to wrap whatever we are linking to in a Page, handled by the Page Manager. Exactly how we do that will differ a little bit depending on what we are linking to. The page manager contains many options, and I cannot describe all of them in detail here. You may want to watch this video introduction if you have never seen page manager or panels before. Videos 1 to 3 together are less than 30 minutes, and are likely necessary to make sense of the instructions below.

For nodes: Enable the node template.

For Views: Click "Add custom page", add the View in that page instead, and save.

For Module defined pages: Use Page manager existing pages to hand them over to the page manager.

For Something else entirely: Comment on the answer and tell me what it is, and I'll add instructions.

Now, in the Page manager interface for the page you enabled/created above do the following

Create a variant of type "HTTP response code".
Set the response code to 301.
Set the path to /user
Go to "Selection rules" in the left menu
Add "User:role" == "anonymous user"
Save


Pass term id from menu to views block first post, here goes, I want to get the tid from the taxonomy/term/% taxonomy menu to look up a query on a cck  table to pass an array of nids to filter a views block view. I can get the tid of the term being viewed and I can get the view to accept an array of nids, just can't figure out the bit in between. D6 BTW, got panels if that makes it any easier! Some of the stuff I have read says its easier done with panels. But I'm stumped!

If what you want to do is create a list of nodes (or fields of nodes rather) that have a certain $tid, you would create a view, probably filter it on node type and if it's published, put $tid in as an argument to further filter things based on it, select whatever fields in the nodes that pass all of these you want displayed, and then over on the top left of the form, add a block display, name it whatever you want, save it all, then go into your Blocks admin page and put that block in whatever region of your theme you want. (Or at this point use panels, but I don't, so don't know how lol) And take a couple breaths in between all of these steps :)

ADD:  Check out the http://mustardseedmedia.com/podcast/episode31 video as Bob there answers in great depth how to adjust your views to do what I think you are attempting here, and can answer all the details you need a lot easier than me going into that detail here.


Custom module .install does not create table in database I want to create database table for my custom module.

Inside mymodule.install I have:

function mymodule_schema(){
    $schema['a_visits'] = array(

    'description' => 'visits table',
    'fields' => array(
        'id' => array(
            'description' => 'make id primary key auto increment',
            'type' => 'serial',
            'not null' => TRUE,
        ),
        'oferta' => array(
            'description' => 'nazwa oferty',
            'type' => 'varchar',
            'length' => '255',
            'not null' => TRUE,
        )
    ),
    'primary key' => array('id'),
    );
    return $schema;
}

function mymodule_install() {
   drupal_install_schema('a_visits');
}

function mymodule_uninstall() {
   drupal_uninstall_schema('a_visits');
}

Then I've moved the module's file to server under sites/all/modules/custom/mymodule and enabled it via admin panel. Unfortunately no table in database has been created (the module is listed as active now).

hook_schema alone is sufficient to create database tables. I assume you are just disabling and then enabling the module which will not help you to create tables in the database.
To get it working, admin/modules' locate your module and disable it. Then navigate to 'admin/modules/uninstall' and again locate your module and uninstall it.
After this, go toadmin/modules', and enable your module.
Now you can find the respective tables in your database.

You can also use drush for the same.
drush dis module_name, then
drush pm-uninstall module_name and finally
drush en module_name.

Also, as per @OPTASY Canada, do check your dblog for any warning or error.


Add a form between shipping method selection and order review I'm coding a custom module to make shipping by a delivery enterprise which is not having a module compatible with Drupal commerce.

So, I give the customers a choice between 2 shipping methods:

colissimo (a French official delivery method) using an existing module
exapaq using the custom module I am trying to create

This is working, but exapaq doesn't deliver to customer's home; it delivers to stores where customers can have their order.

So, after customers select the shipping method, I would like to test which is selected and, if this is exapaq, add a new form to allow customers select the store to take the order.

The problem is that I don't have any idea on where can I do this test and how I can insert a new form before to go on order review page.

The payment panes makes this kind of interaction possible through a "details form" that open when you select the payment method that has this configured, and this is great because everything happens on the same page via ajax. But i don't know if Commerce Shipping has this too.
If not, i think that the best way for you to make this is to create a Checkout Page specific for your Shipping Method and create a Checkout Pane with your form to be in this page.

You can take a look at how https://drupal.org/project/commerce_correios handle this situation, because it's a Shipping Method too, so the API should have a lot in common with what you need.


simplenews subscription form on front page with frontpage module I want to place a Simplenews subscription form on my front page that I implemented using the Front Page module in 'full' mode. How do I do this?

Try this:

<?php $block = module_invoke('simplenews','block_view',5); print render($block); ?>

The number 5 shouldn't be sent as a string.

And if you are putting this in a textarea on Drupal's backend, you need the PHP input filter, which is generally a bad idea.  Better to go through the theming system, add a region, and put the block there.

http://drupal.org/node/1088718


Linking to files inside Drupal I've been asked to create an intranet at work and thought I'd look at Drupal to get this done. What they want to have is a few blogs, a calendar, a forum as well as a link to all of the documentation that staff are required to be able to access to do their jobs, such as a phone list (in .xls format) and a ton of .pdf files that contain policies and procedures.

I have D7 installed on a 2008R2 server, the same server that contains all of the data. This server doesn't face the internet, so security doesn't have to be too deep.

Anyway, how would I create my site in Drupal so that I can point to the directories on the file server (which everyone can access to read)? I'm ok with a directory listing, it doesn't have to be fancy.

I had explored creating a directory inside of my site then having the files sync between the data drive and the www data store. I looked into having the site tie into our AD infrastructure but it's going to be setup so only a few can add to it and everyone else can read. The forums will be for certain staff (5 or so) to be able to bat around ideas.

I'm not sure what kind of answer you are looking for ...

If you just want these files stored remotely, but accessible from drupal you may want to look at these modules:

Filedepot
MediaMover
Migrate

I actually have a similar criteria on a site. Serve pdf file listings from a non-drupal directory to allowed users -- essentially a simple directory listing. Here is how I did it in D7 with a bit of custom coding.

I make a symlink from a remote filesystem into like DRUPAL_SITE_DIR/sites/default/files/REMOTE_MOUNTPOINT
Make a custom module that uses something to scan for files and show them to the enduser. You can use D7 file_scan_directory if you like, I actually opted for Symfony's Finder Component. The advantage to Symfony's finder is things like "show files of X size", "sort by something" or doing more complex search filters (which I will need) or truely different types of remote files (FTP, S3, etc). Example code for a module poorly named "views_fs" can be found in this public Gist.

Hope this info helps.


How do I import configuration without getting these errors? I am using drush cim and drush cex for importing and exporting the  configuration between environments.

At this moment, local and develop are working OK, but I am getting an error on stage.

This is the error.

  The import failed due to the following reasons:
  This config does not have system.site, rejected
  UUID source site does not match current site.

  Config core.extension does not exists.

But actually both of them exists. I have already ran drupal config.override and set the UUID on system.site, but I am still getting those errors.

I have also tried drush cr.

The system site has the same UUID as local. It's the same file.

I have fixed the issue using config suite module: install this module and it will assign the uuid for those enviroments so you don't need to worry to set up manually.


Views, Grouping by various levels of granularity in a date field? I'd like to group a nodes in a view by date, but more specifically, I'd like Grouping field Nr.1 to be year and Grouping field Nr.2 to be the month.

Possible?

At current the test view looks like this:

I'd like it to look more like this

2015

November

ibh Persto Torqueo Vel

October

Commoveo Macto Premo Vel

September

Ad Adipiscing Meus Nutus Tego Torqueo

2012

December

Antehabeo Decet Pala Populus

April

Quadrum Si Suscipit

Well I think I got it.

Step 1: Add two new date formats

I set up two new date formats: Month only and Year only

Step 2: Query the date date field twice under the new formats

Add the Publication Date field twice in these newly created formats

Step 3: Apply the proper grouping to the view

Here's how I grouped it....

And finally, the results

Below, albeit poorly formatted, I have two two years of 2015 and 2014 with sub divided months.

(For some reason, what ever the last grouped field is encapulated in . I tried playing with the formatting but no luck. However, I've worked out my logic here.)


Adding custom variable to $user object I am using the following to add a custom field to a user with a custom variable.

global $user;

$account = user_load($user->uid);

$language = ($user->language) ? $user->language : 'und';

$edit = array(
  'field_favourite_football_team' => array(
    $language => array(
      0 => array(
        'value' => 'Manchester City',
      ),
    ),
  ),
);

user_save($account, $edit);

Problem: I can see the outputted value on module A but on module B, when I dump or print out that global $user, I can't see that field. Is there anyway to save that on a for global use?

To add a field to the user entity, you need to visit the menu entry Administration > Configuration > People > Account Settings > Manage Fields. You can then define the field properties (including specifying whether it appears on the registration form or not) and customize how it is displayed on user pages.


How to display field revisions? I want to keep field revisions: I want to see who changed a field to which value and when. Currently I can keep node revisions, but in the revisions tab, it only shows title and body changes.

How can I also keep field revisions?
How can I display revisions preferably like this:

User 1 changed Color: red to Color: green
User 2 changed Color: green to Color: white

Is the second one achievable by Views?

I came across a similar issue and found your post last week. After a bit of searching around I found this module:

https://drupal.org/project/track_field_changes

It appears to cover what you were looking for in terms of functionality as well as what I was trying to cover. I've since installed the module and set it up, but unfortunately whilst some of it is working for me I can't get a view to display the 'value after' or 'value before' fields (See https://drupal.stackexchange.com/questions/81507/how-to-display-values-in-the-value-after-value-before-fields-track-field).

If you still need this functionality perhaps try out the module - if you have success with it let me know as it's still not quite working fully for me, but that could be down to user-errors perhaps.

All the best

Tom


How to restrict access to private files to members of an organic group? I have an organic group with a file field that stores its files in a private directory (sites/default/files/private/).
These files are visible only to members of that group. But, as is commonly known, if someone guesses the Drupal path even if he is not a member of that group or not even logged in, he can access that file by using the correct file link directly.

How can I restrict file access to group members?

OG provides no access control on attached files.  I ran into the same situation and came up with two options.

The file depot module integrates nicely with OG and does prevent users who are not members of a group from accessing files that are attached to a group.

  The filedepot module is full featured Document Management module that has a google docs like feel. It fulfills the need for an integrated file management module supporting role and user based security. Documents can be saved outside the Drupal public directory to protect documents for safe access and distribution.

Another option is writing a custom module that implements hook_file_download().  In that module you would have to get the node id of the file attachment then use that to determine what group the node belongs too then from there determine if the logged in user is a member of the group.  If they are not a member of the group the module would return -1 which would give them access denied if they try to directly download the file via url.


How to properly call drush command from another drush command? I have a drush command that does some stuff and at the end of its execution I want to invoke twig-compile --uri=foobar.com. When I call drush_invoke('twig-compile') I get error about unknown arguments(those were passed to my drush command). I tried things like this before invoking the command drush_set_context('options', ['uri', 'foobar.com']); but no success yet.

How should I reset the options so twigc won't complain about them or how do I invoke the twigc command directly with the uri argument?

If you use drush_invoke, you should first use drush_set_option('strict', FALSE); to turn off strict option checking for the subcommand.  drush_invoke runs a subcommand in the same process, which can be more efficient; however, there are a number of ways that this can go wrong, so it is often better to use drush_invoke_process instead, to run the subcommand in its own process.  If you do this, there is no need to disable strict option handling.

drush_invoke_process('@self', 'twig-compile', $args, $options);.


Using Node Limit, Show Role How Many Nodes They Can Still Add Using Node Limit and have limited roles to be able to add 3, 8 or 20 nodes of one content type depending on what they register with.

I wondered if it's possible to show how many of their limit they have left and then show it on their user page.

So if they have created 3 nodes, they have 5 left (if they had the 8 role allowance).

I checked the node_limit module and you need to create an api to be able to get the remaining limit for a particular role or user.

The number of limit and limit id are stored on node_limit table.
Your limit id and role id are stored on node_limit_role table.

What you need to do next is count the number of nodes the role or user has created.

Now you need to alter the user profile to print the remaining limit. See the api that you can use here.


Changing date format in monthly archive in Views I created a view which summarise the nodes and displays them in a year + month block. The result looks like this:

március 2015 (26)
február 2015 (12)
január 2015 (18)

I'd like to change the date format according to Hungarian standards:

2015 március (26)
2015 február (12)
2015 január (18)

I tried to find the appropriate settings in date/time settings (admin/config/regional/date-time) without any success.

Create a template file of your view Display output: views-view--view-post-by-date--block.tpl.php

Make some slight changes where row is printing in your tempalate file:

         <?php if ($rows): ?>

         <?php
   $output = '';
 for($i=0;$i<5;$i++){
$filter_link = date("Ym",strtotime("-$i months"));
$filter_display = date("Y F",strtotime("-$i months"));
$link = $GLOBALS['base_url'].'/post-by-date/'.$filter_link;
 $output .= ''.$filter_display.'('.count($filter_display).')
';

  }
print $output;
// print $rows; ?>


How to remove a Required Field based on other field value i have a form with two fields, FieldA (Select List) and FieldB (Select List, required field).

How to set the FieldB to optional when FieldA has certain value in order to pass the form validation?

Try using the #states attribute: a structured array describing the different JavaScript states that can be applied to the element when certain conditions are met. Please read the extensive description of this feature at drupal_process_states()


Display Only the Product Add to Cart Button Drupal 8.4.2

On both the commerce-product and the node--product level, I can get the add to cart button to show, but it also renders the product variation fields as well.

If I have content that does not have variations and only a single price, how can I render just the "add to cart button" in the commerce form?

I've been all through config via the admin panel and feel I am just missing something obvious???

My question would be: How do you render just the add to cart button on the product level, or node level (via reference) via the admin panel?

Yes the link above resolved my question: Where is the "add to cart" configuration?.

There is a sub-menu link that I was missing.

This allowed me control of the display of the form items on both the product and node level. With this I am able to choose to show the variations and quantity fields. Thanks Patrick Kenny!


Views UI options do not work I am building a drupal 7 site.

Lately I made a lot of changes and install many modules.

Currently, when I enter into a view, everything looks fine.
but, when I enter a field settings inside a view, I see that some of the option are not available - meaning the collapsible option is not available.

I tried to replace the views folder on my server with a folder I backed-up 4 days ago.
ran cron, flushed all caches, ran upadte.php - nothing helped.

Can someone please help me solve this issue?

Here is a screen-shot (you can see they are not clickable and not collapsible):

I found the problem.

The problem was an option on the advagg module that move all JS to the footer (which is usually a good thing).

The "All" option was problematic.
when I chose "Disabled" - the views UI worked correctly.

here is a screen-shot:


What is the difference between watchdog Location and watchdog Referrer in dblog messages What is the difference between watchdog Location and watchdog Referrer in dblog messages?

An easy example to see the difference would be nice, for example on the node creation/edit they are the same.In which case these two URLs will be different?

The 'Location' is the URL a user/process was visiting when the watchdog entry was invoked.

The 'Referrer' is the URL that referred the user to the 'Location' URL.

So if a person goes directly from a link on http://www.google.com to http://yoursite.com/, and visiting that URL on your site generates a watchdog record, the 'Location' will be '/', and the 'Referrer' will be 'http://www.google.com'.


How to render protected element? I want to print [entityInfo:protected] present in below image.

I am able to print all element except [entityInfo:protected] and [entityType:protected]

You can't (without reflection). Protected members of a class are available only to the defining class and its subclasses - it's the whole point of using access modifiers in the first place - if you can get access to a protected value directly from the object, then the language has failed. Miserably.

If a method doesn't exist to expose that data already, you'll need to extend the class that represents that object to provide getter methods for the protected properties.


How to add a CSS class to an render array? In a template file, before print render($content['field_image']); I would like to add a CSS class to the image in the $content['field_image'] render array. How can I do this?
Here is the render array:

Array
(
[#theme] => field
[#weight] => 2
[#title] => Image
[#access] => 1
[#label_display] => hidden
[#view_mode] => full
[#language] => und
[#field_name] => field_image
[#field_type] => image
[#field_translatable] => 1
[#entity_type] => node
[#bundle] => ll_basic_page
[#object] => stdClass Object
[#items] => Array
    (
        [0] => Array
            (
                [fid] => 6777
                [alt] => alt text
                [title] =>
                [uid] => 1
                [filename] => imageFile.jpg
                [uri] => public://imageFile.jpg
                [filemime] => image/jpeg
                [filesize] => 28742
                [status] => 1
                [timestamp] => 1314312382
                [rdf_mapping] => Array
                    (
                    )
            )
    )
[#formatter] => image
[0] => Array
    (
        [#theme] => image_formatter
        [#item] => Array
            (
                [fid] => 6777
                [alt] => alt text
                [title] =>
                [uid] => 1
                [filename] => imageFile.jpg
                [uri] => public://imageFile.jpg
                [filemime] => image/jpeg
                [filesize] => 28742
                [status] => 1
                [timestamp] => 1314312382
                [rdf_mapping] => Array ()
            )
        [#image_style] =>
        [#path] =>
    )
)

And this is the HTML output:

I tried adding a class to $content['field_image']['#attributes']['class'], but that didn't work.
Do you have any idea on how I can achieve what I am trying to do?

I believe it would be:

$content['field_image'][0]['#attributes']['class'][] = 'my-class';

Or to assign it to every element,

foreach (element_children($content['field_image'] as $key) {
  $content['field_image'][$key]['#attributes']['class'][] = 'my-class';
}


User View List in Drupal filter by taxonomy In a social website powered by Drupal, Users are allowed to add interest tags into a taxonomy terms by autotagging.

My problem is how to create a view page to list all users based on a certain interest in the term list.

Say, I need to display user interested on PHP.

You can accomplish this using the views module. Its the Drupal GUI way to build queries so you will be able to crate a page that lists all users based on the field you need.

Here goes a really good reference that may help you with that:

http://nodeone.se/en/taming-the-beast-learn-views-with-nodeone

If you prefer to get your hands dirty you can use the Entity Field Query


MIgrate to drupal 7 join related tables I am migrating from a another non Drupal CMS. I have 4 tables:

stories (story1, story2, story3)
story_tags (story_id, tag_id)
tags (ABC, NBC, WTOP, CBS, clinton)
tag_types (radio, tv, person)

How can I link tags to stories by tag_type. So that when I open a story I can see all it's related tags, knowing that a story can have several tags.
Any good detailed tutorial of migrate module link will be appreciated also.

update
How can i translate this in a migrate query

SELECT t.name FROM tags t
    join tag_types tt on (tt.id = 3)
    join story_tags stg on (stg.tag_id = t.id) WHERE story_id = $row_id'

Tried but it is not working:

->select('story_tags', 'tags')
->fields('tags', array('tag_id'))
->leftJoin('tag_types', 'tt', '(tt.id = tag.tag_type_id)')
->condition('tag_type_id', '3', '=' )
->condition('story_id', $row->id, '=')
->execute()
->fetchCol();

What am i missing?

My approach to this would be to have a content type called Story that had 2 taxonomy term references. One tag field could just be called tags and then other could be called tag_types. These 2 fields would be 2 distinct Taxonomy Vocabularies in Drupal.

Drupal 7 actually installs with a tags vocabulary out-of-the-box which is assumed to be free-tagging terms as your legacy site appears to be already using. So you just need to make 1 vocabulary for the tag_types.

Anyways then in your migration class for Stories. Your source SQL statement would figure out the necessary terms for these 2 fields, probably using a sub-select, and the migrate module can set the terms for the content type as Stories are inserted into the system.

So, some psuedocode is:

<?php

class StoryMigration extends Migration
{
  public function __construct($arguments)
  {
    parent::__construct($arguments);
    $query = Database::getConnection('default', 'legacy')
      ->select('stories')
      ->fields('stories', array('pgid', 'page_title', 'page_body'));
    // Create subqueries to get the tags for the story we are on. We will call
    // a fake field in our SQL query as legacy_tags or legacy_tags_type to be
    // passed using Migrate field mappings.
    $query->addExpression('SELECT GROUP_CONCAT(term_name) FROM legacydb_terms WHERE page_id = pgid' ,'legacy_tags');
    $query->addExpression('SELECT GROUP_CONCAT(term_name) FROM legacydb_term_types WHERE page_id = pgid' ,'legacy_tags_type');
    $this->source = new MigrateSourceSQL($query);
    $this->destination = new MigrateDestinationNode('page');

    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'pgid' => array('type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
          'description' => t('Source ID'),
        )
      ),
      MigrateDestinationNode::getKeySchema()
    );

    $this->addFieldMapping('title', 'page_title');
    $this->addFieldMapping('body', 'page_body');

    // Import a story's tag(s). Make the term in the vocabulary if it's not
    // there already, ignore the CaSe of the term so sloppy legacy terms
    // come across as 1 term.
    // By specifying this could have a SEPERATOR VALUE this can create any N
    // terms provided by our SQL statement above.
    $this->addFieldMapping('field_tags', 'legacy_tags');
    $this->addFieldMapping('field_tags:create_term')
      ->defaultValue(TRUE);
    $this->addFieldMapping('field_tags:ignore_case')
      ->defaultValue(TRUE);

    // Similar steps as for the above term, but for the tags_type reference field.
    $this->addFieldMapping('field_tags_type', 'legacy_tags_type');
    $this->addFieldMapping('field_tags_type:create_term')
      ->defaultValue(TRUE);
    $this->addFieldMapping('field_tags_type:ignore_case')
      ->defaultValue(TRUE);
  }
}

Term Reference Fields and the Migrate module are described in the documentation. Adding SQL Expressions to an SQL query is covered in the sql documentation.

My above code is an example and not guarenteed to work. It's simply 1 method of doing this and is to be referenced as an outline. Your SQL schema and php may look different in the end.


Blocking a certain user from apearing in user search results I'm looking for a way to exclude certain users (by ID or name) from appearing in the user search results in Drupal 7.

Any thoughts?

If you're using drupal search out of the box to search users, that should still call implementations of hook_search_page

Build a small custom module that implements hook_search_page, parse thru $results and remove anything you don't want appearing in search results.

function custom_module_search_page($results) {
  foreach($results as $result_index => $result) {
    //do something, maybe detect for a user id
    //and run unset($results[$result_index]); if the criteria is met
  }
}


Configuring the new display modes in Drupal 8 I like very much that in Drupal 8 you can create your own display modes (i.e. not just have "Full" and "Teaser", but create your own) and that you can reference Content via Entity Reference fields within Content. It's really neat and allows me to add arbitrary lists of content on pages and have them render as I like. EXCEPT there seems to be one small issue - the rendered entities always start with the title linking to the Content. There doesn't seem to be any way of getting around it.

Apart from creating my own templates for my display modes, is there any way I can prevent the Title displaying when I render Content in another piece of Content using an Entity Reference? This seems to be an oversight with a very useful bit of functionality - or am I missing something?

As you've found out through comments, the title is currently hardcoded.

The reason for that is that the title isn't controlled by the view mode in the default behavior. It's whether the node thinks he's on his own page vs. not. A behavior that's not easily configurable.

Would have been nice to fix that but like many other things, we didn't enough time.

Apart from using templates to do, you could also consider to use Display Suite, just like in 7.x, it allows you to control the title, pick from different layouts and so on.


Hook_Form_Alter Edit Existing Field Type I am using hook_form_alter in template.php to add datepicker to a field on an exposed view filter.

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

  if($form_id == "views_exposed_form"){
    $form['data_2_op'] = array(
            '#type' => 'date_popup',
            '#date_format' => 'Y-m-d'
        );
    }
}

But all it is doing is adding another field into the form, rather than editing the field I have declared. Is there a way I can just add #type > 'date_popup' to an existing field?

EDIT:

Results after using...

drupal_set_message($form_id);  // print form ID to messages
  drupal_set_message(print_r($form, TRUE));  // print array to messages

views_exposed_form
Array (
  [#info] => Array (
    [filter-combine] => Array (
      [operator] => combine_op
      [value] => combine
      [label] => Search Event ID
      [description] =>
    )
[filter-data_2] => Array (
  [operator] => data_2_op
  [value] => data_2
  [label] => Choose Date [description] =>
  )
[filter-data] => Array (
  [value] => data
  [label] => Data field
  [description] => )
  [filter-data_1] => Array (
    [value] => data_1
    [label] => Data field
    [description] =>
    )
  )
[combine] => Array (
  [#type] => textfield
  [#size] => 30
  [#default_value] => )
[data_2] => Array (
  [#type] => textfield
  [#size] => 30
  [#default_value] => )

hook_form_alter work only with module implementation. So you have to use it in any module not in template.php

Use the above statement in module like

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

  if($form_id == "views_exposed_form"){
    $form['data_2'] = array(
            '#type' => 'date_popup',
            '#date_format' => 'Y-m-d'
        );
    }
}


How to check if a view is grouped? In a views template, I need to check if the views rows are grouped. Which property of the $view object contains this information?

In the example below, $grouped = !empty($options['grouping'][0]); seems to work. However I don't know/understand all details about the $view object and I'm not sure if this really is a solid solution. Will this work in all situations?

Currently, my views-view-unformatted.tpl.php looks like this:

<?php
$grouped = !empty($options['grouping'][0]);
$heading_classes = $grouped ? ' class="group-heading"' : '';
?>

<?php if ($grouped): ?>

<?php endif; ?>

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

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>

<?php endforeach; ?>

<?php if ($grouped): ?>

<?php endif; ?>

Some tips about your solution:

1- It looks right to me. I would try keep the logic separate from the template. I'd also declare my own template to avoid problems. Another style plugin, for example a custom style plugin, could use the original template.

HOOK_preprocess_views_view_unformatted(&$vars){
  if(!empty($options['grouping'])){
    $vars['heading_classes'] = $grouped ? ' class="group-heading"' : '';
    // My own template
    $vars['theme_hook_suggestions'] = 'views_view_unformatted_group';
  }
}

/*
* Implement hook_theme
*/
HOOK_theme($existing, $type, $theme, $path){
  return array(
    'views_view_unformatted_group' => array(
     'variables' => array(),
     'path' => 'PATH/TO/YOUR/MODULE',
     'template' => 'views_view_unformatted_group',
  ),
}

Template views_view_unformatted_group.tpl.php

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

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
  <?php print $row; ?>

<?php endforeach; ?>

2 - The default function that manage the grouping is render_grouping_sets() in an style plugin object. The documentation warn about that:

  Plugins may override this method if they wish some other way of handling
     * grouping

The unformatted list, html list, grid and table style inherit the default methods and they don't override it.

3 - If you have nested groups, Views wrap the parent group with the next function in theme.inc:

function theme_views_view_grouping($vars) {
  $view = $vars['view'];
  $title = $vars['title'];
  $content = $vars['content'];

  $output = '
';
  $output .= '
' . $title . '
';
  $output .= '
' . $content . '
' ;
  $output .= '
';

  return $output;
}


Adding a final review page to entityform, before submit I have a complex entityform, where I'd like the user to see what has been entered on a final "review" page, before the data is written away.

As far as I can see the preview page, on entityforms, is shown AFTER the data is saved.

Can this be achieved?

So to be clear..

Step 1 : User enters data into form, and clicks "Review"

Step 2 : User sees all the data nicely presented, and clicks "Confirm", or "Edit"

Step 3: If Confirmed, data is written away, otherwise go to Step 1

Rob, I created Entityforms.

  As far as I can see the preview page, on entityforms, is shown AFTER
  the data is saved.

Actually when the "preview" page is shown the submission hasn't been saved yet.


Default image only for view I know that I can set default images for content types, but for my page, I would like to only display the default image for one particular view and not the other ones.

It would also be nice if the image is automatically displayed in the proper image style just like a regular image. Therefore it seems that I can't use "no results behavior" since there, I would have to specify the full html myself.

So can I somehow tell drupal 7 to use a default image for a view in case there is no image for an article such that it does not affect any other views?

Assuming you are working with the default Article content type of Drupal 7.x

You should add something similar to this in your NO RESULT BEHAVIOUR of your IMAGE field in your VIEWS


Drupal multi-site not working I am trying to create a sample multi-site drupal on my local machine. I use windows XP and XAMPP.
   For creating a multi-site i created a folder in /sites.
   Like /sites/example.com.
   After that I changed example.sites.php to sites.php and removed # from the line given below.
     # $sites['localhost.example'] = 'example.com';

After that i tried to rum by typing localhost/example.com
it is not installing to the new folder example.com but to default folder.
My drupal 7 files are in htdocs
I need help... Is there anything missing????

A multisite configuration is used when a web server is associated to different domain names, and you want the web site to appear different when accessed from different domains. (If you want the web site appears the same in both the domain, there isn't any special Drupal configuration to follow.)

Suppose that your web site answers to example.com, and example.org. You can have two different settings.php files:

sites/example.com/settings.php for example.com
sites/example.org/settings.php for example.org

In the case those files are not found, Drupal would use the default one (sites/default/settings.php).

The same can be done for subdomains.

On your Mac, you should edit your hosts file (/private/etc/hosts) to add something similar to the following one:

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
127.0.0.1 first.localhost
127.0.0.1 second.localhost

In this case, the following files would be used:

sites/first.localhost/settings.php for first.localhost
sites/second.localhost/settings.php for second.localhost

If those files are not found, Drupal would look for the following ones (and other files as well):

sites/localhost/settings.php
sites/default/settings.php